Move all of the header files which are involved in modelling the LLVM IR
[oota-llvm.git] / lib / IR / PassManager.cpp
1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/PassManagers.h"
16 #include "llvm/Assembly/PrintModulePass.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/PassNameParser.h"
26 #include "llvm/Support/Timer.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 #include <map>
30 using namespace llvm;
31
32 // See PassManagers.h for Pass Manager infrastructure overview.
33
34 namespace llvm {
35
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information.  Often it is useful to find out what pass is
38 // running when a crash occurs in a utility.  When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
41 //
42
43 // Different debug levels that can be enabled...
44 enum PassDebugLevel {
45   None, Arguments, Structure, Executions, Details
46 };
47
48 static cl::opt<enum PassDebugLevel>
49 PassDebugging("debug-pass", cl::Hidden,
50                   cl::desc("Print PassManager debugging information"),
51                   cl::values(
52   clEnumVal(None      , "disable debug output"),
53   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54   clEnumVal(Structure , "print pass structure before run()"),
55   clEnumVal(Executions, "print pass name before it is executed"),
56   clEnumVal(Details   , "print pass details when it is executed"),
57                              clEnumValEnd));
58
59 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
60 PassOptionList;
61
62 // Print IR out before/after specified passes.
63 static PassOptionList
64 PrintBefore("print-before",
65             llvm::cl::desc("Print IR before specified passes"),
66             cl::Hidden);
67
68 static PassOptionList
69 PrintAfter("print-after",
70            llvm::cl::desc("Print IR after specified passes"),
71            cl::Hidden);
72
73 static cl::opt<bool>
74 PrintBeforeAll("print-before-all",
75                llvm::cl::desc("Print IR before each pass"),
76                cl::init(false));
77 static cl::opt<bool>
78 PrintAfterAll("print-after-all",
79               llvm::cl::desc("Print IR after each pass"),
80               cl::init(false));
81
82 /// This is a helper to determine whether to print IR before or
83 /// after a pass.
84
85 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
86                                          PassOptionList &PassesToPrint) {
87   for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
88     const llvm::PassInfo *PassInf = PassesToPrint[i];
89     if (PassInf)
90       if (PassInf->getPassArgument() == PI->getPassArgument()) {
91         return true;
92       }
93   }
94   return false;
95 }
96
97 /// This is a utility to check whether a pass should have IR dumped
98 /// before it.
99 static bool ShouldPrintBeforePass(const PassInfo *PI) {
100   return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
101 }
102
103 /// This is a utility to check whether a pass should have IR dumped
104 /// after it.
105 static bool ShouldPrintAfterPass(const PassInfo *PI) {
106   return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
107 }
108
109 } // End of llvm namespace
110
111 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
112 /// or higher is specified.
113 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
114   return PassDebugging >= Executions;
115 }
116
117
118
119
120 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
121   if (V == 0 && M == 0)
122     OS << "Releasing pass '";
123   else
124     OS << "Running pass '";
125
126   OS << P->getPassName() << "'";
127
128   if (M) {
129     OS << " on module '" << M->getModuleIdentifier() << "'.\n";
130     return;
131   }
132   if (V == 0) {
133     OS << '\n';
134     return;
135   }
136
137   OS << " on ";
138   if (isa<Function>(V))
139     OS << "function";
140   else if (isa<BasicBlock>(V))
141     OS << "basic block";
142   else
143     OS << "value";
144
145   OS << " '";
146   WriteAsOperand(OS, V, /*PrintTy=*/false, M);
147   OS << "'\n";
148 }
149
150
151 namespace {
152
153 //===----------------------------------------------------------------------===//
154 // BBPassManager
155 //
156 /// BBPassManager manages BasicBlockPass. It batches all the
157 /// pass together and sequence them to process one basic block before
158 /// processing next basic block.
159 class BBPassManager : public PMDataManager, public FunctionPass {
160
161 public:
162   static char ID;
163   explicit BBPassManager()
164     : PMDataManager(), FunctionPass(ID) {}
165
166   /// Execute all of the passes scheduled for execution.  Keep track of
167   /// whether any of the passes modifies the function, and if so, return true.
168   bool runOnFunction(Function &F);
169
170   /// Pass Manager itself does not invalidate any analysis info.
171   void getAnalysisUsage(AnalysisUsage &Info) const {
172     Info.setPreservesAll();
173   }
174
175   bool doInitialization(Module &M);
176   bool doInitialization(Function &F);
177   bool doFinalization(Module &M);
178   bool doFinalization(Function &F);
179
180   virtual PMDataManager *getAsPMDataManager() { return this; }
181   virtual Pass *getAsPass() { return this; }
182
183   virtual const char *getPassName() const {
184     return "BasicBlock Pass Manager";
185   }
186
187   // Print passes managed by this manager
188   void dumpPassStructure(unsigned Offset) {
189     llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
190     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
191       BasicBlockPass *BP = getContainedPass(Index);
192       BP->dumpPassStructure(Offset + 1);
193       dumpLastUses(BP, Offset+1);
194     }
195   }
196
197   BasicBlockPass *getContainedPass(unsigned N) {
198     assert(N < PassVector.size() && "Pass number out of range!");
199     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
200     return BP;
201   }
202
203   virtual PassManagerType getPassManagerType() const {
204     return PMT_BasicBlockPassManager;
205   }
206 };
207
208 char BBPassManager::ID = 0;
209 }
210
211 namespace llvm {
212
213 //===----------------------------------------------------------------------===//
214 // FunctionPassManagerImpl
215 //
216 /// FunctionPassManagerImpl manages FPPassManagers
217 class FunctionPassManagerImpl : public Pass,
218                                 public PMDataManager,
219                                 public PMTopLevelManager {
220   virtual void anchor();
221 private:
222   bool wasRun;
223 public:
224   static char ID;
225   explicit FunctionPassManagerImpl() :
226     Pass(PT_PassManager, ID), PMDataManager(),
227     PMTopLevelManager(new FPPassManager()), wasRun(false) {}
228
229   /// add - Add a pass to the queue of passes to run.  This passes ownership of
230   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
231   /// will be destroyed as well, so there is no need to delete the pass.  This
232   /// implies that all passes MUST be allocated with 'new'.
233   void add(Pass *P) {
234     schedulePass(P);
235   }
236
237   /// createPrinterPass - Get a function printer pass.
238   Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
239     return createPrintFunctionPass(Banner, &O);
240   }
241
242   // Prepare for running an on the fly pass, freeing memory if needed
243   // from a previous run.
244   void releaseMemoryOnTheFly();
245
246   /// run - Execute all of the passes scheduled for execution.  Keep track of
247   /// whether any of the passes modifies the module, and if so, return true.
248   bool run(Function &F);
249
250   /// doInitialization - Run all of the initializers for the function passes.
251   ///
252   bool doInitialization(Module &M);
253
254   /// doFinalization - Run all of the finalizers for the function passes.
255   ///
256   bool doFinalization(Module &M);
257
258
259   virtual PMDataManager *getAsPMDataManager() { return this; }
260   virtual Pass *getAsPass() { return this; }
261   virtual PassManagerType getTopLevelPassManagerType() {
262     return PMT_FunctionPassManager;
263   }
264
265   /// Pass Manager itself does not invalidate any analysis info.
266   void getAnalysisUsage(AnalysisUsage &Info) const {
267     Info.setPreservesAll();
268   }
269
270   FPPassManager *getContainedManager(unsigned N) {
271     assert(N < PassManagers.size() && "Pass number out of range!");
272     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
273     return FP;
274   }
275 };
276
277 void FunctionPassManagerImpl::anchor() {}
278
279 char FunctionPassManagerImpl::ID = 0;
280
281 //===----------------------------------------------------------------------===//
282 // MPPassManager
283 //
284 /// MPPassManager manages ModulePasses and function pass managers.
285 /// It batches all Module passes and function pass managers together and
286 /// sequences them to process one module.
287 class MPPassManager : public Pass, public PMDataManager {
288 public:
289   static char ID;
290   explicit MPPassManager() :
291     Pass(PT_PassManager, ID), PMDataManager() { }
292
293   // Delete on the fly managers.
294   virtual ~MPPassManager() {
295     for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
296            I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
297          I != E; ++I) {
298       FunctionPassManagerImpl *FPP = I->second;
299       delete FPP;
300     }
301   }
302
303   /// createPrinterPass - Get a module printer pass.
304   Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
305     return createPrintModulePass(&O, false, Banner);
306   }
307
308   /// run - Execute all of the passes scheduled for execution.  Keep track of
309   /// whether any of the passes modifies the module, and if so, return true.
310   bool runOnModule(Module &M);
311
312   using llvm::Pass::doInitialization;
313   using llvm::Pass::doFinalization;
314
315   /// doInitialization - Run all of the initializers for the module passes.
316   ///
317   bool doInitialization();
318
319   /// doFinalization - Run all of the finalizers for the module passes.
320   ///
321   bool doFinalization();
322
323   /// Pass Manager itself does not invalidate any analysis info.
324   void getAnalysisUsage(AnalysisUsage &Info) const {
325     Info.setPreservesAll();
326   }
327
328   /// Add RequiredPass into list of lower level passes required by pass P.
329   /// RequiredPass is run on the fly by Pass Manager when P requests it
330   /// through getAnalysis interface.
331   virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
332
333   /// Return function pass corresponding to PassInfo PI, that is
334   /// required by module pass MP. Instantiate analysis pass, by using
335   /// its runOnFunction() for function F.
336   virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
337
338   virtual const char *getPassName() const {
339     return "Module Pass Manager";
340   }
341
342   virtual PMDataManager *getAsPMDataManager() { return this; }
343   virtual Pass *getAsPass() { return this; }
344
345   // Print passes managed by this manager
346   void dumpPassStructure(unsigned Offset) {
347     llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
348     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
349       ModulePass *MP = getContainedPass(Index);
350       MP->dumpPassStructure(Offset + 1);
351       std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
352         OnTheFlyManagers.find(MP);
353       if (I != OnTheFlyManagers.end())
354         I->second->dumpPassStructure(Offset + 2);
355       dumpLastUses(MP, Offset+1);
356     }
357   }
358
359   ModulePass *getContainedPass(unsigned N) {
360     assert(N < PassVector.size() && "Pass number out of range!");
361     return static_cast<ModulePass *>(PassVector[N]);
362   }
363
364   virtual PassManagerType getPassManagerType() const {
365     return PMT_ModulePassManager;
366   }
367
368  private:
369   /// Collection of on the fly FPPassManagers. These managers manage
370   /// function passes that are required by module passes.
371   std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
372 };
373
374 char MPPassManager::ID = 0;
375 //===----------------------------------------------------------------------===//
376 // PassManagerImpl
377 //
378
379 /// PassManagerImpl manages MPPassManagers
380 class PassManagerImpl : public Pass,
381                         public PMDataManager,
382                         public PMTopLevelManager {
383   virtual void anchor();
384
385 public:
386   static char ID;
387   explicit PassManagerImpl() :
388     Pass(PT_PassManager, ID), PMDataManager(),
389                               PMTopLevelManager(new MPPassManager()) {}
390
391   /// add - Add a pass to the queue of passes to run.  This passes ownership of
392   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
393   /// will be destroyed as well, so there is no need to delete the pass.  This
394   /// implies that all passes MUST be allocated with 'new'.
395   void add(Pass *P) {
396     schedulePass(P);
397   }
398
399   /// createPrinterPass - Get a module printer pass.
400   Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
401     return createPrintModulePass(&O, false, Banner);
402   }
403
404   /// run - Execute all of the passes scheduled for execution.  Keep track of
405   /// whether any of the passes modifies the module, and if so, return true.
406   bool run(Module &M);
407
408   using llvm::Pass::doInitialization;
409   using llvm::Pass::doFinalization;
410
411   /// doInitialization - Run all of the initializers for the module passes.
412   ///
413   bool doInitialization();
414
415   /// doFinalization - Run all of the finalizers for the module passes.
416   ///
417   bool doFinalization();
418
419   /// Pass Manager itself does not invalidate any analysis info.
420   void getAnalysisUsage(AnalysisUsage &Info) const {
421     Info.setPreservesAll();
422   }
423
424   virtual PMDataManager *getAsPMDataManager() { return this; }
425   virtual Pass *getAsPass() { return this; }
426   virtual PassManagerType getTopLevelPassManagerType() {
427     return PMT_ModulePassManager;
428   }
429
430   MPPassManager *getContainedManager(unsigned N) {
431     assert(N < PassManagers.size() && "Pass number out of range!");
432     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
433     return MP;
434   }
435 };
436
437 void PassManagerImpl::anchor() {}
438
439 char PassManagerImpl::ID = 0;
440 } // End of llvm namespace
441
442 namespace {
443
444 //===----------------------------------------------------------------------===//
445 /// TimingInfo Class - This class is used to calculate information about the
446 /// amount of time each pass takes to execute.  This only happens when
447 /// -time-passes is enabled on the command line.
448 ///
449
450 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
451
452 class TimingInfo {
453   DenseMap<Pass*, Timer*> TimingData;
454   TimerGroup TG;
455 public:
456   // Use 'create' member to get this.
457   TimingInfo() : TG("... Pass execution timing report ...") {}
458
459   // TimingDtor - Print out information about timing information
460   ~TimingInfo() {
461     // Delete all of the timers, which accumulate their info into the
462     // TimerGroup.
463     for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
464          E = TimingData.end(); I != E; ++I)
465       delete I->second;
466     // TimerGroup is deleted next, printing the report.
467   }
468
469   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
470   // to a non null value (if the -time-passes option is enabled) or it leaves it
471   // null.  It may be called multiple times.
472   static void createTheTimeInfo();
473
474   /// getPassTimer - Return the timer for the specified pass if it exists.
475   Timer *getPassTimer(Pass *P) {
476     if (P->getAsPMDataManager())
477       return 0;
478
479     sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
480     Timer *&T = TimingData[P];
481     if (T == 0)
482       T = new Timer(P->getPassName(), TG);
483     return T;
484   }
485 };
486
487 } // End of anon namespace
488
489 static TimingInfo *TheTimeInfo;
490
491 //===----------------------------------------------------------------------===//
492 // PMTopLevelManager implementation
493
494 /// Initialize top level manager. Create first pass manager.
495 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
496   PMDM->setTopLevelManager(this);
497   addPassManager(PMDM);
498   activeStack.push(PMDM);
499 }
500
501 /// Set pass P as the last user of the given analysis passes.
502 void
503 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
504   unsigned PDepth = 0;
505   if (P->getResolver())
506     PDepth = P->getResolver()->getPMDataManager().getDepth();
507
508   for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
509          E = AnalysisPasses.end(); I != E; ++I) {
510     Pass *AP = *I;
511     LastUser[AP] = P;
512
513     if (P == AP)
514       continue;
515
516     // Update the last users of passes that are required transitive by AP.
517     AnalysisUsage *AnUsage = findAnalysisUsage(AP);
518     const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
519     SmallVector<Pass *, 12> LastUses;
520     SmallVector<Pass *, 12> LastPMUses;
521     for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
522          E = IDs.end(); I != E; ++I) {
523       Pass *AnalysisPass = findAnalysisPass(*I);
524       assert(AnalysisPass && "Expected analysis pass to exist.");
525       AnalysisResolver *AR = AnalysisPass->getResolver();
526       assert(AR && "Expected analysis resolver to exist.");
527       unsigned APDepth = AR->getPMDataManager().getDepth();
528
529       if (PDepth == APDepth)
530         LastUses.push_back(AnalysisPass);
531       else if (PDepth > APDepth)
532         LastPMUses.push_back(AnalysisPass);
533     }
534
535     setLastUser(LastUses, P);
536
537     // If this pass has a corresponding pass manager, push higher level
538     // analysis to this pass manager.
539     if (P->getResolver())
540       setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
541
542
543     // If AP is the last user of other passes then make P last user of
544     // such passes.
545     for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
546            LUE = LastUser.end(); LUI != LUE; ++LUI) {
547       if (LUI->second == AP)
548         // DenseMap iterator is not invalidated here because
549         // this is just updating existing entries.
550         LastUser[LUI->first] = P;
551     }
552   }
553 }
554
555 /// Collect passes whose last user is P
556 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
557                                         Pass *P) {
558   DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
559     InversedLastUser.find(P);
560   if (DMI == InversedLastUser.end())
561     return;
562
563   SmallPtrSet<Pass *, 8> &LU = DMI->second;
564   for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
565          E = LU.end(); I != E; ++I) {
566     LastUses.push_back(*I);
567   }
568
569 }
570
571 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
572   AnalysisUsage *AnUsage = NULL;
573   DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
574   if (DMI != AnUsageMap.end())
575     AnUsage = DMI->second;
576   else {
577     AnUsage = new AnalysisUsage();
578     P->getAnalysisUsage(*AnUsage);
579     AnUsageMap[P] = AnUsage;
580   }
581   return AnUsage;
582 }
583
584 /// Schedule pass P for execution. Make sure that passes required by
585 /// P are run before P is run. Update analysis info maintained by
586 /// the manager. Remove dead passes. This is a recursive function.
587 void PMTopLevelManager::schedulePass(Pass *P) {
588
589   // TODO : Allocate function manager for this pass, other wise required set
590   // may be inserted into previous function manager
591
592   // Give pass a chance to prepare the stage.
593   P->preparePassManager(activeStack);
594
595   // If P is an analysis pass and it is available then do not
596   // generate the analysis again. Stale analysis info should not be
597   // available at this point.
598   const PassInfo *PI =
599     PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
600   if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
601     delete P;
602     return;
603   }
604
605   AnalysisUsage *AnUsage = findAnalysisUsage(P);
606
607   bool checkAnalysis = true;
608   while (checkAnalysis) {
609     checkAnalysis = false;
610
611     const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
612     for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
613            E = RequiredSet.end(); I != E; ++I) {
614
615       Pass *AnalysisPass = findAnalysisPass(*I);
616       if (!AnalysisPass) {
617         const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
618
619         if (PI == NULL) {
620           // Pass P is not in the global PassRegistry
621           dbgs() << "Pass '"  << P->getPassName() << "' is not initialized." << "\n";
622           dbgs() << "Verify if there is a pass dependency cycle." << "\n";
623           dbgs() << "Required Passes:" << "\n";
624           for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
625                  E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
626             Pass *AnalysisPass2 = findAnalysisPass(*I2);
627             if (AnalysisPass2) {
628               dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
629             }
630             else {
631               dbgs() << "\t"   << "Error: Required pass not found! Possible causes:"  << "\n";
632               dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)"    << "\n";
633               dbgs() << "\t\t" << "- Corruption of the global PassRegistry"           << "\n";
634             }
635           }
636         }
637
638         assert(PI && "Expected required passes to be initialized");
639         AnalysisPass = PI->createPass();
640         if (P->getPotentialPassManagerType () ==
641             AnalysisPass->getPotentialPassManagerType())
642           // Schedule analysis pass that is managed by the same pass manager.
643           schedulePass(AnalysisPass);
644         else if (P->getPotentialPassManagerType () >
645                  AnalysisPass->getPotentialPassManagerType()) {
646           // Schedule analysis pass that is managed by a new manager.
647           schedulePass(AnalysisPass);
648           // Recheck analysis passes to ensure that required analyses that
649           // are already checked are still available.
650           checkAnalysis = true;
651         }
652         else
653           // Do not schedule this analysis. Lower level analsyis
654           // passes are run on the fly.
655           delete AnalysisPass;
656       }
657     }
658   }
659
660   // Now all required passes are available.
661   if (ImmutablePass *IP = P->getAsImmutablePass()) {
662     // P is a immutable pass and it will be managed by this
663     // top level manager. Set up analysis resolver to connect them.
664     PMDataManager *DM = getAsPMDataManager();
665     AnalysisResolver *AR = new AnalysisResolver(*DM);
666     P->setResolver(AR);
667     DM->initializeAnalysisImpl(P);
668     addImmutablePass(IP);
669     DM->recordAvailableAnalysis(IP);
670     return;
671   }
672
673   if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
674     Pass *PP = P->createPrinterPass(
675       dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
676     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
677   }
678
679   // Add the requested pass to the best available pass manager.
680   P->assignPassManager(activeStack, getTopLevelPassManagerType());
681
682   if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
683     Pass *PP = P->createPrinterPass(
684       dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
685     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
686   }
687 }
688
689 /// Find the pass that implements Analysis AID. Search immutable
690 /// passes and all pass managers. If desired pass is not found
691 /// then return NULL.
692 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
693
694   // Check pass managers
695   for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
696          E = PassManagers.end(); I != E; ++I)
697     if (Pass *P = (*I)->findAnalysisPass(AID, false))
698       return P;
699
700   // Check other pass managers
701   for (SmallVectorImpl<PMDataManager *>::iterator
702          I = IndirectPassManagers.begin(),
703          E = IndirectPassManagers.end(); I != E; ++I)
704     if (Pass *P = (*I)->findAnalysisPass(AID, false))
705       return P;
706
707   // Check the immutable passes. Iterate in reverse order so that we find
708   // the most recently registered passes first.
709   for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
710        ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
711     AnalysisID PI = (*I)->getPassID();
712     if (PI == AID)
713       return *I;
714
715     // If Pass not found then check the interfaces implemented by Immutable Pass
716     const PassInfo *PassInf =
717       PassRegistry::getPassRegistry()->getPassInfo(PI);
718     assert(PassInf && "Expected all immutable passes to be initialized");
719     const std::vector<const PassInfo*> &ImmPI =
720       PassInf->getInterfacesImplemented();
721     for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
722          EE = ImmPI.end(); II != EE; ++II) {
723       if ((*II)->getTypeInfo() == AID)
724         return *I;
725     }
726   }
727
728   return 0;
729 }
730
731 // Print passes managed by this top level manager.
732 void PMTopLevelManager::dumpPasses() const {
733
734   if (PassDebugging < Structure)
735     return;
736
737   // Print out the immutable passes
738   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
739     ImmutablePasses[i]->dumpPassStructure(0);
740   }
741
742   // Every class that derives from PMDataManager also derives from Pass
743   // (sometimes indirectly), but there's no inheritance relationship
744   // between PMDataManager and Pass, so we have to getAsPass to get
745   // from a PMDataManager* to a Pass*.
746   for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
747          E = PassManagers.end(); I != E; ++I)
748     (*I)->getAsPass()->dumpPassStructure(1);
749 }
750
751 void PMTopLevelManager::dumpArguments() const {
752
753   if (PassDebugging < Arguments)
754     return;
755
756   dbgs() << "Pass Arguments: ";
757   for (SmallVector<ImmutablePass *, 8>::const_iterator I =
758        ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
759     if (const PassInfo *PI =
760         PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
761       assert(PI && "Expected all immutable passes to be initialized");
762       if (!PI->isAnalysisGroup())
763         dbgs() << " -" << PI->getPassArgument();
764     }
765   for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
766          E = PassManagers.end(); I != E; ++I)
767     (*I)->dumpPassArguments();
768   dbgs() << "\n";
769 }
770
771 void PMTopLevelManager::initializeAllAnalysisInfo() {
772   for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
773          E = PassManagers.end(); I != E; ++I)
774     (*I)->initializeAnalysisInfo();
775
776   // Initailize other pass managers
777   for (SmallVectorImpl<PMDataManager *>::iterator
778        I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
779        I != E; ++I)
780     (*I)->initializeAnalysisInfo();
781
782   for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
783         DME = LastUser.end(); DMI != DME; ++DMI) {
784     DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
785       InversedLastUser.find(DMI->second);
786     if (InvDMI != InversedLastUser.end()) {
787       SmallPtrSet<Pass *, 8> &L = InvDMI->second;
788       L.insert(DMI->first);
789     } else {
790       SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
791       InversedLastUser[DMI->second] = L;
792     }
793   }
794 }
795
796 /// Destructor
797 PMTopLevelManager::~PMTopLevelManager() {
798   for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
799          E = PassManagers.end(); I != E; ++I)
800     delete *I;
801
802   for (SmallVectorImpl<ImmutablePass *>::iterator
803          I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
804     delete *I;
805
806   for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
807          DME = AnUsageMap.end(); DMI != DME; ++DMI)
808     delete DMI->second;
809 }
810
811 //===----------------------------------------------------------------------===//
812 // PMDataManager implementation
813
814 /// Augement AvailableAnalysis by adding analysis made available by pass P.
815 void PMDataManager::recordAvailableAnalysis(Pass *P) {
816   AnalysisID PI = P->getPassID();
817
818   AvailableAnalysis[PI] = P;
819
820   assert(!AvailableAnalysis.empty());
821
822   // This pass is the current implementation of all of the interfaces it
823   // implements as well.
824   const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
825   if (PInf == 0) return;
826   const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
827   for (unsigned i = 0, e = II.size(); i != e; ++i)
828     AvailableAnalysis[II[i]->getTypeInfo()] = P;
829 }
830
831 // Return true if P preserves high level analysis used by other
832 // passes managed by this manager
833 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
834   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
835   if (AnUsage->getPreservesAll())
836     return true;
837
838   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
839   for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
840          E = HigherLevelAnalysis.end(); I  != E; ++I) {
841     Pass *P1 = *I;
842     if (P1->getAsImmutablePass() == 0 &&
843         std::find(PreservedSet.begin(), PreservedSet.end(),
844                   P1->getPassID()) ==
845            PreservedSet.end())
846       return false;
847   }
848
849   return true;
850 }
851
852 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
853 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
854   // Don't do this unless assertions are enabled.
855 #ifdef NDEBUG
856   return;
857 #endif
858   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
859   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
860
861   // Verify preserved analysis
862   for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
863          E = PreservedSet.end(); I != E; ++I) {
864     AnalysisID AID = *I;
865     if (Pass *AP = findAnalysisPass(AID, true)) {
866       TimeRegion PassTimer(getPassTimer(AP));
867       AP->verifyAnalysis();
868     }
869   }
870 }
871
872 /// Remove Analysis not preserved by Pass P
873 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
874   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
875   if (AnUsage->getPreservesAll())
876     return;
877
878   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
879   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
880          E = AvailableAnalysis.end(); I != E; ) {
881     std::map<AnalysisID, Pass*>::iterator Info = I++;
882     if (Info->second->getAsImmutablePass() == 0 &&
883         std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
884         PreservedSet.end()) {
885       // Remove this analysis
886       if (PassDebugging >= Details) {
887         Pass *S = Info->second;
888         dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
889         dbgs() << S->getPassName() << "'\n";
890       }
891       AvailableAnalysis.erase(Info);
892     }
893   }
894
895   // Check inherited analysis also. If P is not preserving analysis
896   // provided by parent manager then remove it here.
897   for (unsigned Index = 0; Index < PMT_Last; ++Index) {
898
899     if (!InheritedAnalysis[Index])
900       continue;
901
902     for (std::map<AnalysisID, Pass*>::iterator
903            I = InheritedAnalysis[Index]->begin(),
904            E = InheritedAnalysis[Index]->end(); I != E; ) {
905       std::map<AnalysisID, Pass *>::iterator Info = I++;
906       if (Info->second->getAsImmutablePass() == 0 &&
907           std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
908              PreservedSet.end()) {
909         // Remove this analysis
910         if (PassDebugging >= Details) {
911           Pass *S = Info->second;
912           dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
913           dbgs() << S->getPassName() << "'\n";
914         }
915         InheritedAnalysis[Index]->erase(Info);
916       }
917     }
918   }
919 }
920
921 /// Remove analysis passes that are not used any longer
922 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
923                                      enum PassDebuggingString DBG_STR) {
924
925   SmallVector<Pass *, 12> DeadPasses;
926
927   // If this is a on the fly manager then it does not have TPM.
928   if (!TPM)
929     return;
930
931   TPM->collectLastUses(DeadPasses, P);
932
933   if (PassDebugging >= Details && !DeadPasses.empty()) {
934     dbgs() << " -*- '" <<  P->getPassName();
935     dbgs() << "' is the last user of following pass instances.";
936     dbgs() << " Free these instances\n";
937   }
938
939   for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
940          E = DeadPasses.end(); I != E; ++I)
941     freePass(*I, Msg, DBG_STR);
942 }
943
944 void PMDataManager::freePass(Pass *P, StringRef Msg,
945                              enum PassDebuggingString DBG_STR) {
946   dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
947
948   {
949     // If the pass crashes releasing memory, remember this.
950     PassManagerPrettyStackEntry X(P);
951     TimeRegion PassTimer(getPassTimer(P));
952
953     P->releaseMemory();
954   }
955
956   AnalysisID PI = P->getPassID();
957   if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
958     // Remove the pass itself (if it is not already removed).
959     AvailableAnalysis.erase(PI);
960
961     // Remove all interfaces this pass implements, for which it is also
962     // listed as the available implementation.
963     const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
964     for (unsigned i = 0, e = II.size(); i != e; ++i) {
965       std::map<AnalysisID, Pass*>::iterator Pos =
966         AvailableAnalysis.find(II[i]->getTypeInfo());
967       if (Pos != AvailableAnalysis.end() && Pos->second == P)
968         AvailableAnalysis.erase(Pos);
969     }
970   }
971 }
972
973 /// Add pass P into the PassVector. Update
974 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
975 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
976   // This manager is going to manage pass P. Set up analysis resolver
977   // to connect them.
978   AnalysisResolver *AR = new AnalysisResolver(*this);
979   P->setResolver(AR);
980
981   // If a FunctionPass F is the last user of ModulePass info M
982   // then the F's manager, not F, records itself as a last user of M.
983   SmallVector<Pass *, 12> TransferLastUses;
984
985   if (!ProcessAnalysis) {
986     // Add pass
987     PassVector.push_back(P);
988     return;
989   }
990
991   // At the moment, this pass is the last user of all required passes.
992   SmallVector<Pass *, 12> LastUses;
993   SmallVector<Pass *, 8> RequiredPasses;
994   SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
995
996   unsigned PDepth = this->getDepth();
997
998   collectRequiredAnalysis(RequiredPasses,
999                           ReqAnalysisNotAvailable, P);
1000   for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1001          E = RequiredPasses.end(); I != E; ++I) {
1002     Pass *PRequired = *I;
1003     unsigned RDepth = 0;
1004
1005     assert(PRequired->getResolver() && "Analysis Resolver is not set");
1006     PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1007     RDepth = DM.getDepth();
1008
1009     if (PDepth == RDepth)
1010       LastUses.push_back(PRequired);
1011     else if (PDepth > RDepth) {
1012       // Let the parent claim responsibility of last use
1013       TransferLastUses.push_back(PRequired);
1014       // Keep track of higher level analysis used by this manager.
1015       HigherLevelAnalysis.push_back(PRequired);
1016     } else
1017       llvm_unreachable("Unable to accommodate Required Pass");
1018   }
1019
1020   // Set P as P's last user until someone starts using P.
1021   // However, if P is a Pass Manager then it does not need
1022   // to record its last user.
1023   if (P->getAsPMDataManager() == 0)
1024     LastUses.push_back(P);
1025   TPM->setLastUser(LastUses, P);
1026
1027   if (!TransferLastUses.empty()) {
1028     Pass *My_PM = getAsPass();
1029     TPM->setLastUser(TransferLastUses, My_PM);
1030     TransferLastUses.clear();
1031   }
1032
1033   // Now, take care of required analyses that are not available.
1034   for (SmallVectorImpl<AnalysisID>::iterator
1035          I = ReqAnalysisNotAvailable.begin(),
1036          E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1037     const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1038     Pass *AnalysisPass = PI->createPass();
1039     this->addLowerLevelRequiredPass(P, AnalysisPass);
1040   }
1041
1042   // Take a note of analysis required and made available by this pass.
1043   // Remove the analysis not preserved by this pass
1044   removeNotPreservedAnalysis(P);
1045   recordAvailableAnalysis(P);
1046
1047   // Add pass
1048   PassVector.push_back(P);
1049 }
1050
1051
1052 /// Populate RP with analysis pass that are required by
1053 /// pass P and are available. Populate RP_NotAvail with analysis
1054 /// pass that are required by pass P but are not available.
1055 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1056                                        SmallVectorImpl<AnalysisID> &RP_NotAvail,
1057                                             Pass *P) {
1058   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1059   const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1060   for (AnalysisUsage::VectorType::const_iterator
1061          I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1062     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1063       RP.push_back(AnalysisPass);
1064     else
1065       RP_NotAvail.push_back(*I);
1066   }
1067
1068   const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1069   for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1070          E = IDs.end(); I != E; ++I) {
1071     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1072       RP.push_back(AnalysisPass);
1073     else
1074       RP_NotAvail.push_back(*I);
1075   }
1076 }
1077
1078 // All Required analyses should be available to the pass as it runs!  Here
1079 // we fill in the AnalysisImpls member of the pass so that it can
1080 // successfully use the getAnalysis() method to retrieve the
1081 // implementations it needs.
1082 //
1083 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1084   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1085
1086   for (AnalysisUsage::VectorType::const_iterator
1087          I = AnUsage->getRequiredSet().begin(),
1088          E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1089     Pass *Impl = findAnalysisPass(*I, true);
1090     if (Impl == 0)
1091       // This may be analysis pass that is initialized on the fly.
1092       // If that is not the case then it will raise an assert when it is used.
1093       continue;
1094     AnalysisResolver *AR = P->getResolver();
1095     assert(AR && "Analysis Resolver is not set");
1096     AR->addAnalysisImplsPair(*I, Impl);
1097   }
1098 }
1099
1100 /// Find the pass that implements Analysis AID. If desired pass is not found
1101 /// then return NULL.
1102 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1103
1104   // Check if AvailableAnalysis map has one entry.
1105   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
1106
1107   if (I != AvailableAnalysis.end())
1108     return I->second;
1109
1110   // Search Parents through TopLevelManager
1111   if (SearchParent)
1112     return TPM->findAnalysisPass(AID);
1113
1114   return NULL;
1115 }
1116
1117 // Print list of passes that are last used by P.
1118 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1119
1120   SmallVector<Pass *, 12> LUses;
1121
1122   // If this is a on the fly manager then it does not have TPM.
1123   if (!TPM)
1124     return;
1125
1126   TPM->collectLastUses(LUses, P);
1127
1128   for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1129          E = LUses.end(); I != E; ++I) {
1130     llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1131     (*I)->dumpPassStructure(0);
1132   }
1133 }
1134
1135 void PMDataManager::dumpPassArguments() const {
1136   for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1137         E = PassVector.end(); I != E; ++I) {
1138     if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1139       PMD->dumpPassArguments();
1140     else
1141       if (const PassInfo *PI =
1142             PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1143         if (!PI->isAnalysisGroup())
1144           dbgs() << " -" << PI->getPassArgument();
1145   }
1146 }
1147
1148 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1149                                  enum PassDebuggingString S2,
1150                                  StringRef Msg) {
1151   if (PassDebugging < Executions)
1152     return;
1153   dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1154   switch (S1) {
1155   case EXECUTION_MSG:
1156     dbgs() << "Executing Pass '" << P->getPassName();
1157     break;
1158   case MODIFICATION_MSG:
1159     dbgs() << "Made Modification '" << P->getPassName();
1160     break;
1161   case FREEING_MSG:
1162     dbgs() << " Freeing Pass '" << P->getPassName();
1163     break;
1164   default:
1165     break;
1166   }
1167   switch (S2) {
1168   case ON_BASICBLOCK_MSG:
1169     dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1170     break;
1171   case ON_FUNCTION_MSG:
1172     dbgs() << "' on Function '" << Msg << "'...\n";
1173     break;
1174   case ON_MODULE_MSG:
1175     dbgs() << "' on Module '"  << Msg << "'...\n";
1176     break;
1177   case ON_REGION_MSG:
1178     dbgs() << "' on Region '"  << Msg << "'...\n";
1179     break;
1180   case ON_LOOP_MSG:
1181     dbgs() << "' on Loop '" << Msg << "'...\n";
1182     break;
1183   case ON_CG_MSG:
1184     dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1185     break;
1186   default:
1187     break;
1188   }
1189 }
1190
1191 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1192   if (PassDebugging < Details)
1193     return;
1194
1195   AnalysisUsage analysisUsage;
1196   P->getAnalysisUsage(analysisUsage);
1197   dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1198 }
1199
1200 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1201   if (PassDebugging < Details)
1202     return;
1203
1204   AnalysisUsage analysisUsage;
1205   P->getAnalysisUsage(analysisUsage);
1206   dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1207 }
1208
1209 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1210                                    const AnalysisUsage::VectorType &Set) const {
1211   assert(PassDebugging >= Details);
1212   if (Set.empty())
1213     return;
1214   dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1215   for (unsigned i = 0; i != Set.size(); ++i) {
1216     if (i) dbgs() << ',';
1217     const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1218     if (!PInf) {
1219       // Some preserved passes, such as AliasAnalysis, may not be initialized by
1220       // all drivers.
1221       dbgs() << " Uninitialized Pass";
1222       continue;
1223     }
1224     dbgs() << ' ' << PInf->getPassName();
1225   }
1226   dbgs() << '\n';
1227 }
1228
1229 /// Add RequiredPass into list of lower level passes required by pass P.
1230 /// RequiredPass is run on the fly by Pass Manager when P requests it
1231 /// through getAnalysis interface.
1232 /// This should be handled by specific pass manager.
1233 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1234   if (TPM) {
1235     TPM->dumpArguments();
1236     TPM->dumpPasses();
1237   }
1238
1239   // Module Level pass may required Function Level analysis info
1240   // (e.g. dominator info). Pass manager uses on the fly function pass manager
1241   // to provide this on demand. In that case, in Pass manager terminology,
1242   // module level pass is requiring lower level analysis info managed by
1243   // lower level pass manager.
1244
1245   // When Pass manager is not able to order required analysis info, Pass manager
1246   // checks whether any lower level manager will be able to provide this
1247   // analysis info on demand or not.
1248 #ifndef NDEBUG
1249   dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1250   dbgs() << "' required by '" << P->getPassName() << "'\n";
1251 #endif
1252   llvm_unreachable("Unable to schedule pass");
1253 }
1254
1255 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1256   llvm_unreachable("Unable to find on the fly pass");
1257 }
1258
1259 // Destructor
1260 PMDataManager::~PMDataManager() {
1261   for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1262          E = PassVector.end(); I != E; ++I)
1263     delete *I;
1264 }
1265
1266 //===----------------------------------------------------------------------===//
1267 // NOTE: Is this the right place to define this method ?
1268 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1269 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1270   return PM.findAnalysisPass(ID, dir);
1271 }
1272
1273 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1274                                      Function &F) {
1275   return PM.getOnTheFlyPass(P, AnalysisPI, F);
1276 }
1277
1278 //===----------------------------------------------------------------------===//
1279 // BBPassManager implementation
1280
1281 /// Execute all of the passes scheduled for execution by invoking
1282 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies
1283 /// the function, and if so, return true.
1284 bool BBPassManager::runOnFunction(Function &F) {
1285   if (F.isDeclaration())
1286     return false;
1287
1288   bool Changed = doInitialization(F);
1289
1290   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1291     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1292       BasicBlockPass *BP = getContainedPass(Index);
1293       bool LocalChanged = false;
1294
1295       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1296       dumpRequiredSet(BP);
1297
1298       initializeAnalysisImpl(BP);
1299
1300       {
1301         // If the pass crashes, remember this.
1302         PassManagerPrettyStackEntry X(BP, *I);
1303         TimeRegion PassTimer(getPassTimer(BP));
1304
1305         LocalChanged |= BP->runOnBasicBlock(*I);
1306       }
1307
1308       Changed |= LocalChanged;
1309       if (LocalChanged)
1310         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1311                      I->getName());
1312       dumpPreservedSet(BP);
1313
1314       verifyPreservedAnalysis(BP);
1315       removeNotPreservedAnalysis(BP);
1316       recordAvailableAnalysis(BP);
1317       removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1318     }
1319
1320   return doFinalization(F) || Changed;
1321 }
1322
1323 // Implement doInitialization and doFinalization
1324 bool BBPassManager::doInitialization(Module &M) {
1325   bool Changed = false;
1326
1327   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1328     Changed |= getContainedPass(Index)->doInitialization(M);
1329
1330   return Changed;
1331 }
1332
1333 bool BBPassManager::doFinalization(Module &M) {
1334   bool Changed = false;
1335
1336   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1337     Changed |= getContainedPass(Index)->doFinalization(M);
1338
1339   return Changed;
1340 }
1341
1342 bool BBPassManager::doInitialization(Function &F) {
1343   bool Changed = false;
1344
1345   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1346     BasicBlockPass *BP = getContainedPass(Index);
1347     Changed |= BP->doInitialization(F);
1348   }
1349
1350   return Changed;
1351 }
1352
1353 bool BBPassManager::doFinalization(Function &F) {
1354   bool Changed = false;
1355
1356   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1357     BasicBlockPass *BP = getContainedPass(Index);
1358     Changed |= BP->doFinalization(F);
1359   }
1360
1361   return Changed;
1362 }
1363
1364
1365 //===----------------------------------------------------------------------===//
1366 // FunctionPassManager implementation
1367
1368 /// Create new Function pass manager
1369 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1370   FPM = new FunctionPassManagerImpl();
1371   // FPM is the top level manager.
1372   FPM->setTopLevelManager(FPM);
1373
1374   AnalysisResolver *AR = new AnalysisResolver(*FPM);
1375   FPM->setResolver(AR);
1376 }
1377
1378 FunctionPassManager::~FunctionPassManager() {
1379   delete FPM;
1380 }
1381
1382 /// add - Add a pass to the queue of passes to run.  This passes
1383 /// ownership of the Pass to the PassManager.  When the
1384 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1385 /// there is no need to delete the pass. (TODO delete passes.)
1386 /// This implies that all passes MUST be allocated with 'new'.
1387 void FunctionPassManager::add(Pass *P) {
1388   FPM->add(P);
1389 }
1390
1391 /// run - Execute all of the passes scheduled for execution.  Keep
1392 /// track of whether any of the passes modifies the function, and if
1393 /// so, return true.
1394 ///
1395 bool FunctionPassManager::run(Function &F) {
1396   if (F.isMaterializable()) {
1397     std::string errstr;
1398     if (F.Materialize(&errstr))
1399       report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1400   }
1401   return FPM->run(F);
1402 }
1403
1404
1405 /// doInitialization - Run all of the initializers for the function passes.
1406 ///
1407 bool FunctionPassManager::doInitialization() {
1408   return FPM->doInitialization(*M);
1409 }
1410
1411 /// doFinalization - Run all of the finalizers for the function passes.
1412 ///
1413 bool FunctionPassManager::doFinalization() {
1414   return FPM->doFinalization(*M);
1415 }
1416
1417 //===----------------------------------------------------------------------===//
1418 // FunctionPassManagerImpl implementation
1419 //
1420 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1421   bool Changed = false;
1422
1423   dumpArguments();
1424   dumpPasses();
1425
1426   SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1427   for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1428        E = IPV.end(); I != E; ++I) {
1429     Changed |= (*I)->doInitialization(M);
1430   }
1431
1432   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1433     Changed |= getContainedManager(Index)->doInitialization(M);
1434
1435   return Changed;
1436 }
1437
1438 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1439   bool Changed = false;
1440
1441   for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1442     Changed |= getContainedManager(Index)->doFinalization(M);
1443
1444   SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1445   for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1446        E = IPV.end(); I != E; ++I) {
1447     Changed |= (*I)->doFinalization(M);
1448   }
1449
1450   return Changed;
1451 }
1452
1453 /// cleanup - After running all passes, clean up pass manager cache.
1454 void FPPassManager::cleanup() {
1455  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1456     FunctionPass *FP = getContainedPass(Index);
1457     AnalysisResolver *AR = FP->getResolver();
1458     assert(AR && "Analysis Resolver is not set");
1459     AR->clearAnalysisImpls();
1460  }
1461 }
1462
1463 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1464   if (!wasRun)
1465     return;
1466   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1467     FPPassManager *FPPM = getContainedManager(Index);
1468     for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1469       FPPM->getContainedPass(Index)->releaseMemory();
1470     }
1471   }
1472   wasRun = false;
1473 }
1474
1475 // Execute all the passes managed by this top level manager.
1476 // Return true if any function is modified by a pass.
1477 bool FunctionPassManagerImpl::run(Function &F) {
1478   bool Changed = false;
1479   TimingInfo::createTheTimeInfo();
1480
1481   initializeAllAnalysisInfo();
1482   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1483     Changed |= getContainedManager(Index)->runOnFunction(F);
1484
1485   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1486     getContainedManager(Index)->cleanup();
1487
1488   wasRun = true;
1489   return Changed;
1490 }
1491
1492 //===----------------------------------------------------------------------===//
1493 // FPPassManager implementation
1494
1495 char FPPassManager::ID = 0;
1496 /// Print passes managed by this manager
1497 void FPPassManager::dumpPassStructure(unsigned Offset) {
1498   dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1499   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1500     FunctionPass *FP = getContainedPass(Index);
1501     FP->dumpPassStructure(Offset + 1);
1502     dumpLastUses(FP, Offset+1);
1503   }
1504 }
1505
1506
1507 /// Execute all of the passes scheduled for execution by invoking
1508 /// runOnFunction method.  Keep track of whether any of the passes modifies
1509 /// the function, and if so, return true.
1510 bool FPPassManager::runOnFunction(Function &F) {
1511   if (F.isDeclaration())
1512     return false;
1513
1514   bool Changed = false;
1515
1516   // Collect inherited analysis from Module level pass manager.
1517   populateInheritedAnalysis(TPM->activeStack);
1518
1519   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1520     FunctionPass *FP = getContainedPass(Index);
1521     bool LocalChanged = false;
1522
1523     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1524     dumpRequiredSet(FP);
1525
1526     initializeAnalysisImpl(FP);
1527
1528     {
1529       PassManagerPrettyStackEntry X(FP, F);
1530       TimeRegion PassTimer(getPassTimer(FP));
1531
1532       LocalChanged |= FP->runOnFunction(F);
1533     }
1534
1535     Changed |= LocalChanged;
1536     if (LocalChanged)
1537       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1538     dumpPreservedSet(FP);
1539
1540     verifyPreservedAnalysis(FP);
1541     removeNotPreservedAnalysis(FP);
1542     recordAvailableAnalysis(FP);
1543     removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1544   }
1545   return Changed;
1546 }
1547
1548 bool FPPassManager::runOnModule(Module &M) {
1549   bool Changed = false;
1550
1551   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1552     Changed |= runOnFunction(*I);
1553
1554   return Changed;
1555 }
1556
1557 bool FPPassManager::doInitialization(Module &M) {
1558   bool Changed = false;
1559
1560   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1561     Changed |= getContainedPass(Index)->doInitialization(M);
1562   
1563   return Changed;
1564 }
1565
1566 bool FPPassManager::doFinalization(Module &M) {
1567   bool Changed = false;
1568
1569   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1570     Changed |= getContainedPass(Index)->doFinalization(M);
1571   
1572   return Changed;
1573 }
1574
1575 //===----------------------------------------------------------------------===//
1576 // MPPassManager implementation
1577
1578 /// Execute all of the passes scheduled for execution by invoking
1579 /// runOnModule method.  Keep track of whether any of the passes modifies
1580 /// the module, and if so, return true.
1581 bool
1582 MPPassManager::runOnModule(Module &M) {
1583   bool Changed = false;
1584
1585   // Initialize on-the-fly passes
1586   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1587        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1588        I != E; ++I) {
1589     FunctionPassManagerImpl *FPP = I->second;
1590     Changed |= FPP->doInitialization(M);
1591   }
1592
1593   // Initialize module passes
1594   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1595     Changed |= getContainedPass(Index)->doInitialization(M);
1596
1597   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1598     ModulePass *MP = getContainedPass(Index);
1599     bool LocalChanged = false;
1600
1601     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1602     dumpRequiredSet(MP);
1603
1604     initializeAnalysisImpl(MP);
1605
1606     {
1607       PassManagerPrettyStackEntry X(MP, M);
1608       TimeRegion PassTimer(getPassTimer(MP));
1609
1610       LocalChanged |= MP->runOnModule(M);
1611     }
1612
1613     Changed |= LocalChanged;
1614     if (LocalChanged)
1615       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1616                    M.getModuleIdentifier());
1617     dumpPreservedSet(MP);
1618
1619     verifyPreservedAnalysis(MP);
1620     removeNotPreservedAnalysis(MP);
1621     recordAvailableAnalysis(MP);
1622     removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1623   }
1624
1625   // Finalize module passes
1626   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1627     Changed |= getContainedPass(Index)->doFinalization(M);
1628
1629   // Finalize on-the-fly passes
1630   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1631        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1632        I != E; ++I) {
1633     FunctionPassManagerImpl *FPP = I->second;
1634     // We don't know when is the last time an on-the-fly pass is run,
1635     // so we need to releaseMemory / finalize here
1636     FPP->releaseMemoryOnTheFly();
1637     Changed |= FPP->doFinalization(M);
1638   }
1639   
1640   return Changed;
1641 }
1642
1643 /// Add RequiredPass into list of lower level passes required by pass P.
1644 /// RequiredPass is run on the fly by Pass Manager when P requests it
1645 /// through getAnalysis interface.
1646 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1647   assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1648          "Unable to handle Pass that requires lower level Analysis pass");
1649   assert((P->getPotentialPassManagerType() <
1650           RequiredPass->getPotentialPassManagerType()) &&
1651          "Unable to handle Pass that requires lower level Analysis pass");
1652
1653   FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1654   if (!FPP) {
1655     FPP = new FunctionPassManagerImpl();
1656     // FPP is the top level manager.
1657     FPP->setTopLevelManager(FPP);
1658
1659     OnTheFlyManagers[P] = FPP;
1660   }
1661   FPP->add(RequiredPass);
1662
1663   // Register P as the last user of RequiredPass.
1664   if (RequiredPass) {
1665     SmallVector<Pass *, 1> LU;
1666     LU.push_back(RequiredPass);
1667     FPP->setLastUser(LU,  P);
1668   }
1669 }
1670
1671 /// Return function pass corresponding to PassInfo PI, that is
1672 /// required by module pass MP. Instantiate analysis pass, by using
1673 /// its runOnFunction() for function F.
1674 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1675   FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1676   assert(FPP && "Unable to find on the fly pass");
1677
1678   FPP->releaseMemoryOnTheFly();
1679   FPP->run(F);
1680   return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1681 }
1682
1683
1684 //===----------------------------------------------------------------------===//
1685 // PassManagerImpl implementation
1686
1687 //
1688 /// run - Execute all of the passes scheduled for execution.  Keep track of
1689 /// whether any of the passes modifies the module, and if so, return true.
1690 bool PassManagerImpl::run(Module &M) {
1691   bool Changed = false;
1692   TimingInfo::createTheTimeInfo();
1693
1694   dumpArguments();
1695   dumpPasses();
1696
1697   SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1698   for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1699        E = IPV.end(); I != E; ++I) {
1700     Changed |= (*I)->doInitialization(M);
1701   }
1702
1703   initializeAllAnalysisInfo();
1704   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1705     Changed |= getContainedManager(Index)->runOnModule(M);
1706
1707   for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1708        E = IPV.end(); I != E; ++I) {
1709     Changed |= (*I)->doFinalization(M);
1710   }
1711
1712   return Changed;
1713 }
1714
1715 //===----------------------------------------------------------------------===//
1716 // PassManager implementation
1717
1718 /// Create new pass manager
1719 PassManager::PassManager() {
1720   PM = new PassManagerImpl();
1721   // PM is the top level manager
1722   PM->setTopLevelManager(PM);
1723 }
1724
1725 PassManager::~PassManager() {
1726   delete PM;
1727 }
1728
1729 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1730 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1731 /// will be destroyed as well, so there is no need to delete the pass.  This
1732 /// implies that all passes MUST be allocated with 'new'.
1733 void PassManager::add(Pass *P) {
1734   PM->add(P);
1735 }
1736
1737 /// run - Execute all of the passes scheduled for execution.  Keep track of
1738 /// whether any of the passes modifies the module, and if so, return true.
1739 bool PassManager::run(Module &M) {
1740   return PM->run(M);
1741 }
1742
1743 //===----------------------------------------------------------------------===//
1744 // TimingInfo Class - This class is used to calculate information about the
1745 // amount of time each pass takes to execute.  This only happens with
1746 // -time-passes is enabled on the command line.
1747 //
1748 bool llvm::TimePassesIsEnabled = false;
1749 static cl::opt<bool,true>
1750 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1751             cl::desc("Time each pass, printing elapsed time for each on exit"));
1752
1753 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1754 // a non null value (if the -time-passes option is enabled) or it leaves it
1755 // null.  It may be called multiple times.
1756 void TimingInfo::createTheTimeInfo() {
1757   if (!TimePassesIsEnabled || TheTimeInfo) return;
1758
1759   // Constructed the first time this is called, iff -time-passes is enabled.
1760   // This guarantees that the object will be constructed before static globals,
1761   // thus it will be destroyed before them.
1762   static ManagedStatic<TimingInfo> TTI;
1763   TheTimeInfo = &*TTI;
1764 }
1765
1766 /// If TimingInfo is enabled then start pass timer.
1767 Timer *llvm::getPassTimer(Pass *P) {
1768   if (TheTimeInfo)
1769     return TheTimeInfo->getPassTimer(P);
1770   return 0;
1771 }
1772
1773 //===----------------------------------------------------------------------===//
1774 // PMStack implementation
1775 //
1776
1777 // Pop Pass Manager from the stack and clear its analysis info.
1778 void PMStack::pop() {
1779
1780   PMDataManager *Top = this->top();
1781   Top->initializeAnalysisInfo();
1782
1783   S.pop_back();
1784 }
1785
1786 // Push PM on the stack and set its top level manager.
1787 void PMStack::push(PMDataManager *PM) {
1788   assert(PM && "Unable to push. Pass Manager expected");
1789   assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1790
1791   if (!this->empty()) {
1792     assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1793            && "pushing bad pass manager to PMStack");
1794     PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1795
1796     assert(TPM && "Unable to find top level manager");
1797     TPM->addIndirectPassManager(PM);
1798     PM->setTopLevelManager(TPM);
1799     PM->setDepth(this->top()->getDepth()+1);
1800   }
1801   else {
1802     assert((PM->getPassManagerType() == PMT_ModulePassManager
1803            || PM->getPassManagerType() == PMT_FunctionPassManager)
1804            && "pushing bad pass manager to PMStack");
1805     PM->setDepth(1);
1806   }
1807
1808   S.push_back(PM);
1809 }
1810
1811 // Dump content of the pass manager stack.
1812 void PMStack::dump() const {
1813   for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1814          E = S.end(); I != E; ++I)
1815     dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1816
1817   if (!S.empty())
1818     dbgs() << '\n';
1819 }
1820
1821 /// Find appropriate Module Pass Manager in the PM Stack and
1822 /// add self into that manager.
1823 void ModulePass::assignPassManager(PMStack &PMS,
1824                                    PassManagerType PreferredType) {
1825   // Find Module Pass Manager
1826   while (!PMS.empty()) {
1827     PassManagerType TopPMType = PMS.top()->getPassManagerType();
1828     if (TopPMType == PreferredType)
1829       break; // We found desired pass manager
1830     else if (TopPMType > PMT_ModulePassManager)
1831       PMS.pop();    // Pop children pass managers
1832     else
1833       break;
1834   }
1835   assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1836   PMS.top()->add(this);
1837 }
1838
1839 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1840 /// in the PM Stack and add self into that manager.
1841 void FunctionPass::assignPassManager(PMStack &PMS,
1842                                      PassManagerType PreferredType) {
1843
1844   // Find Function Pass Manager
1845   while (!PMS.empty()) {
1846     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1847       PMS.pop();
1848     else
1849       break;
1850   }
1851
1852   // Create new Function Pass Manager if needed.
1853   FPPassManager *FPP;
1854   if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1855     FPP = (FPPassManager *)PMS.top();
1856   } else {
1857     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1858     PMDataManager *PMD = PMS.top();
1859
1860     // [1] Create new Function Pass Manager
1861     FPP = new FPPassManager();
1862     FPP->populateInheritedAnalysis(PMS);
1863
1864     // [2] Set up new manager's top level manager
1865     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1866     TPM->addIndirectPassManager(FPP);
1867
1868     // [3] Assign manager to manage this new manager. This may create
1869     // and push new managers into PMS
1870     FPP->assignPassManager(PMS, PMD->getPassManagerType());
1871
1872     // [4] Push new manager into PMS
1873     PMS.push(FPP);
1874   }
1875
1876   // Assign FPP as the manager of this pass.
1877   FPP->add(this);
1878 }
1879
1880 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1881 /// in the PM Stack and add self into that manager.
1882 void BasicBlockPass::assignPassManager(PMStack &PMS,
1883                                        PassManagerType PreferredType) {
1884   BBPassManager *BBP;
1885
1886   // Basic Pass Manager is a leaf pass manager. It does not handle
1887   // any other pass manager.
1888   if (!PMS.empty() &&
1889       PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1890     BBP = (BBPassManager *)PMS.top();
1891   } else {
1892     // If leaf manager is not Basic Block Pass manager then create new
1893     // basic Block Pass manager.
1894     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1895     PMDataManager *PMD = PMS.top();
1896
1897     // [1] Create new Basic Block Manager
1898     BBP = new BBPassManager();
1899
1900     // [2] Set up new manager's top level manager
1901     // Basic Block Pass Manager does not live by itself
1902     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1903     TPM->addIndirectPassManager(BBP);
1904
1905     // [3] Assign manager to manage this new manager. This may create
1906     // and push new managers into PMS
1907     BBP->assignPassManager(PMS, PreferredType);
1908
1909     // [4] Push new manager into PMS
1910     PMS.push(BBP);
1911   }
1912
1913   // Assign BBP as the manager of this pass.
1914   BBP->add(this);
1915 }
1916
1917 PassManagerBase::~PassManagerBase() {}