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