PassManager.cpp revision 1336a6bf06e64a096217628d2cc9644e48a5d7d6
1//===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Devang Patel and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LLVM Pass Manager infrastructure.
11//
12//===----------------------------------------------------------------------===//
13
14
15#include "llvm/PassManager.h"
16#include "llvm/Support/CommandLine.h"
17#include "llvm/Support/Timer.h"
18#include "llvm/Module.h"
19#include "llvm/ModuleProvider.h"
20#include "llvm/Support/Streams.h"
21#include "llvm/Support/ManagedStatic.h"
22#include <vector>
23#include <map>
24
25using namespace llvm;
26class llvm::PMDataManager;
27
28//===----------------------------------------------------------------------===//
29// Overview:
30// The Pass Manager Infrastructure manages passes. It's responsibilities are:
31//
32//   o Manage optimization pass execution order
33//   o Make required Analysis information available before pass P is run
34//   o Release memory occupied by dead passes
35//   o If Analysis information is dirtied by a pass then regenerate Analysis
36//     information before it is consumed by another pass.
37//
38// Pass Manager Infrastructure uses multiple pass managers.  They are
39// PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
40// This class hierarcy uses multiple inheritance but pass managers do not derive
41// from another pass manager.
42//
43// PassManager and FunctionPassManager are two top-level pass manager that
44// represents the external interface of this entire pass manager infrastucture.
45//
46// Important classes :
47//
48// [o] class PMTopLevelManager;
49//
50// Two top level managers, PassManager and FunctionPassManager, derive from
51// PMTopLevelManager. PMTopLevelManager manages information used by top level
52// managers such as last user info.
53//
54// [o] class PMDataManager;
55//
56// PMDataManager manages information, e.g. list of available analysis info,
57// used by a pass manager to manage execution order of passes. It also provides
58// a place to implement common pass manager APIs. All pass managers derive from
59// PMDataManager.
60//
61// [o] class BBPassManager : public FunctionPass, public PMDataManager;
62//
63// BBPassManager manages BasicBlockPasses.
64//
65// [o] class FunctionPassManager;
66//
67// This is a external interface used by JIT to manage FunctionPasses. This
68// interface relies on FunctionPassManagerImpl to do all the tasks.
69//
70// [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
71//                                     public PMTopLevelManager;
72//
73// FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
74//
75// [o] class FPPassManager : public ModulePass, public PMDataManager;
76//
77// FPPassManager manages FunctionPasses and BBPassManagers
78//
79// [o] class MPPassManager : public Pass, public PMDataManager;
80//
81// MPPassManager manages ModulePasses and FPPassManagers
82//
83// [o] class PassManager;
84//
85// This is a external interface used by various tools to manages passes. It
86// relies on PassManagerImpl to do all the tasks.
87//
88// [o] class PassManagerImpl : public Pass, public PMDataManager,
89//                             public PMDTopLevelManager
90//
91// PassManagerImpl is a top level pass manager responsible for managing
92// MPPassManagers.
93//===----------------------------------------------------------------------===//
94
95namespace llvm {
96
97//===----------------------------------------------------------------------===//
98// Pass debugging information.  Often it is useful to find out what pass is
99// running when a crash occurs in a utility.  When this library is compiled with
100// debugging on, a command line option (--debug-pass) is enabled that causes the
101// pass name to be printed before it executes.
102//
103
104// Different debug levels that can be enabled...
105enum PassDebugLevel {
106  None, Arguments, Structure, Executions, Details
107};
108
109static cl::opt<enum PassDebugLevel>
110PassDebugging_New("debug-pass", cl::Hidden,
111                  cl::desc("Print PassManager debugging information"),
112                  cl::values(
113  clEnumVal(None      , "disable debug output"),
114  clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
115  clEnumVal(Structure , "print pass structure before run()"),
116  clEnumVal(Executions, "print pass name before it is executed"),
117  clEnumVal(Details   , "print pass details when it is executed"),
118                             clEnumValEnd));
119} // End of llvm namespace
120
121#ifndef USE_OLD_PASSMANAGER
122namespace {
123
124//===----------------------------------------------------------------------===//
125// PMTopLevelManager
126//
127/// PMTopLevelManager manages LastUser info and collects common APIs used by
128/// top level pass managers.
129class VISIBILITY_HIDDEN PMTopLevelManager {
130public:
131
132  virtual unsigned getNumContainedManagers() {
133    return PassManagers.size();
134  }
135
136  /// Schedule pass P for execution. Make sure that passes required by
137  /// P are run before P is run. Update analysis info maintained by
138  /// the manager. Remove dead passes. This is a recursive function.
139  void schedulePass(Pass *P);
140
141  /// This is implemented by top level pass manager and used by
142  /// schedulePass() to add analysis info passes that are not available.
143  virtual void addTopLevelPass(Pass  *P) = 0;
144
145  /// Set pass P as the last user of the given analysis passes.
146  void setLastUser(std::vector<Pass *> &AnalysisPasses, Pass *P);
147
148  /// Collect passes whose last user is P
149  void collectLastUses(std::vector<Pass *> &LastUses, Pass *P);
150
151  /// Find the pass that implements Analysis AID. Search immutable
152  /// passes and all pass managers. If desired pass is not found
153  /// then return NULL.
154  Pass *findAnalysisPass(AnalysisID AID);
155
156  virtual ~PMTopLevelManager() {
157    for (std::vector<Pass *>::iterator I = PassManagers.begin(),
158           E = PassManagers.end(); I != E; ++I)
159      delete *I;
160
161    for (std::vector<ImmutablePass *>::iterator
162           I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
163      delete *I;
164
165    PassManagers.clear();
166  }
167
168  /// Add immutable pass and initialize it.
169  inline void addImmutablePass(ImmutablePass *P) {
170    P->initializePass();
171    ImmutablePasses.push_back(P);
172  }
173
174  inline std::vector<ImmutablePass *>& getImmutablePasses() {
175    return ImmutablePasses;
176  }
177
178  void addPassManager(Pass *Manager) {
179    PassManagers.push_back(Manager);
180  }
181
182  // Add Manager into the list of managers that are not directly
183  // maintained by this top level pass manager
184  inline void addIndirectPassManager(PMDataManager *Manager) {
185    IndirectPassManagers.push_back(Manager);
186  }
187
188  // Print passes managed by this top level manager.
189  void dumpPasses() const;
190  void dumpArguments() const;
191
192  void initializeAllAnalysisInfo();
193
194protected:
195
196  /// Collection of pass managers
197  std::vector<Pass *> PassManagers;
198
199private:
200
201  /// Collection of pass managers that are not directly maintained
202  /// by this pass manager
203  std::vector<PMDataManager *> IndirectPassManagers;
204
205  // Map to keep track of last user of the analysis pass.
206  // LastUser->second is the last user of Lastuser->first.
207  std::map<Pass *, Pass *> LastUser;
208
209  /// Immutable passes are managed by top level manager.
210  std::vector<ImmutablePass *> ImmutablePasses;
211};
212
213} // End of anon namespace
214
215//===----------------------------------------------------------------------===//
216// PMDataManager
217
218namespace llvm {
219/// PMDataManager provides the common place to manage the analysis data
220/// used by pass managers.
221class PMDataManager {
222public:
223  PMDataManager(int Depth) : TPM(NULL), Depth(Depth) {
224    initializeAnalysisInfo();
225  }
226
227  virtual ~PMDataManager() {
228
229    for (std::vector<Pass *>::iterator I = PassVector.begin(),
230           E = PassVector.end(); I != E; ++I)
231      delete *I;
232
233    PassVector.clear();
234  }
235
236  /// Return true IFF pass P's required analysis set does not required new
237  /// manager.
238  bool manageablePass(Pass *P);
239
240  /// Augment AvailableAnalysis by adding analysis made available by pass P.
241  void recordAvailableAnalysis(Pass *P);
242
243  /// Remove Analysis that is not preserved by the pass
244  void removeNotPreservedAnalysis(Pass *P);
245
246  /// Remove dead passes
247  void removeDeadPasses(Pass *P, std::string &Msg);
248
249  /// Add pass P into the PassVector. Update
250  /// AvailableAnalysis appropriately if ProcessAnalysis is true.
251  void addPassToManager(Pass *P, bool ProcessAnalysis = true);
252
253  /// Initialize available analysis information.
254  void initializeAnalysisInfo() {
255    TransferLastUses.clear();
256    AvailableAnalysis.clear();
257  }
258
259  /// Populate RequiredPasses with the analysis pass that are required by
260  /// pass P.
261  void collectRequiredAnalysisPasses(std::vector<Pass *> &RequiredPasses,
262                                     Pass *P);
263
264  /// All Required analyses should be available to the pass as it runs!  Here
265  /// we fill in the AnalysisImpls member of the pass so that it can
266  /// successfully use the getAnalysis() method to retrieve the
267  /// implementations it needs.
268  void initializeAnalysisImpl(Pass *P);
269
270  /// Find the pass that implements Analysis AID. If desired pass is not found
271  /// then return NULL.
272  Pass *findAnalysisPass(AnalysisID AID, bool Direction);
273
274  // Access toplevel manager
275  PMTopLevelManager *getTopLevelManager() { return TPM; }
276  void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
277
278  unsigned getDepth() const { return Depth; }
279
280  // Print routines used by debug-pass
281  void dumpLastUses(Pass *P, unsigned Offset) const;
282  void dumpPassArguments() const;
283  void dumpPassInfo(Pass *P,  std::string &Msg1, std::string &Msg2) const;
284  void dumpAnalysisSetInfo(const char *Msg, Pass *P,
285                           const std::vector<AnalysisID> &Set) const;
286
287  std::vector<Pass *>& getTransferredLastUses() {
288    return TransferLastUses;
289  }
290
291  virtual unsigned getNumContainedPasses() {
292    return PassVector.size();
293  }
294
295protected:
296
297  // If a FunctionPass F is the last user of ModulePass info M
298  // then the F's manager, not F, records itself as a last user of M.
299  // Current pass manage is requesting parent manager to record parent
300  // manager as the last user of these TrransferLastUses passes.
301  std::vector<Pass *> TransferLastUses;
302
303  // Top level manager.
304  PMTopLevelManager *TPM;
305
306  // Collection of pass that are managed by this manager
307  std::vector<Pass *> PassVector;
308
309private:
310  // Set of available Analysis. This information is used while scheduling
311  // pass. If a pass requires an analysis which is not not available then
312  // equired analysis pass is scheduled to run before the pass itself is
313  // scheduled to run.
314  std::map<AnalysisID, Pass*> AvailableAnalysis;
315
316  unsigned Depth;
317};
318
319//===----------------------------------------------------------------------===//
320// BBPassManager
321//
322/// BBPassManager manages BasicBlockPass. It batches all the
323/// pass together and sequence them to process one basic block before
324/// processing next basic block.
325class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
326                                        public FunctionPass {
327
328public:
329  BBPassManager(int Depth) : PMDataManager(Depth) { }
330
331  /// Add a pass into a passmanager queue.
332  bool addPass(Pass *p);
333
334  /// Execute all of the passes scheduled for execution.  Keep track of
335  /// whether any of the passes modifies the function, and if so, return true.
336  bool runOnFunction(Function &F);
337
338  /// Pass Manager itself does not invalidate any analysis info.
339  void getAnalysisUsage(AnalysisUsage &Info) const {
340    Info.setPreservesAll();
341  }
342
343  bool doInitialization(Module &M);
344  bool doInitialization(Function &F);
345  bool doFinalization(Module &M);
346  bool doFinalization(Function &F);
347
348  // Print passes managed by this manager
349  void dumpPassStructure(unsigned Offset) {
350    llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
351    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
352      BasicBlockPass *BP = getContainedPass(Index);
353      BP->dumpPassStructure(Offset + 1);
354      dumpLastUses(BP, Offset+1);
355    }
356  }
357
358  BasicBlockPass *getContainedPass(unsigned N) {
359    assert ( N < PassVector.size() && "Pass number out of range!");
360    BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
361    return BP;
362  }
363};
364
365//===----------------------------------------------------------------------===//
366// FPPassManager
367//
368/// FPPassManager manages BBPassManagers and FunctionPasses.
369/// It batches all function passes and basic block pass managers together and
370/// sequence them to process one function at a time before processing next
371/// function.
372
373class FPPassManager : public ModulePass, public PMDataManager {
374
375public:
376  FPPassManager(int Depth) : PMDataManager(Depth) {
377    activeBBPassManager = NULL;
378  }
379
380  /// Add a pass into a passmanager queue.
381  bool addPass(Pass *p);
382
383  /// run - Execute all of the passes scheduled for execution.  Keep track of
384  /// whether any of the passes modifies the module, and if so, return true.
385  bool runOnFunction(Function &F);
386  bool runOnModule(Module &M);
387
388  /// doInitialization - Run all of the initializers for the function passes.
389  ///
390  bool doInitialization(Module &M);
391
392  /// doFinalization - Run all of the initializers for the function passes.
393  ///
394  bool doFinalization(Module &M);
395
396  /// Pass Manager itself does not invalidate any analysis info.
397  void getAnalysisUsage(AnalysisUsage &Info) const {
398    Info.setPreservesAll();
399  }
400
401  // Print passes managed by this manager
402  void dumpPassStructure(unsigned Offset) {
403    llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
404    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
405      FunctionPass *FP = getContainedPass(Index);
406      FP->dumpPassStructure(Offset + 1);
407      dumpLastUses(FP, Offset+1);
408    }
409  }
410
411  FunctionPass *getContainedPass(unsigned N) {
412    assert ( N < PassVector.size() && "Pass number out of range!");
413    FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
414    return FP;
415  }
416
417private:
418  // Active Pass Manager
419  BBPassManager *activeBBPassManager;
420};
421
422//===----------------------------------------------------------------------===//
423// FunctionPassManagerImpl
424//
425/// FunctionPassManagerImpl manages FPPassManagers
426class FunctionPassManagerImpl : public Pass,
427                                    public PMDataManager,
428                                    public PMTopLevelManager {
429
430public:
431
432  FunctionPassManagerImpl(int Depth) : PMDataManager(Depth) {
433    activeManager = NULL;
434  }
435
436  /// add - Add a pass to the queue of passes to run.  This passes ownership of
437  /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
438  /// will be destroyed as well, so there is no need to delete the pass.  This
439  /// implies that all passes MUST be allocated with 'new'.
440  void add(Pass *P) {
441    schedulePass(P);
442  }
443
444  /// run - Execute all of the passes scheduled for execution.  Keep track of
445  /// whether any of the passes modifies the module, and if so, return true.
446  bool run(Function &F);
447
448  /// doInitialization - Run all of the initializers for the function passes.
449  ///
450  bool doInitialization(Module &M);
451
452  /// doFinalization - Run all of the initializers for the function passes.
453  ///
454  bool doFinalization(Module &M);
455
456  /// Pass Manager itself does not invalidate any analysis info.
457  void getAnalysisUsage(AnalysisUsage &Info) const {
458    Info.setPreservesAll();
459  }
460
461  inline void addTopLevelPass(Pass *P) {
462
463    if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
464
465      // P is a immutable pass and it will be managed by this
466      // top level manager. Set up analysis resolver to connect them.
467      AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
468      P->setResolver(AR);
469      initializeAnalysisImpl(P);
470      addImmutablePass(IP);
471      recordAvailableAnalysis(IP);
472    }
473    else
474      addPass(P);
475  }
476
477  FPPassManager *getContainedManager(unsigned N) {
478    assert ( N < PassManagers.size() && "Pass number out of range!");
479    FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
480    return FP;
481  }
482
483  /// Add a pass into a passmanager queue.
484  bool addPass(Pass *p);
485
486private:
487
488  // Active Pass Manager
489  FPPassManager *activeManager;
490};
491
492//===----------------------------------------------------------------------===//
493// MPPassManager
494//
495/// MPPassManager manages ModulePasses and function pass managers.
496/// It batches all Module passes  passes and function pass managers together and
497/// sequence them to process one module.
498class MPPassManager : public Pass, public PMDataManager {
499
500public:
501  MPPassManager(int Depth) : PMDataManager(Depth) {
502    activeFunctionPassManager = NULL;
503  }
504
505  /// Add a pass into a passmanager queue.
506  bool addPass(Pass *p);
507
508  /// run - Execute all of the passes scheduled for execution.  Keep track of
509  /// whether any of the passes modifies the module, and if so, return true.
510  bool runOnModule(Module &M);
511
512  /// Pass Manager itself does not invalidate any analysis info.
513  void getAnalysisUsage(AnalysisUsage &Info) const {
514    Info.setPreservesAll();
515  }
516
517  // Print passes managed by this manager
518  void dumpPassStructure(unsigned Offset) {
519    llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
520    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
521      ModulePass *MP = getContainedPass(Index);
522      MP->dumpPassStructure(Offset + 1);
523      dumpLastUses(MP, Offset+1);
524    }
525  }
526
527  ModulePass *getContainedPass(unsigned N) {
528    assert ( N < PassVector.size() && "Pass number out of range!");
529    ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
530    return MP;
531  }
532
533private:
534  // Active Pass Manager
535  FPPassManager *activeFunctionPassManager;
536};
537
538//===----------------------------------------------------------------------===//
539// PassManagerImpl
540//
541/// PassManagerImpl manages MPPassManagers
542class PassManagerImpl : public Pass,
543                            public PMDataManager,
544                            public PMTopLevelManager {
545
546public:
547
548  PassManagerImpl(int Depth) : PMDataManager(Depth) {
549    activeManager = NULL;
550  }
551
552  /// add - Add a pass to the queue of passes to run.  This passes ownership of
553  /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
554  /// will be destroyed as well, so there is no need to delete the pass.  This
555  /// implies that all passes MUST be allocated with 'new'.
556  void add(Pass *P) {
557    schedulePass(P);
558  }
559
560  /// run - Execute all of the passes scheduled for execution.  Keep track of
561  /// whether any of the passes modifies the module, and if so, return true.
562  bool run(Module &M);
563
564  /// Pass Manager itself does not invalidate any analysis info.
565  void getAnalysisUsage(AnalysisUsage &Info) const {
566    Info.setPreservesAll();
567  }
568
569  inline void addTopLevelPass(Pass *P) {
570
571    if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
572
573      // P is a immutable pass and it will be managed by this
574      // top level manager. Set up analysis resolver to connect them.
575      AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
576      P->setResolver(AR);
577      initializeAnalysisImpl(P);
578      addImmutablePass(IP);
579      recordAvailableAnalysis(IP);
580    }
581    else
582      addPass(P);
583  }
584
585  MPPassManager *getContainedManager(unsigned N) {
586    assert ( N < PassManagers.size() && "Pass number out of range!");
587    MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
588    return MP;
589  }
590
591private:
592
593  /// Add a pass into a passmanager queue.
594  bool addPass(Pass *p);
595
596  // Active Pass Manager
597  MPPassManager *activeManager;
598};
599
600} // End of llvm namespace
601
602namespace {
603
604//===----------------------------------------------------------------------===//
605// TimingInfo Class - This class is used to calculate information about the
606// amount of time each pass takes to execute.  This only happens when
607// -time-passes is enabled on the command line.
608//
609
610class VISIBILITY_HIDDEN TimingInfo {
611  std::map<Pass*, Timer> TimingData;
612  TimerGroup TG;
613
614public:
615  // Use 'create' member to get this.
616  TimingInfo() : TG("... Pass execution timing report ...") {}
617
618  // TimingDtor - Print out information about timing information
619  ~TimingInfo() {
620    // Delete all of the timers...
621    TimingData.clear();
622    // TimerGroup is deleted next, printing the report.
623  }
624
625  // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
626  // to a non null value (if the -time-passes option is enabled) or it leaves it
627  // null.  It may be called multiple times.
628  static void createTheTimeInfo();
629
630  void passStarted(Pass *P) {
631
632    if (dynamic_cast<PMDataManager *>(P))
633      return;
634
635    std::map<Pass*, Timer>::iterator I = TimingData.find(P);
636    if (I == TimingData.end())
637      I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
638    I->second.startTimer();
639  }
640  void passEnded(Pass *P) {
641
642    if (dynamic_cast<PMDataManager *>(P))
643      return;
644
645    std::map<Pass*, Timer>::iterator I = TimingData.find(P);
646    assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
647    I->second.stopTimer();
648  }
649};
650
651static TimingInfo *TheTimeInfo;
652
653} // End of anon namespace
654
655//===----------------------------------------------------------------------===//
656// PMTopLevelManager implementation
657
658/// Set pass P as the last user of the given analysis passes.
659void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
660                                    Pass *P) {
661
662  for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
663         E = AnalysisPasses.end(); I != E; ++I) {
664    Pass *AP = *I;
665    LastUser[AP] = P;
666    // If AP is the last user of other passes then make P last user of
667    // such passes.
668    for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
669           LUE = LastUser.end(); LUI != LUE; ++LUI) {
670      if (LUI->second == AP)
671        LastUser[LUI->first] = P;
672    }
673  }
674}
675
676/// Collect passes whose last user is P
677void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
678                                            Pass *P) {
679   for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
680          LUE = LastUser.end(); LUI != LUE; ++LUI)
681      if (LUI->second == P)
682        LastUses.push_back(LUI->first);
683}
684
685/// Schedule pass P for execution. Make sure that passes required by
686/// P are run before P is run. Update analysis info maintained by
687/// the manager. Remove dead passes. This is a recursive function.
688void PMTopLevelManager::schedulePass(Pass *P) {
689
690  // TODO : Allocate function manager for this pass, other wise required set
691  // may be inserted into previous function manager
692
693  AnalysisUsage AnUsage;
694  P->getAnalysisUsage(AnUsage);
695  const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
696  for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
697         E = RequiredSet.end(); I != E; ++I) {
698
699    Pass *AnalysisPass = findAnalysisPass(*I);
700    if (!AnalysisPass) {
701      // Schedule this analysis run first.
702      AnalysisPass = (*I)->createPass();
703      schedulePass(AnalysisPass);
704    }
705  }
706
707  // Now all required passes are available.
708  addTopLevelPass(P);
709}
710
711/// Find the pass that implements Analysis AID. Search immutable
712/// passes and all pass managers. If desired pass is not found
713/// then return NULL.
714Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
715
716  Pass *P = NULL;
717  // Check pass managers
718  for (std::vector<Pass *>::iterator I = PassManagers.begin(),
719         E = PassManagers.end(); P == NULL && I != E; ++I) {
720    PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
721    assert(PMD && "This is not a PassManager");
722    P = PMD->findAnalysisPass(AID, false);
723  }
724
725  // Check other pass managers
726  for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
727         E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
728    P = (*I)->findAnalysisPass(AID, false);
729
730  for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
731         E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
732    const PassInfo *PI = (*I)->getPassInfo();
733    if (PI == AID)
734      P = *I;
735
736    // If Pass not found then check the interfaces implemented by Immutable Pass
737    if (!P) {
738      const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
739      if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
740        P = *I;
741    }
742  }
743
744  return P;
745}
746
747// Print passes managed by this top level manager.
748void PMTopLevelManager::dumpPasses() const {
749
750  if (PassDebugging_New < Structure)
751    return;
752
753  // Print out the immutable passes
754  for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
755    ImmutablePasses[i]->dumpPassStructure(0);
756  }
757
758  for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
759         E = PassManagers.end(); I != E; ++I)
760    (*I)->dumpPassStructure(1);
761}
762
763void PMTopLevelManager::dumpArguments() const {
764
765  if (PassDebugging_New < Arguments)
766    return;
767
768  cerr << "Pass Arguments: ";
769  for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
770         E = PassManagers.end(); I != E; ++I) {
771    PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
772    assert(PMD && "This is not a PassManager");
773    PMD->dumpPassArguments();
774  }
775  cerr << "\n";
776}
777
778void PMTopLevelManager::initializeAllAnalysisInfo() {
779
780  for (std::vector<Pass *>::iterator I = PassManagers.begin(),
781         E = PassManagers.end(); I != E; ++I) {
782    PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
783    assert(PMD && "This is not a PassManager");
784    PMD->initializeAnalysisInfo();
785  }
786
787  // Initailize other pass managers
788  for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
789         E = IndirectPassManagers.end(); I != E; ++I)
790    (*I)->initializeAnalysisInfo();
791}
792
793//===----------------------------------------------------------------------===//
794// PMDataManager implementation
795
796/// Return true IFF pass P's required analysis set does not required new
797/// manager.
798bool PMDataManager::manageablePass(Pass *P) {
799
800  // TODO
801  // If this pass is not preserving information that is required by a
802  // pass maintained by higher level pass manager then do not insert
803  // this pass into current manager. Use new manager. For example,
804  // For example, If FunctionPass F is not preserving ModulePass Info M1
805  // that is used by another ModulePass M2 then do not insert F in
806  // current function pass manager.
807  return true;
808}
809
810/// Augement AvailableAnalysis by adding analysis made available by pass P.
811void PMDataManager::recordAvailableAnalysis(Pass *P) {
812
813  if (const PassInfo *PI = P->getPassInfo()) {
814    AvailableAnalysis[PI] = P;
815
816    //This pass is the current implementation of all of the interfaces it
817    //implements as well.
818    const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
819    for (unsigned i = 0, e = II.size(); i != e; ++i)
820      AvailableAnalysis[II[i]] = P;
821  }
822}
823
824/// Remove Analyss not preserved by Pass P
825void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
826  AnalysisUsage AnUsage;
827  P->getAnalysisUsage(AnUsage);
828
829  if (AnUsage.getPreservesAll())
830    return;
831
832  const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
833  for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
834         E = AvailableAnalysis.end(); I != E; ) {
835    std::map<AnalysisID, Pass*>::iterator Info = I++;
836    if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
837        PreservedSet.end()) {
838      // Remove this analysis
839      if (!dynamic_cast<ImmutablePass*>(Info->second))
840        AvailableAnalysis.erase(Info);
841    }
842  }
843}
844
845/// Remove analysis passes that are not used any longer
846void PMDataManager::removeDeadPasses(Pass *P, std::string &Msg) {
847
848  std::vector<Pass *> DeadPasses;
849  TPM->collectLastUses(DeadPasses, P);
850
851  for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
852         E = DeadPasses.end(); I != E; ++I) {
853
854    std::string Msg1 = "  Freeing Pass '";
855    dumpPassInfo(*I, Msg1, Msg);
856
857    if (TheTimeInfo) TheTimeInfo->passStarted(P);
858    (*I)->releaseMemory();
859    if (TheTimeInfo) TheTimeInfo->passEnded(P);
860
861    std::map<AnalysisID, Pass*>::iterator Pos =
862      AvailableAnalysis.find((*I)->getPassInfo());
863
864    // It is possible that pass is already removed from the AvailableAnalysis
865    if (Pos != AvailableAnalysis.end())
866      AvailableAnalysis.erase(Pos);
867  }
868}
869
870/// Add pass P into the PassVector. Update
871/// AvailableAnalysis appropriately if ProcessAnalysis is true.
872void PMDataManager::addPassToManager(Pass *P,
873                                     bool ProcessAnalysis) {
874
875  // This manager is going to manage pass P. Set up analysis resolver
876  // to connect them.
877  AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
878  P->setResolver(AR);
879
880  if (ProcessAnalysis) {
881
882    // At the moment, this pass is the last user of all required passes.
883    std::vector<Pass *> LastUses;
884    std::vector<Pass *> RequiredPasses;
885    unsigned PDepth = this->getDepth();
886
887    collectRequiredAnalysisPasses(RequiredPasses, P);
888    for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
889           E = RequiredPasses.end(); I != E; ++I) {
890      Pass *PRequired = *I;
891      unsigned RDepth = 0;
892
893      PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
894      RDepth = DM.getDepth();
895
896      if (PDepth == RDepth)
897        LastUses.push_back(PRequired);
898      else if (PDepth >  RDepth) {
899        // Let the parent claim responsibility of last use
900        TransferLastUses.push_back(PRequired);
901      } else {
902        // Note : This feature is not yet implemented
903        assert (0 &&
904                "Unable to handle Pass that requires lower level Analysis pass");
905      }
906    }
907
908    LastUses.push_back(P);
909    TPM->setLastUser(LastUses, P);
910
911    // Take a note of analysis required and made available by this pass.
912    // Remove the analysis not preserved by this pass
913    removeNotPreservedAnalysis(P);
914    recordAvailableAnalysis(P);
915  }
916
917  // Add pass
918  PassVector.push_back(P);
919}
920
921/// Populate RequiredPasses with the analysis pass that are required by
922/// pass P.
923void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
924                                                  Pass *P) {
925  AnalysisUsage AnUsage;
926  P->getAnalysisUsage(AnUsage);
927  const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
928  for (std::vector<AnalysisID>::const_iterator
929         I = RequiredSet.begin(), E = RequiredSet.end();
930       I != E; ++I) {
931    Pass *AnalysisPass = findAnalysisPass(*I, true);
932    assert (AnalysisPass && "Analysis pass is not available");
933    RP.push_back(AnalysisPass);
934  }
935
936  const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
937  for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
938         E = IDs.end(); I != E; ++I) {
939    Pass *AnalysisPass = findAnalysisPass(*I, true);
940    assert (AnalysisPass && "Analysis pass is not available");
941    RP.push_back(AnalysisPass);
942  }
943}
944
945// All Required analyses should be available to the pass as it runs!  Here
946// we fill in the AnalysisImpls member of the pass so that it can
947// successfully use the getAnalysis() method to retrieve the
948// implementations it needs.
949//
950void PMDataManager::initializeAnalysisImpl(Pass *P) {
951  AnalysisUsage AnUsage;
952  P->getAnalysisUsage(AnUsage);
953
954  for (std::vector<const PassInfo *>::const_iterator
955         I = AnUsage.getRequiredSet().begin(),
956         E = AnUsage.getRequiredSet().end(); I != E; ++I) {
957    Pass *Impl = findAnalysisPass(*I, true);
958    if (Impl == 0)
959      assert(0 && "Analysis used but not available!");
960    AnalysisResolver_New *AR = P->getResolver();
961    AR->addAnalysisImplsPair(*I, Impl);
962  }
963}
964
965/// Find the pass that implements Analysis AID. If desired pass is not found
966/// then return NULL.
967Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
968
969  // Check if AvailableAnalysis map has one entry.
970  std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
971
972  if (I != AvailableAnalysis.end())
973    return I->second;
974
975  // Search Parents through TopLevelManager
976  if (SearchParent)
977    return TPM->findAnalysisPass(AID);
978
979  return NULL;
980}
981
982// Print list of passes that are last used by P.
983void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
984
985  std::vector<Pass *> LUses;
986
987  assert (TPM && "Top Level Manager is missing");
988  TPM->collectLastUses(LUses, P);
989
990  for (std::vector<Pass *>::iterator I = LUses.begin(),
991         E = LUses.end(); I != E; ++I) {
992    llvm::cerr << "--" << std::string(Offset*2, ' ');
993    (*I)->dumpPassStructure(0);
994  }
995}
996
997void PMDataManager::dumpPassArguments() const {
998  for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
999        E = PassVector.end(); I != E; ++I) {
1000    if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
1001      PMD->dumpPassArguments();
1002    else
1003      if (const PassInfo *PI = (*I)->getPassInfo())
1004        if (!PI->isAnalysisGroup())
1005          cerr << " -" << PI->getPassArgument();
1006  }
1007}
1008
1009void PMDataManager:: dumpPassInfo(Pass *P,  std::string &Msg1,
1010                                  std::string &Msg2) const {
1011  if (PassDebugging_New < Executions)
1012    return;
1013  cerr << (void*)this << std::string(getDepth()*2+1, ' ');
1014  cerr << Msg1;
1015  cerr << P->getPassName();
1016  cerr << Msg2;
1017}
1018
1019void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
1020                                        const std::vector<AnalysisID> &Set)
1021  const {
1022  if (PassDebugging_New >= Details && !Set.empty()) {
1023    cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1024      for (unsigned i = 0; i != Set.size(); ++i) {
1025        if (i) cerr << ",";
1026        cerr << " " << Set[i]->getPassName();
1027      }
1028      cerr << "\n";
1029  }
1030}
1031
1032//===----------------------------------------------------------------------===//
1033// NOTE: Is this the right place to define this method ?
1034// getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
1035Pass *AnalysisResolver_New::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
1036  return PM.findAnalysisPass(ID, dir);
1037}
1038
1039//===----------------------------------------------------------------------===//
1040// BBPassManager implementation
1041
1042/// Add pass P into PassVector and return true. If this pass is not
1043/// manageable by this manager then return false.
1044bool
1045BBPassManager::addPass(Pass *P) {
1046
1047  BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
1048  if (!BP)
1049    return false;
1050
1051  // If this pass does not preserve analysis that is used by other passes
1052  // managed by this manager than it is not a suitable pass for this manager.
1053  if (!manageablePass(P))
1054    return false;
1055
1056  addPassToManager(BP);
1057
1058  return true;
1059}
1060
1061/// Execute all of the passes scheduled for execution by invoking
1062/// runOnBasicBlock method.  Keep track of whether any of the passes modifies
1063/// the function, and if so, return true.
1064bool
1065BBPassManager::runOnFunction(Function &F) {
1066
1067  if (F.isExternal())
1068    return false;
1069
1070  bool Changed = doInitialization(F);
1071
1072  std::string Msg1 = "Executing Pass '";
1073  std::string Msg3 = "' Made Modification '";
1074
1075  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1076    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1077      BasicBlockPass *BP = getContainedPass(Index);
1078      AnalysisUsage AnUsage;
1079      BP->getAnalysisUsage(AnUsage);
1080
1081      std::string Msg2 = "' on BasicBlock '" + (*I).getName() + "'...\n";
1082      dumpPassInfo(BP, Msg1, Msg2);
1083      dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
1084
1085      initializeAnalysisImpl(BP);
1086
1087      if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1088      Changed |= BP->runOnBasicBlock(*I);
1089      if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1090
1091      if (Changed)
1092        dumpPassInfo(BP, Msg3, Msg2);
1093      dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
1094
1095      removeNotPreservedAnalysis(BP);
1096      recordAvailableAnalysis(BP);
1097      removeDeadPasses(BP, Msg2);
1098    }
1099  return Changed |= doFinalization(F);
1100}
1101
1102// Implement doInitialization and doFinalization
1103inline bool BBPassManager::doInitialization(Module &M) {
1104  bool Changed = false;
1105
1106  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1107    BasicBlockPass *BP = getContainedPass(Index);
1108    Changed |= BP->doInitialization(M);
1109  }
1110
1111  return Changed;
1112}
1113
1114inline bool BBPassManager::doFinalization(Module &M) {
1115  bool Changed = false;
1116
1117  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1118    BasicBlockPass *BP = getContainedPass(Index);
1119    Changed |= BP->doFinalization(M);
1120  }
1121
1122  return Changed;
1123}
1124
1125inline bool BBPassManager::doInitialization(Function &F) {
1126  bool Changed = false;
1127
1128  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1129    BasicBlockPass *BP = getContainedPass(Index);
1130    Changed |= BP->doInitialization(F);
1131  }
1132
1133  return Changed;
1134}
1135
1136inline bool BBPassManager::doFinalization(Function &F) {
1137  bool Changed = false;
1138
1139  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1140    BasicBlockPass *BP = getContainedPass(Index);
1141    Changed |= BP->doFinalization(F);
1142  }
1143
1144  return Changed;
1145}
1146
1147
1148//===----------------------------------------------------------------------===//
1149// FunctionPassManager implementation
1150
1151/// Create new Function pass manager
1152FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1153  FPM = new FunctionPassManagerImpl(0);
1154  // FPM is the top level manager.
1155  FPM->setTopLevelManager(FPM);
1156
1157  PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
1158  AnalysisResolver_New *AR = new AnalysisResolver_New(*PMD);
1159  FPM->setResolver(AR);
1160
1161  MP = P;
1162}
1163
1164FunctionPassManager::~FunctionPassManager() {
1165  delete FPM;
1166}
1167
1168/// add - Add a pass to the queue of passes to run.  This passes
1169/// ownership of the Pass to the PassManager.  When the
1170/// PassManager_X is destroyed, the pass will be destroyed as well, so
1171/// there is no need to delete the pass. (TODO delete passes.)
1172/// This implies that all passes MUST be allocated with 'new'.
1173void FunctionPassManager::add(Pass *P) {
1174  FPM->add(P);
1175}
1176
1177/// run - Execute all of the passes scheduled for execution.  Keep
1178/// track of whether any of the passes modifies the function, and if
1179/// so, return true.
1180///
1181bool FunctionPassManager::run(Function &F) {
1182  std::string errstr;
1183  if (MP->materializeFunction(&F, &errstr)) {
1184    cerr << "Error reading bytecode file: " << errstr << "\n";
1185    abort();
1186  }
1187  return FPM->run(F);
1188}
1189
1190
1191/// doInitialization - Run all of the initializers for the function passes.
1192///
1193bool FunctionPassManager::doInitialization() {
1194  return FPM->doInitialization(*MP->getModule());
1195}
1196
1197/// doFinalization - Run all of the initializers for the function passes.
1198///
1199bool FunctionPassManager::doFinalization() {
1200  return FPM->doFinalization(*MP->getModule());
1201}
1202
1203//===----------------------------------------------------------------------===//
1204// FunctionPassManagerImpl implementation
1205//
1206/// Add P into active pass manager or use new module pass manager to
1207/// manage it.
1208bool FunctionPassManagerImpl::addPass(Pass *P) {
1209
1210  if (!activeManager || !activeManager->addPass(P)) {
1211    activeManager = new FPPassManager(getDepth() + 1);
1212    // Inherit top level manager
1213    activeManager->setTopLevelManager(this->getTopLevelManager());
1214
1215    // This top level manager is going to manage activeManager.
1216    // Set up analysis resolver to connect them.
1217    AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
1218    activeManager->setResolver(AR);
1219
1220    addPassManager(activeManager);
1221    return activeManager->addPass(P);
1222  }
1223  return true;
1224}
1225
1226inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1227  bool Changed = false;
1228
1229  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1230    FPPassManager *FP = getContainedManager(Index);
1231    Changed |= FP->doInitialization(M);
1232  }
1233
1234  return Changed;
1235}
1236
1237inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1238  bool Changed = false;
1239
1240  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1241    FPPassManager *FP = getContainedManager(Index);
1242    Changed |= FP->doFinalization(M);
1243  }
1244
1245  return Changed;
1246}
1247
1248// Execute all the passes managed by this top level manager.
1249// Return true if any function is modified by a pass.
1250bool FunctionPassManagerImpl::run(Function &F) {
1251
1252  bool Changed = false;
1253
1254  TimingInfo::createTheTimeInfo();
1255
1256  dumpArguments();
1257  dumpPasses();
1258
1259  initializeAllAnalysisInfo();
1260  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1261    FPPassManager *FP = getContainedManager(Index);
1262    Changed |= FP->runOnFunction(F);
1263  }
1264  return Changed;
1265}
1266
1267//===----------------------------------------------------------------------===//
1268// FPPassManager implementation
1269
1270/// Add pass P into the pass manager queue. If P is a BasicBlockPass then
1271/// either use it into active basic block pass manager or create new basic
1272/// block pass manager to handle pass P.
1273bool
1274FPPassManager::addPass(Pass *P) {
1275
1276  // If P is a BasicBlockPass then use BBPassManager.
1277  if (BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P)) {
1278
1279    if (!activeBBPassManager || !activeBBPassManager->addPass(BP)) {
1280
1281      // If active manager exists then clear its analysis info.
1282      if (activeBBPassManager)
1283        activeBBPassManager->initializeAnalysisInfo();
1284
1285      // Create and add new manager
1286      activeBBPassManager = new BBPassManager(getDepth() + 1);
1287      // Inherit top level manager
1288      activeBBPassManager->setTopLevelManager(this->getTopLevelManager());
1289
1290      // Add new manager into current manager's list.
1291      addPassToManager(activeBBPassManager, false);
1292
1293      // Add new manager into top level manager's indirect passes list
1294      PMDataManager *PMD = dynamic_cast<PMDataManager *>(activeBBPassManager);
1295      assert (PMD && "Manager is not Pass Manager");
1296      TPM->addIndirectPassManager(PMD);
1297
1298      // Add pass into new manager. This time it must succeed.
1299      if (!activeBBPassManager->addPass(BP))
1300        assert(0 && "Unable to add Pass");
1301
1302      // If activeBBPassManager transfered any Last Uses then handle them here.
1303      std::vector<Pass *> &TLU = activeBBPassManager->getTransferredLastUses();
1304      if (!TLU.empty())
1305        TPM->setLastUser(TLU, this);
1306
1307    }
1308
1309    return true;
1310  }
1311
1312  FunctionPass *FP = dynamic_cast<FunctionPass *>(P);
1313  if (!FP)
1314    return false;
1315
1316  // If this pass does not preserve analysis that is used by other passes
1317  // managed by this manager than it is not a suitable pass for this manager.
1318  if (!manageablePass(P))
1319    return false;
1320
1321  addPassToManager (FP);
1322
1323  // If active manager exists then clear its analysis info.
1324  if (activeBBPassManager) {
1325    activeBBPassManager->initializeAnalysisInfo();
1326    activeBBPassManager = NULL;
1327  }
1328
1329  return true;
1330}
1331
1332/// Execute all of the passes scheduled for execution by invoking
1333/// runOnFunction method.  Keep track of whether any of the passes modifies
1334/// the function, and if so, return true.
1335bool FPPassManager::runOnFunction(Function &F) {
1336
1337  bool Changed = false;
1338
1339  if (F.isExternal())
1340    return false;
1341
1342  std::string Msg1 = "Executing Pass '";
1343  std::string Msg3 = "' Made Modification '";
1344
1345  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1346    FunctionPass *FP = getContainedPass(Index);
1347
1348    AnalysisUsage AnUsage;
1349    FP->getAnalysisUsage(AnUsage);
1350
1351    std::string Msg2 = "' on Function '" + F.getName() + "'...\n";
1352    dumpPassInfo(FP, Msg1, Msg2);
1353    dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1354
1355    initializeAnalysisImpl(FP);
1356
1357    if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1358    Changed |= FP->runOnFunction(F);
1359    if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1360
1361    if (Changed)
1362      dumpPassInfo(FP, Msg3, Msg2);
1363    dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1364
1365    removeNotPreservedAnalysis(FP);
1366    recordAvailableAnalysis(FP);
1367    removeDeadPasses(FP, Msg2);
1368  }
1369  return Changed;
1370}
1371
1372bool FPPassManager::runOnModule(Module &M) {
1373
1374  bool Changed = doInitialization(M);
1375
1376  for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1377    this->runOnFunction(*I);
1378
1379  return Changed |= doFinalization(M);
1380}
1381
1382inline bool FPPassManager::doInitialization(Module &M) {
1383  bool Changed = false;
1384
1385  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1386    FunctionPass *FP = getContainedPass(Index);
1387    Changed |= FP->doInitialization(M);
1388  }
1389
1390  return Changed;
1391}
1392
1393inline bool FPPassManager::doFinalization(Module &M) {
1394  bool Changed = false;
1395
1396  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1397    FunctionPass *FP = getContainedPass(Index);
1398    Changed |= FP->doFinalization(M);
1399  }
1400
1401  return Changed;
1402}
1403
1404//===----------------------------------------------------------------------===//
1405// MPPassManager implementation
1406
1407/// Add P into pass vector if it is manageble. If P is a FunctionPass
1408/// then use FPPassManager to manage it. Return false if P
1409/// is not manageable by this manager.
1410bool
1411MPPassManager::addPass(Pass *P) {
1412
1413  // If P is FunctionPass then use function pass maanager.
1414  if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P)) {
1415
1416    if (!activeFunctionPassManager || !activeFunctionPassManager->addPass(P)) {
1417
1418      // If active manager exists then clear its analysis info.
1419      if (activeFunctionPassManager)
1420        activeFunctionPassManager->initializeAnalysisInfo();
1421
1422      // Create and add new manager
1423      activeFunctionPassManager =
1424        new FPPassManager(getDepth() + 1);
1425
1426      // Add new manager into current manager's list
1427      addPassToManager(activeFunctionPassManager, false);
1428
1429      // Inherit top level manager
1430      activeFunctionPassManager->setTopLevelManager(this->getTopLevelManager());
1431
1432      // Add new manager into top level manager's indirect passes list
1433      PMDataManager *PMD =
1434        dynamic_cast<PMDataManager *>(activeFunctionPassManager);
1435      assert(PMD && "Manager is not Pass Manager");
1436      TPM->addIndirectPassManager(PMD);
1437
1438      // Add pass into new manager. This time it must succeed.
1439      if (!activeFunctionPassManager->addPass(FP))
1440        assert(0 && "Unable to add pass");
1441
1442      // If activeFunctionPassManager transfered any Last Uses then
1443      // handle them here.
1444      std::vector<Pass *> &TLU =
1445        activeFunctionPassManager->getTransferredLastUses();
1446      if (!TLU.empty())
1447        TPM->setLastUser(TLU, this);
1448    }
1449
1450    return true;
1451  }
1452
1453  ModulePass *MP = dynamic_cast<ModulePass *>(P);
1454  if (!MP)
1455    return false;
1456
1457  // If this pass does not preserve analysis that is used by other passes
1458  // managed by this manager than it is not a suitable pass for this manager.
1459  if (!manageablePass(P))
1460    return false;
1461
1462  addPassToManager(MP);
1463  // If active manager exists then clear its analysis info.
1464  if (activeFunctionPassManager) {
1465    activeFunctionPassManager->initializeAnalysisInfo();
1466    activeFunctionPassManager = NULL;
1467  }
1468
1469  return true;
1470}
1471
1472
1473/// Execute all of the passes scheduled for execution by invoking
1474/// runOnModule method.  Keep track of whether any of the passes modifies
1475/// the module, and if so, return true.
1476bool
1477MPPassManager::runOnModule(Module &M) {
1478  bool Changed = false;
1479
1480  std::string Msg1 = "Executing Pass '";
1481  std::string Msg3 = "' Made Modification '";
1482
1483  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1484    ModulePass *MP = getContainedPass(Index);
1485
1486    AnalysisUsage AnUsage;
1487    MP->getAnalysisUsage(AnUsage);
1488
1489    std::string Msg2 = "' on Module '" + M.getModuleIdentifier() + "'...\n";
1490    dumpPassInfo(MP, Msg1, Msg2);
1491    dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1492
1493    initializeAnalysisImpl(MP);
1494
1495    if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1496    Changed |= MP->runOnModule(M);
1497    if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1498
1499    if (Changed)
1500      dumpPassInfo(MP, Msg3, Msg2);
1501    dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1502
1503    removeNotPreservedAnalysis(MP);
1504    recordAvailableAnalysis(MP);
1505    removeDeadPasses(MP, Msg2);
1506  }
1507  return Changed;
1508}
1509
1510//===----------------------------------------------------------------------===//
1511// PassManagerImpl implementation
1512//
1513/// Add P into active pass manager or use new module pass manager to
1514/// manage it.
1515bool PassManagerImpl::addPass(Pass *P) {
1516
1517  if (!activeManager || !activeManager->addPass(P)) {
1518    activeManager = new MPPassManager(getDepth() + 1);
1519    // Inherit top level manager
1520    activeManager->setTopLevelManager(this->getTopLevelManager());
1521
1522    // This top level manager is going to manage activeManager.
1523    // Set up analysis resolver to connect them.
1524    AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
1525    activeManager->setResolver(AR);
1526
1527    addPassManager(activeManager);
1528    return activeManager->addPass(P);
1529  }
1530  return true;
1531}
1532
1533/// run - Execute all of the passes scheduled for execution.  Keep track of
1534/// whether any of the passes modifies the module, and if so, return true.
1535bool PassManagerImpl::run(Module &M) {
1536
1537  bool Changed = false;
1538
1539  TimingInfo::createTheTimeInfo();
1540
1541  dumpArguments();
1542  dumpPasses();
1543
1544  initializeAllAnalysisInfo();
1545  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1546    MPPassManager *MP = getContainedManager(Index);
1547    Changed |= MP->runOnModule(M);
1548  }
1549  return Changed;
1550}
1551
1552//===----------------------------------------------------------------------===//
1553// PassManager implementation
1554
1555/// Create new pass manager
1556PassManager::PassManager() {
1557  PM = new PassManagerImpl(0);
1558  // PM is the top level manager
1559  PM->setTopLevelManager(PM);
1560}
1561
1562PassManager::~PassManager() {
1563  delete PM;
1564}
1565
1566/// add - Add a pass to the queue of passes to run.  This passes ownership of
1567/// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1568/// will be destroyed as well, so there is no need to delete the pass.  This
1569/// implies that all passes MUST be allocated with 'new'.
1570void
1571PassManager::add(Pass *P) {
1572  PM->add(P);
1573}
1574
1575/// run - Execute all of the passes scheduled for execution.  Keep track of
1576/// whether any of the passes modifies the module, and if so, return true.
1577bool
1578PassManager::run(Module &M) {
1579  return PM->run(M);
1580}
1581
1582//===----------------------------------------------------------------------===//
1583// TimingInfo Class - This class is used to calculate information about the
1584// amount of time each pass takes to execute.  This only happens with
1585// -time-passes is enabled on the command line.
1586//
1587bool llvm::TimePassesIsEnabled = false;
1588static cl::opt<bool,true>
1589EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1590            cl::desc("Time each pass, printing elapsed time for each on exit"));
1591
1592// createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1593// a non null value (if the -time-passes option is enabled) or it leaves it
1594// null.  It may be called multiple times.
1595void TimingInfo::createTheTimeInfo() {
1596  if (!TimePassesIsEnabled || TheTimeInfo) return;
1597
1598  // Constructed the first time this is called, iff -time-passes is enabled.
1599  // This guarantees that the object will be constructed before static globals,
1600  // thus it will be destroyed before them.
1601  static ManagedStatic<TimingInfo> TTI;
1602  TheTimeInfo = &*TTI;
1603}
1604
1605#endif
1606