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