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