]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/lib/VMCore/PassManager.cpp
MFC r234353:
[FreeBSD/stable/9.git] / contrib / llvm / 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(const SmallVectorImpl<Pass *> &AnalysisPasses,
482                                Pass *P) {
483   unsigned PDepth = 0;
484   if (P->getResolver())
485     PDepth = P->getResolver()->getPMDataManager().getDepth();
486
487   for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
488          E = AnalysisPasses.end(); I != E; ++I) {
489     Pass *AP = *I;
490     LastUser[AP] = P;
491
492     if (P == AP)
493       continue;
494
495     // Update the last users of passes that are required transitive by AP.
496     AnalysisUsage *AnUsage = findAnalysisUsage(AP);
497     const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
498     SmallVector<Pass *, 12> LastUses;
499     SmallVector<Pass *, 12> LastPMUses;
500     for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
501          E = IDs.end(); I != E; ++I) {
502       Pass *AnalysisPass = findAnalysisPass(*I);
503       assert(AnalysisPass && "Expected analysis pass to exist.");
504       AnalysisResolver *AR = AnalysisPass->getResolver();
505       assert(AR && "Expected analysis resolver to exist.");
506       unsigned APDepth = AR->getPMDataManager().getDepth();
507
508       if (PDepth == APDepth)
509         LastUses.push_back(AnalysisPass);
510       else if (PDepth > APDepth)
511         LastPMUses.push_back(AnalysisPass);
512     }
513
514     setLastUser(LastUses, P);
515
516     // If this pass has a corresponding pass manager, push higher level
517     // analysis to this pass manager.
518     if (P->getResolver())
519       setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
520
521
522     // If AP is the last user of other passes then make P last user of
523     // such passes.
524     for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
525            LUE = LastUser.end(); LUI != LUE; ++LUI) {
526       if (LUI->second == AP)
527         // DenseMap iterator is not invalidated here because
528         // this is just updating existing entries.
529         LastUser[LUI->first] = P;
530     }
531   }
532 }
533
534 /// Collect passes whose last user is P
535 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
536                                         Pass *P) {
537   DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
538     InversedLastUser.find(P);
539   if (DMI == InversedLastUser.end())
540     return;
541
542   SmallPtrSet<Pass *, 8> &LU = DMI->second;
543   for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
544          E = LU.end(); I != E; ++I) {
545     LastUses.push_back(*I);
546   }
547
548 }
549
550 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
551   AnalysisUsage *AnUsage = NULL;
552   DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
553   if (DMI != AnUsageMap.end())
554     AnUsage = DMI->second;
555   else {
556     AnUsage = new AnalysisUsage();
557     P->getAnalysisUsage(*AnUsage);
558     AnUsageMap[P] = AnUsage;
559   }
560   return AnUsage;
561 }
562
563 /// Schedule pass P for execution. Make sure that passes required by
564 /// P are run before P is run. Update analysis info maintained by
565 /// the manager. Remove dead passes. This is a recursive function.
566 void PMTopLevelManager::schedulePass(Pass *P) {
567
568   // TODO : Allocate function manager for this pass, other wise required set
569   // may be inserted into previous function manager
570
571   // Give pass a chance to prepare the stage.
572   P->preparePassManager(activeStack);
573
574   // If P is an analysis pass and it is available then do not
575   // generate the analysis again. Stale analysis info should not be
576   // available at this point.
577   const PassInfo *PI =
578     PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
579   if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
580     delete P;
581     return;
582   }
583
584   AnalysisUsage *AnUsage = findAnalysisUsage(P);
585
586   bool checkAnalysis = true;
587   while (checkAnalysis) {
588     checkAnalysis = false;
589
590     const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
591     for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
592            E = RequiredSet.end(); I != E; ++I) {
593
594       Pass *AnalysisPass = findAnalysisPass(*I);
595       if (!AnalysisPass) {
596         const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
597         assert(PI && "Expected required passes to be initialized");
598         AnalysisPass = PI->createPass();
599         if (P->getPotentialPassManagerType () ==
600             AnalysisPass->getPotentialPassManagerType())
601           // Schedule analysis pass that is managed by the same pass manager.
602           schedulePass(AnalysisPass);
603         else if (P->getPotentialPassManagerType () >
604                  AnalysisPass->getPotentialPassManagerType()) {
605           // Schedule analysis pass that is managed by a new manager.
606           schedulePass(AnalysisPass);
607           // Recheck analysis passes to ensure that required analyses that
608           // are already checked are still available.
609           checkAnalysis = true;
610         }
611         else
612           // Do not schedule this analysis. Lower level analsyis
613           // passes are run on the fly.
614           delete AnalysisPass;
615       }
616     }
617   }
618
619   // Now all required passes are available.
620   if (ImmutablePass *IP = P->getAsImmutablePass()) {
621     // P is a immutable pass and it will be managed by this
622     // top level manager. Set up analysis resolver to connect them.
623     PMDataManager *DM = getAsPMDataManager();
624     AnalysisResolver *AR = new AnalysisResolver(*DM);
625     P->setResolver(AR);
626     DM->initializeAnalysisImpl(P);
627     addImmutablePass(IP);
628     DM->recordAvailableAnalysis(IP);
629     return;
630   }
631
632   if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
633     Pass *PP = P->createPrinterPass(
634       dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
635     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
636   }
637
638   // Add the requested pass to the best available pass manager.
639   P->assignPassManager(activeStack, getTopLevelPassManagerType());
640
641   if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
642     Pass *PP = P->createPrinterPass(
643       dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
644     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
645   }
646 }
647
648 /// Find the pass that implements Analysis AID. Search immutable
649 /// passes and all pass managers. If desired pass is not found
650 /// then return NULL.
651 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
652
653   // Check pass managers
654   for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
655          E = PassManagers.end(); I != E; ++I)
656     if (Pass *P = (*I)->findAnalysisPass(AID, false))
657       return P;
658
659   // Check other pass managers
660   for (SmallVectorImpl<PMDataManager *>::iterator
661          I = IndirectPassManagers.begin(),
662          E = IndirectPassManagers.end(); I != E; ++I)
663     if (Pass *P = (*I)->findAnalysisPass(AID, false))
664       return P;
665
666   // Check the immutable passes. Iterate in reverse order so that we find
667   // the most recently registered passes first.
668   for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
669        ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
670     AnalysisID PI = (*I)->getPassID();
671     if (PI == AID)
672       return *I;
673
674     // If Pass not found then check the interfaces implemented by Immutable Pass
675     const PassInfo *PassInf =
676       PassRegistry::getPassRegistry()->getPassInfo(PI);
677     assert(PassInf && "Expected all immutable passes to be initialized");
678     const std::vector<const PassInfo*> &ImmPI =
679       PassInf->getInterfacesImplemented();
680     for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
681          EE = ImmPI.end(); II != EE; ++II) {
682       if ((*II)->getTypeInfo() == AID)
683         return *I;
684     }
685   }
686
687   return 0;
688 }
689
690 // Print passes managed by this top level manager.
691 void PMTopLevelManager::dumpPasses() const {
692
693   if (PassDebugging < Structure)
694     return;
695
696   // Print out the immutable passes
697   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
698     ImmutablePasses[i]->dumpPassStructure(0);
699   }
700
701   // Every class that derives from PMDataManager also derives from Pass
702   // (sometimes indirectly), but there's no inheritance relationship
703   // between PMDataManager and Pass, so we have to getAsPass to get
704   // from a PMDataManager* to a Pass*.
705   for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
706          E = PassManagers.end(); I != E; ++I)
707     (*I)->getAsPass()->dumpPassStructure(1);
708 }
709
710 void PMTopLevelManager::dumpArguments() const {
711
712   if (PassDebugging < Arguments)
713     return;
714
715   dbgs() << "Pass Arguments: ";
716   for (SmallVector<ImmutablePass *, 8>::const_iterator I =
717        ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
718     if (const PassInfo *PI =
719         PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
720       assert(PI && "Expected all immutable passes to be initialized");
721       if (!PI->isAnalysisGroup())
722         dbgs() << " -" << PI->getPassArgument();
723     }
724   for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
725          E = PassManagers.end(); I != E; ++I)
726     (*I)->dumpPassArguments();
727   dbgs() << "\n";
728 }
729
730 void PMTopLevelManager::initializeAllAnalysisInfo() {
731   for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
732          E = PassManagers.end(); I != E; ++I)
733     (*I)->initializeAnalysisInfo();
734
735   // Initailize other pass managers
736   for (SmallVectorImpl<PMDataManager *>::iterator
737        I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
738        I != E; ++I)
739     (*I)->initializeAnalysisInfo();
740
741   for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
742         DME = LastUser.end(); DMI != DME; ++DMI) {
743     DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
744       InversedLastUser.find(DMI->second);
745     if (InvDMI != InversedLastUser.end()) {
746       SmallPtrSet<Pass *, 8> &L = InvDMI->second;
747       L.insert(DMI->first);
748     } else {
749       SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
750       InversedLastUser[DMI->second] = L;
751     }
752   }
753 }
754
755 /// Destructor
756 PMTopLevelManager::~PMTopLevelManager() {
757   for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
758          E = PassManagers.end(); I != E; ++I)
759     delete *I;
760
761   for (SmallVectorImpl<ImmutablePass *>::iterator
762          I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
763     delete *I;
764
765   for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
766          DME = AnUsageMap.end(); DMI != DME; ++DMI)
767     delete DMI->second;
768 }
769
770 //===----------------------------------------------------------------------===//
771 // PMDataManager implementation
772
773 /// Augement AvailableAnalysis by adding analysis made available by pass P.
774 void PMDataManager::recordAvailableAnalysis(Pass *P) {
775   AnalysisID PI = P->getPassID();
776
777   AvailableAnalysis[PI] = P;
778
779   assert(!AvailableAnalysis.empty());
780
781   // This pass is the current implementation of all of the interfaces it
782   // implements as well.
783   const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
784   if (PInf == 0) return;
785   const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
786   for (unsigned i = 0, e = II.size(); i != e; ++i)
787     AvailableAnalysis[II[i]->getTypeInfo()] = P;
788 }
789
790 // Return true if P preserves high level analysis used by other
791 // passes managed by this manager
792 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
793   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
794   if (AnUsage->getPreservesAll())
795     return true;
796
797   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
798   for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
799          E = HigherLevelAnalysis.end(); I  != E; ++I) {
800     Pass *P1 = *I;
801     if (P1->getAsImmutablePass() == 0 &&
802         std::find(PreservedSet.begin(), PreservedSet.end(),
803                   P1->getPassID()) ==
804            PreservedSet.end())
805       return false;
806   }
807
808   return true;
809 }
810
811 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
812 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
813   // Don't do this unless assertions are enabled.
814 #ifdef NDEBUG
815   return;
816 #endif
817   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
818   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
819
820   // Verify preserved analysis
821   for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
822          E = PreservedSet.end(); I != E; ++I) {
823     AnalysisID AID = *I;
824     if (Pass *AP = findAnalysisPass(AID, true)) {
825       TimeRegion PassTimer(getPassTimer(AP));
826       AP->verifyAnalysis();
827     }
828   }
829 }
830
831 /// Remove Analysis not preserved by Pass P
832 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
833   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
834   if (AnUsage->getPreservesAll())
835     return;
836
837   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
838   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
839          E = AvailableAnalysis.end(); I != E; ) {
840     std::map<AnalysisID, Pass*>::iterator Info = I++;
841     if (Info->second->getAsImmutablePass() == 0 &&
842         std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
843         PreservedSet.end()) {
844       // Remove this analysis
845       if (PassDebugging >= Details) {
846         Pass *S = Info->second;
847         dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
848         dbgs() << S->getPassName() << "'\n";
849       }
850       AvailableAnalysis.erase(Info);
851     }
852   }
853
854   // Check inherited analysis also. If P is not preserving analysis
855   // provided by parent manager then remove it here.
856   for (unsigned Index = 0; Index < PMT_Last; ++Index) {
857
858     if (!InheritedAnalysis[Index])
859       continue;
860
861     for (std::map<AnalysisID, Pass*>::iterator
862            I = InheritedAnalysis[Index]->begin(),
863            E = InheritedAnalysis[Index]->end(); I != E; ) {
864       std::map<AnalysisID, Pass *>::iterator Info = I++;
865       if (Info->second->getAsImmutablePass() == 0 &&
866           std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
867              PreservedSet.end()) {
868         // Remove this analysis
869         if (PassDebugging >= Details) {
870           Pass *S = Info->second;
871           dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
872           dbgs() << S->getPassName() << "'\n";
873         }
874         InheritedAnalysis[Index]->erase(Info);
875       }
876     }
877   }
878 }
879
880 /// Remove analysis passes that are not used any longer
881 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
882                                      enum PassDebuggingString DBG_STR) {
883
884   SmallVector<Pass *, 12> DeadPasses;
885
886   // If this is a on the fly manager then it does not have TPM.
887   if (!TPM)
888     return;
889
890   TPM->collectLastUses(DeadPasses, P);
891
892   if (PassDebugging >= Details && !DeadPasses.empty()) {
893     dbgs() << " -*- '" <<  P->getPassName();
894     dbgs() << "' is the last user of following pass instances.";
895     dbgs() << " Free these instances\n";
896   }
897
898   for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
899          E = DeadPasses.end(); I != E; ++I)
900     freePass(*I, Msg, DBG_STR);
901 }
902
903 void PMDataManager::freePass(Pass *P, StringRef Msg,
904                              enum PassDebuggingString DBG_STR) {
905   dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
906
907   {
908     // If the pass crashes releasing memory, remember this.
909     PassManagerPrettyStackEntry X(P);
910     TimeRegion PassTimer(getPassTimer(P));
911
912     P->releaseMemory();
913   }
914
915   AnalysisID PI = P->getPassID();
916   if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
917     // Remove the pass itself (if it is not already removed).
918     AvailableAnalysis.erase(PI);
919
920     // Remove all interfaces this pass implements, for which it is also
921     // listed as the available implementation.
922     const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
923     for (unsigned i = 0, e = II.size(); i != e; ++i) {
924       std::map<AnalysisID, Pass*>::iterator Pos =
925         AvailableAnalysis.find(II[i]->getTypeInfo());
926       if (Pos != AvailableAnalysis.end() && Pos->second == P)
927         AvailableAnalysis.erase(Pos);
928     }
929   }
930 }
931
932 /// Add pass P into the PassVector. Update
933 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
934 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
935   // This manager is going to manage pass P. Set up analysis resolver
936   // to connect them.
937   AnalysisResolver *AR = new AnalysisResolver(*this);
938   P->setResolver(AR);
939
940   // If a FunctionPass F is the last user of ModulePass info M
941   // then the F's manager, not F, records itself as a last user of M.
942   SmallVector<Pass *, 12> TransferLastUses;
943
944   if (!ProcessAnalysis) {
945     // Add pass
946     PassVector.push_back(P);
947     return;
948   }
949
950   // At the moment, this pass is the last user of all required passes.
951   SmallVector<Pass *, 12> LastUses;
952   SmallVector<Pass *, 8> RequiredPasses;
953   SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
954
955   unsigned PDepth = this->getDepth();
956
957   collectRequiredAnalysis(RequiredPasses,
958                           ReqAnalysisNotAvailable, P);
959   for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
960          E = RequiredPasses.end(); I != E; ++I) {
961     Pass *PRequired = *I;
962     unsigned RDepth = 0;
963
964     assert(PRequired->getResolver() && "Analysis Resolver is not set");
965     PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
966     RDepth = DM.getDepth();
967
968     if (PDepth == RDepth)
969       LastUses.push_back(PRequired);
970     else if (PDepth > RDepth) {
971       // Let the parent claim responsibility of last use
972       TransferLastUses.push_back(PRequired);
973       // Keep track of higher level analysis used by this manager.
974       HigherLevelAnalysis.push_back(PRequired);
975     } else
976       llvm_unreachable("Unable to accommodate Required Pass");
977   }
978
979   // Set P as P's last user until someone starts using P.
980   // However, if P is a Pass Manager then it does not need
981   // to record its last user.
982   if (P->getAsPMDataManager() == 0)
983     LastUses.push_back(P);
984   TPM->setLastUser(LastUses, P);
985
986   if (!TransferLastUses.empty()) {
987     Pass *My_PM = getAsPass();
988     TPM->setLastUser(TransferLastUses, My_PM);
989     TransferLastUses.clear();
990   }
991
992   // Now, take care of required analyses that are not available.
993   for (SmallVectorImpl<AnalysisID>::iterator
994          I = ReqAnalysisNotAvailable.begin(),
995          E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
996     const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
997     Pass *AnalysisPass = PI->createPass();
998     this->addLowerLevelRequiredPass(P, AnalysisPass);
999   }
1000
1001   // Take a note of analysis required and made available by this pass.
1002   // Remove the analysis not preserved by this pass
1003   removeNotPreservedAnalysis(P);
1004   recordAvailableAnalysis(P);
1005
1006   // Add pass
1007   PassVector.push_back(P);
1008 }
1009
1010
1011 /// Populate RP with analysis pass that are required by
1012 /// pass P and are available. Populate RP_NotAvail with analysis
1013 /// pass that are required by pass P but are not available.
1014 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1015                                        SmallVectorImpl<AnalysisID> &RP_NotAvail,
1016                                             Pass *P) {
1017   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1018   const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1019   for (AnalysisUsage::VectorType::const_iterator
1020          I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1021     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1022       RP.push_back(AnalysisPass);
1023     else
1024       RP_NotAvail.push_back(*I);
1025   }
1026
1027   const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1028   for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1029          E = IDs.end(); I != E; ++I) {
1030     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1031       RP.push_back(AnalysisPass);
1032     else
1033       RP_NotAvail.push_back(*I);
1034   }
1035 }
1036
1037 // All Required analyses should be available to the pass as it runs!  Here
1038 // we fill in the AnalysisImpls member of the pass so that it can
1039 // successfully use the getAnalysis() method to retrieve the
1040 // implementations it needs.
1041 //
1042 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1043   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1044
1045   for (AnalysisUsage::VectorType::const_iterator
1046          I = AnUsage->getRequiredSet().begin(),
1047          E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1048     Pass *Impl = findAnalysisPass(*I, true);
1049     if (Impl == 0)
1050       // This may be analysis pass that is initialized on the fly.
1051       // If that is not the case then it will raise an assert when it is used.
1052       continue;
1053     AnalysisResolver *AR = P->getResolver();
1054     assert(AR && "Analysis Resolver is not set");
1055     AR->addAnalysisImplsPair(*I, Impl);
1056   }
1057 }
1058
1059 /// Find the pass that implements Analysis AID. If desired pass is not found
1060 /// then return NULL.
1061 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1062
1063   // Check if AvailableAnalysis map has one entry.
1064   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
1065
1066   if (I != AvailableAnalysis.end())
1067     return I->second;
1068
1069   // Search Parents through TopLevelManager
1070   if (SearchParent)
1071     return TPM->findAnalysisPass(AID);
1072
1073   return NULL;
1074 }
1075
1076 // Print list of passes that are last used by P.
1077 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1078
1079   SmallVector<Pass *, 12> LUses;
1080
1081   // If this is a on the fly manager then it does not have TPM.
1082   if (!TPM)
1083     return;
1084
1085   TPM->collectLastUses(LUses, P);
1086
1087   for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1088          E = LUses.end(); I != E; ++I) {
1089     llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1090     (*I)->dumpPassStructure(0);
1091   }
1092 }
1093
1094 void PMDataManager::dumpPassArguments() const {
1095   for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1096         E = PassVector.end(); I != E; ++I) {
1097     if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1098       PMD->dumpPassArguments();
1099     else
1100       if (const PassInfo *PI =
1101             PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1102         if (!PI->isAnalysisGroup())
1103           dbgs() << " -" << PI->getPassArgument();
1104   }
1105 }
1106
1107 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1108                                  enum PassDebuggingString S2,
1109                                  StringRef Msg) {
1110   if (PassDebugging < Executions)
1111     return;
1112   dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1113   switch (S1) {
1114   case EXECUTION_MSG:
1115     dbgs() << "Executing Pass '" << P->getPassName();
1116     break;
1117   case MODIFICATION_MSG:
1118     dbgs() << "Made Modification '" << P->getPassName();
1119     break;
1120   case FREEING_MSG:
1121     dbgs() << " Freeing Pass '" << P->getPassName();
1122     break;
1123   default:
1124     break;
1125   }
1126   switch (S2) {
1127   case ON_BASICBLOCK_MSG:
1128     dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1129     break;
1130   case ON_FUNCTION_MSG:
1131     dbgs() << "' on Function '" << Msg << "'...\n";
1132     break;
1133   case ON_MODULE_MSG:
1134     dbgs() << "' on Module '"  << Msg << "'...\n";
1135     break;
1136   case ON_REGION_MSG:
1137     dbgs() << "' on Region '"  << Msg << "'...\n";
1138     break;
1139   case ON_LOOP_MSG:
1140     dbgs() << "' on Loop '" << Msg << "'...\n";
1141     break;
1142   case ON_CG_MSG:
1143     dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1144     break;
1145   default:
1146     break;
1147   }
1148 }
1149
1150 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1151   if (PassDebugging < Details)
1152     return;
1153
1154   AnalysisUsage analysisUsage;
1155   P->getAnalysisUsage(analysisUsage);
1156   dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1157 }
1158
1159 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1160   if (PassDebugging < Details)
1161     return;
1162
1163   AnalysisUsage analysisUsage;
1164   P->getAnalysisUsage(analysisUsage);
1165   dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1166 }
1167
1168 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1169                                    const AnalysisUsage::VectorType &Set) const {
1170   assert(PassDebugging >= Details);
1171   if (Set.empty())
1172     return;
1173   dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1174   for (unsigned i = 0; i != Set.size(); ++i) {
1175     if (i) dbgs() << ',';
1176     const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1177     if (!PInf) {
1178       // Some preserved passes, such as AliasAnalysis, may not be initialized by
1179       // all drivers.
1180       dbgs() << " Uninitialized Pass";
1181       continue;
1182     }
1183     dbgs() << ' ' << PInf->getPassName();
1184   }
1185   dbgs() << '\n';
1186 }
1187
1188 /// Add RequiredPass into list of lower level passes required by pass P.
1189 /// RequiredPass is run on the fly by Pass Manager when P requests it
1190 /// through getAnalysis interface.
1191 /// This should be handled by specific pass manager.
1192 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1193   if (TPM) {
1194     TPM->dumpArguments();
1195     TPM->dumpPasses();
1196   }
1197
1198   // Module Level pass may required Function Level analysis info
1199   // (e.g. dominator info). Pass manager uses on the fly function pass manager
1200   // to provide this on demand. In that case, in Pass manager terminology,
1201   // module level pass is requiring lower level analysis info managed by
1202   // lower level pass manager.
1203
1204   // When Pass manager is not able to order required analysis info, Pass manager
1205   // checks whether any lower level manager will be able to provide this
1206   // analysis info on demand or not.
1207 #ifndef NDEBUG
1208   dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1209   dbgs() << "' required by '" << P->getPassName() << "'\n";
1210 #endif
1211   llvm_unreachable("Unable to schedule pass");
1212 }
1213
1214 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1215   llvm_unreachable("Unable to find on the fly pass");
1216 }
1217
1218 // Destructor
1219 PMDataManager::~PMDataManager() {
1220   for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1221          E = PassVector.end(); I != E; ++I)
1222     delete *I;
1223 }
1224
1225 //===----------------------------------------------------------------------===//
1226 // NOTE: Is this the right place to define this method ?
1227 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1228 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1229   return PM.findAnalysisPass(ID, dir);
1230 }
1231
1232 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1233                                      Function &F) {
1234   return PM.getOnTheFlyPass(P, AnalysisPI, F);
1235 }
1236
1237 //===----------------------------------------------------------------------===//
1238 // BBPassManager implementation
1239
1240 /// Execute all of the passes scheduled for execution by invoking
1241 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies
1242 /// the function, and if so, return true.
1243 bool BBPassManager::runOnFunction(Function &F) {
1244   if (F.isDeclaration())
1245     return false;
1246
1247   bool Changed = doInitialization(F);
1248
1249   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1250     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1251       BasicBlockPass *BP = getContainedPass(Index);
1252       bool LocalChanged = false;
1253
1254       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1255       dumpRequiredSet(BP);
1256
1257       initializeAnalysisImpl(BP);
1258
1259       {
1260         // If the pass crashes, remember this.
1261         PassManagerPrettyStackEntry X(BP, *I);
1262         TimeRegion PassTimer(getPassTimer(BP));
1263
1264         LocalChanged |= BP->runOnBasicBlock(*I);
1265       }
1266
1267       Changed |= LocalChanged;
1268       if (LocalChanged)
1269         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1270                      I->getName());
1271       dumpPreservedSet(BP);
1272
1273       verifyPreservedAnalysis(BP);
1274       removeNotPreservedAnalysis(BP);
1275       recordAvailableAnalysis(BP);
1276       removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1277     }
1278
1279   return doFinalization(F) || Changed;
1280 }
1281
1282 // Implement doInitialization and doFinalization
1283 bool BBPassManager::doInitialization(Module &M) {
1284   bool Changed = false;
1285
1286   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1287     Changed |= getContainedPass(Index)->doInitialization(M);
1288
1289   return Changed;
1290 }
1291
1292 bool BBPassManager::doFinalization(Module &M) {
1293   bool Changed = false;
1294
1295   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1296     Changed |= getContainedPass(Index)->doFinalization(M);
1297
1298   return Changed;
1299 }
1300
1301 bool BBPassManager::doInitialization(Function &F) {
1302   bool Changed = false;
1303
1304   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1305     BasicBlockPass *BP = getContainedPass(Index);
1306     Changed |= BP->doInitialization(F);
1307   }
1308
1309   return Changed;
1310 }
1311
1312 bool BBPassManager::doFinalization(Function &F) {
1313   bool Changed = false;
1314
1315   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1316     BasicBlockPass *BP = getContainedPass(Index);
1317     Changed |= BP->doFinalization(F);
1318   }
1319
1320   return Changed;
1321 }
1322
1323
1324 //===----------------------------------------------------------------------===//
1325 // FunctionPassManager implementation
1326
1327 /// Create new Function pass manager
1328 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1329   FPM = new FunctionPassManagerImpl();
1330   // FPM is the top level manager.
1331   FPM->setTopLevelManager(FPM);
1332
1333   AnalysisResolver *AR = new AnalysisResolver(*FPM);
1334   FPM->setResolver(AR);
1335 }
1336
1337 FunctionPassManager::~FunctionPassManager() {
1338   delete FPM;
1339 }
1340
1341 /// add - Add a pass to the queue of passes to run.  This passes
1342 /// ownership of the Pass to the PassManager.  When the
1343 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1344 /// there is no need to delete the pass. (TODO delete passes.)
1345 /// This implies that all passes MUST be allocated with 'new'.
1346 void FunctionPassManager::add(Pass *P) {
1347   FPM->add(P);
1348 }
1349
1350 /// run - Execute all of the passes scheduled for execution.  Keep
1351 /// track of whether any of the passes modifies the function, and if
1352 /// so, return true.
1353 ///
1354 bool FunctionPassManager::run(Function &F) {
1355   if (F.isMaterializable()) {
1356     std::string errstr;
1357     if (F.Materialize(&errstr))
1358       report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1359   }
1360   return FPM->run(F);
1361 }
1362
1363
1364 /// doInitialization - Run all of the initializers for the function passes.
1365 ///
1366 bool FunctionPassManager::doInitialization() {
1367   return FPM->doInitialization(*M);
1368 }
1369
1370 /// doFinalization - Run all of the finalizers for the function passes.
1371 ///
1372 bool FunctionPassManager::doFinalization() {
1373   return FPM->doFinalization(*M);
1374 }
1375
1376 //===----------------------------------------------------------------------===//
1377 // FunctionPassManagerImpl implementation
1378 //
1379 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1380   bool Changed = false;
1381
1382   dumpArguments();
1383   dumpPasses();
1384
1385   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1386     Changed |= getContainedManager(Index)->doInitialization(M);
1387
1388   return Changed;
1389 }
1390
1391 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1392   bool Changed = false;
1393
1394   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1395     Changed |= getContainedManager(Index)->doFinalization(M);
1396
1397   return Changed;
1398 }
1399
1400 /// cleanup - After running all passes, clean up pass manager cache.
1401 void FPPassManager::cleanup() {
1402  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1403     FunctionPass *FP = getContainedPass(Index);
1404     AnalysisResolver *AR = FP->getResolver();
1405     assert(AR && "Analysis Resolver is not set");
1406     AR->clearAnalysisImpls();
1407  }
1408 }
1409
1410 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1411   if (!wasRun)
1412     return;
1413   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1414     FPPassManager *FPPM = getContainedManager(Index);
1415     for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1416       FPPM->getContainedPass(Index)->releaseMemory();
1417     }
1418   }
1419   wasRun = false;
1420 }
1421
1422 // Execute all the passes managed by this top level manager.
1423 // Return true if any function is modified by a pass.
1424 bool FunctionPassManagerImpl::run(Function &F) {
1425   bool Changed = false;
1426   TimingInfo::createTheTimeInfo();
1427
1428   initializeAllAnalysisInfo();
1429   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1430     Changed |= getContainedManager(Index)->runOnFunction(F);
1431
1432   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1433     getContainedManager(Index)->cleanup();
1434
1435   wasRun = true;
1436   return Changed;
1437 }
1438
1439 //===----------------------------------------------------------------------===//
1440 // FPPassManager implementation
1441
1442 char FPPassManager::ID = 0;
1443 /// Print passes managed by this manager
1444 void FPPassManager::dumpPassStructure(unsigned Offset) {
1445   dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1446   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1447     FunctionPass *FP = getContainedPass(Index);
1448     FP->dumpPassStructure(Offset + 1);
1449     dumpLastUses(FP, Offset+1);
1450   }
1451 }
1452
1453
1454 /// Execute all of the passes scheduled for execution by invoking
1455 /// runOnFunction method.  Keep track of whether any of the passes modifies
1456 /// the function, and if so, return true.
1457 bool FPPassManager::runOnFunction(Function &F) {
1458   if (F.isDeclaration())
1459     return false;
1460
1461   bool Changed = false;
1462
1463   // Collect inherited analysis from Module level pass manager.
1464   populateInheritedAnalysis(TPM->activeStack);
1465
1466   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1467     FunctionPass *FP = getContainedPass(Index);
1468     bool LocalChanged = false;
1469
1470     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1471     dumpRequiredSet(FP);
1472
1473     initializeAnalysisImpl(FP);
1474
1475     {
1476       PassManagerPrettyStackEntry X(FP, F);
1477       TimeRegion PassTimer(getPassTimer(FP));
1478
1479       LocalChanged |= FP->runOnFunction(F);
1480     }
1481
1482     Changed |= LocalChanged;
1483     if (LocalChanged)
1484       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1485     dumpPreservedSet(FP);
1486
1487     verifyPreservedAnalysis(FP);
1488     removeNotPreservedAnalysis(FP);
1489     recordAvailableAnalysis(FP);
1490     removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1491   }
1492   return Changed;
1493 }
1494
1495 bool FPPassManager::runOnModule(Module &M) {
1496   bool Changed = doInitialization(M);
1497
1498   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1499     Changed |= runOnFunction(*I);
1500
1501   return doFinalization(M) || Changed;
1502 }
1503
1504 bool FPPassManager::doInitialization(Module &M) {
1505   bool Changed = false;
1506
1507   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1508     Changed |= getContainedPass(Index)->doInitialization(M);
1509
1510   return Changed;
1511 }
1512
1513 bool FPPassManager::doFinalization(Module &M) {
1514   bool Changed = false;
1515
1516   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1517     Changed |= getContainedPass(Index)->doFinalization(M);
1518
1519   return Changed;
1520 }
1521
1522 //===----------------------------------------------------------------------===//
1523 // MPPassManager implementation
1524
1525 /// Execute all of the passes scheduled for execution by invoking
1526 /// runOnModule method.  Keep track of whether any of the passes modifies
1527 /// the module, and if so, return true.
1528 bool
1529 MPPassManager::runOnModule(Module &M) {
1530   bool Changed = false;
1531
1532   // Initialize on-the-fly passes
1533   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1534        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1535        I != E; ++I) {
1536     FunctionPassManagerImpl *FPP = I->second;
1537     Changed |= FPP->doInitialization(M);
1538   }
1539
1540   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1541     ModulePass *MP = getContainedPass(Index);
1542     bool LocalChanged = false;
1543
1544     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1545     dumpRequiredSet(MP);
1546
1547     initializeAnalysisImpl(MP);
1548
1549     {
1550       PassManagerPrettyStackEntry X(MP, M);
1551       TimeRegion PassTimer(getPassTimer(MP));
1552
1553       LocalChanged |= MP->runOnModule(M);
1554     }
1555
1556     Changed |= LocalChanged;
1557     if (LocalChanged)
1558       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1559                    M.getModuleIdentifier());
1560     dumpPreservedSet(MP);
1561
1562     verifyPreservedAnalysis(MP);
1563     removeNotPreservedAnalysis(MP);
1564     recordAvailableAnalysis(MP);
1565     removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1566   }
1567
1568   // Finalize on-the-fly passes
1569   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1570        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1571        I != E; ++I) {
1572     FunctionPassManagerImpl *FPP = I->second;
1573     // We don't know when is the last time an on-the-fly pass is run,
1574     // so we need to releaseMemory / finalize here
1575     FPP->releaseMemoryOnTheFly();
1576     Changed |= FPP->doFinalization(M);
1577   }
1578   return Changed;
1579 }
1580
1581 /// Add RequiredPass into list of lower level passes required by pass P.
1582 /// RequiredPass is run on the fly by Pass Manager when P requests it
1583 /// through getAnalysis interface.
1584 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1585   assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1586          "Unable to handle Pass that requires lower level Analysis pass");
1587   assert((P->getPotentialPassManagerType() <
1588           RequiredPass->getPotentialPassManagerType()) &&
1589          "Unable to handle Pass that requires lower level Analysis pass");
1590
1591   FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1592   if (!FPP) {
1593     FPP = new FunctionPassManagerImpl();
1594     // FPP is the top level manager.
1595     FPP->setTopLevelManager(FPP);
1596
1597     OnTheFlyManagers[P] = FPP;
1598   }
1599   FPP->add(RequiredPass);
1600
1601   // Register P as the last user of RequiredPass.
1602   if (RequiredPass) {
1603     SmallVector<Pass *, 1> LU;
1604     LU.push_back(RequiredPass);
1605     FPP->setLastUser(LU,  P);
1606   }
1607 }
1608
1609 /// Return function pass corresponding to PassInfo PI, that is
1610 /// required by module pass MP. Instantiate analysis pass, by using
1611 /// its runOnFunction() for function F.
1612 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1613   FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1614   assert(FPP && "Unable to find on the fly pass");
1615
1616   FPP->releaseMemoryOnTheFly();
1617   FPP->run(F);
1618   return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1619 }
1620
1621
1622 //===----------------------------------------------------------------------===//
1623 // PassManagerImpl implementation
1624 //
1625 /// run - Execute all of the passes scheduled for execution.  Keep track of
1626 /// whether any of the passes modifies the module, and if so, return true.
1627 bool PassManagerImpl::run(Module &M) {
1628   bool Changed = false;
1629   TimingInfo::createTheTimeInfo();
1630
1631   dumpArguments();
1632   dumpPasses();
1633
1634   initializeAllAnalysisInfo();
1635   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1636     Changed |= getContainedManager(Index)->runOnModule(M);
1637   return Changed;
1638 }
1639
1640 //===----------------------------------------------------------------------===//
1641 // PassManager implementation
1642
1643 /// Create new pass manager
1644 PassManager::PassManager() {
1645   PM = new PassManagerImpl();
1646   // PM is the top level manager
1647   PM->setTopLevelManager(PM);
1648 }
1649
1650 PassManager::~PassManager() {
1651   delete PM;
1652 }
1653
1654 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1655 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1656 /// will be destroyed as well, so there is no need to delete the pass.  This
1657 /// implies that all passes MUST be allocated with 'new'.
1658 void PassManager::add(Pass *P) {
1659   PM->add(P);
1660 }
1661
1662 /// run - Execute all of the passes scheduled for execution.  Keep track of
1663 /// whether any of the passes modifies the module, and if so, return true.
1664 bool PassManager::run(Module &M) {
1665   return PM->run(M);
1666 }
1667
1668 //===----------------------------------------------------------------------===//
1669 // TimingInfo Class - This class is used to calculate information about the
1670 // amount of time each pass takes to execute.  This only happens with
1671 // -time-passes is enabled on the command line.
1672 //
1673 bool llvm::TimePassesIsEnabled = false;
1674 static cl::opt<bool,true>
1675 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1676             cl::desc("Time each pass, printing elapsed time for each on exit"));
1677
1678 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1679 // a non null value (if the -time-passes option is enabled) or it leaves it
1680 // null.  It may be called multiple times.
1681 void TimingInfo::createTheTimeInfo() {
1682   if (!TimePassesIsEnabled || TheTimeInfo) return;
1683
1684   // Constructed the first time this is called, iff -time-passes is enabled.
1685   // This guarantees that the object will be constructed before static globals,
1686   // thus it will be destroyed before them.
1687   static ManagedStatic<TimingInfo> TTI;
1688   TheTimeInfo = &*TTI;
1689 }
1690
1691 /// If TimingInfo is enabled then start pass timer.
1692 Timer *llvm::getPassTimer(Pass *P) {
1693   if (TheTimeInfo)
1694     return TheTimeInfo->getPassTimer(P);
1695   return 0;
1696 }
1697
1698 //===----------------------------------------------------------------------===//
1699 // PMStack implementation
1700 //
1701
1702 // Pop Pass Manager from the stack and clear its analysis info.
1703 void PMStack::pop() {
1704
1705   PMDataManager *Top = this->top();
1706   Top->initializeAnalysisInfo();
1707
1708   S.pop_back();
1709 }
1710
1711 // Push PM on the stack and set its top level manager.
1712 void PMStack::push(PMDataManager *PM) {
1713   assert(PM && "Unable to push. Pass Manager expected");
1714   assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1715
1716   if (!this->empty()) {
1717     assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1718            && "pushing bad pass manager to PMStack");
1719     PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1720
1721     assert(TPM && "Unable to find top level manager");
1722     TPM->addIndirectPassManager(PM);
1723     PM->setTopLevelManager(TPM);
1724     PM->setDepth(this->top()->getDepth()+1);
1725   }
1726   else {
1727     assert((PM->getPassManagerType() == PMT_ModulePassManager
1728            || PM->getPassManagerType() == PMT_FunctionPassManager)
1729            && "pushing bad pass manager to PMStack");
1730     PM->setDepth(1);
1731   }
1732
1733   S.push_back(PM);
1734 }
1735
1736 // Dump content of the pass manager stack.
1737 void PMStack::dump() const {
1738   for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1739          E = S.end(); I != E; ++I)
1740     dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1741
1742   if (!S.empty())
1743     dbgs() << '\n';
1744 }
1745
1746 /// Find appropriate Module Pass Manager in the PM Stack and
1747 /// add self into that manager.
1748 void ModulePass::assignPassManager(PMStack &PMS,
1749                                    PassManagerType PreferredType) {
1750   // Find Module Pass Manager
1751   while (!PMS.empty()) {
1752     PassManagerType TopPMType = PMS.top()->getPassManagerType();
1753     if (TopPMType == PreferredType)
1754       break; // We found desired pass manager
1755     else if (TopPMType > PMT_ModulePassManager)
1756       PMS.pop();    // Pop children pass managers
1757     else
1758       break;
1759   }
1760   assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1761   PMS.top()->add(this);
1762 }
1763
1764 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1765 /// in the PM Stack and add self into that manager.
1766 void FunctionPass::assignPassManager(PMStack &PMS,
1767                                      PassManagerType PreferredType) {
1768
1769   // Find Function Pass Manager
1770   while (!PMS.empty()) {
1771     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1772       PMS.pop();
1773     else
1774       break;
1775   }
1776
1777   // Create new Function Pass Manager if needed.
1778   FPPassManager *FPP;
1779   if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1780     FPP = (FPPassManager *)PMS.top();
1781   } else {
1782     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1783     PMDataManager *PMD = PMS.top();
1784
1785     // [1] Create new Function Pass Manager
1786     FPP = new FPPassManager();
1787     FPP->populateInheritedAnalysis(PMS);
1788
1789     // [2] Set up new manager's top level manager
1790     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1791     TPM->addIndirectPassManager(FPP);
1792
1793     // [3] Assign manager to manage this new manager. This may create
1794     // and push new managers into PMS
1795     FPP->assignPassManager(PMS, PMD->getPassManagerType());
1796
1797     // [4] Push new manager into PMS
1798     PMS.push(FPP);
1799   }
1800
1801   // Assign FPP as the manager of this pass.
1802   FPP->add(this);
1803 }
1804
1805 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1806 /// in the PM Stack and add self into that manager.
1807 void BasicBlockPass::assignPassManager(PMStack &PMS,
1808                                        PassManagerType PreferredType) {
1809   BBPassManager *BBP;
1810
1811   // Basic Pass Manager is a leaf pass manager. It does not handle
1812   // any other pass manager.
1813   if (!PMS.empty() &&
1814       PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1815     BBP = (BBPassManager *)PMS.top();
1816   } else {
1817     // If leaf manager is not Basic Block Pass manager then create new
1818     // basic Block Pass manager.
1819     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1820     PMDataManager *PMD = PMS.top();
1821
1822     // [1] Create new Basic Block Manager
1823     BBP = new BBPassManager();
1824
1825     // [2] Set up new manager's top level manager
1826     // Basic Block Pass Manager does not live by itself
1827     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1828     TPM->addIndirectPassManager(BBP);
1829
1830     // [3] Assign manager to manage this new manager. This may create
1831     // and push new managers into PMS
1832     BBP->assignPassManager(PMS, PreferredType);
1833
1834     // [4] Push new manager into PMS
1835     PMS.push(BBP);
1836   }
1837
1838   // Assign BBP as the manager of this pass.
1839   BBP->add(this);
1840 }
1841
1842 PassManagerBase::~PassManagerBase() {}