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