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