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