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