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