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