fairly major rewrite of various timing related stuff.
[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/Assembly/Writer.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Timer.h"
20 #include "llvm/Module.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/System/Threading.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 static cl::opt<enum PassDebugLevel>
49 PassDebugging("debug-pass", cl::Hidden,
50                   cl::desc("Print PassManager debugging information"),
51                   cl::values(
52   clEnumVal(None      , "disable debug output"),
53   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54   clEnumVal(Structure , "print pass structure before run()"),
55   clEnumVal(Executions, "print pass name before it is executed"),
56   clEnumVal(Details   , "print pass details when it is executed"),
57                              clEnumValEnd));
58 } // End of llvm namespace
59
60 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
61 /// or higher is specified.
62 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
63   return PassDebugging >= Executions;
64 }
65
66
67
68
69 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
70   if (V == 0 && M == 0)
71     OS << "Releasing pass '";
72   else
73     OS << "Running pass '";
74   
75   OS << P->getPassName() << "'";
76   
77   if (M) {
78     OS << " on module '" << M->getModuleIdentifier() << "'.\n";
79     return;
80   }
81   if (V == 0) {
82     OS << '\n';
83     return;
84   }
85
86   OS << " on ";
87   if (isa<Function>(V))
88     OS << "function";
89   else if (isa<BasicBlock>(V))
90     OS << "basic block";
91   else
92     OS << "value";
93
94   OS << " '";
95   WriteAsOperand(OS, V, /*PrintTy=*/false, M);
96   OS << "'\n";
97 }
98
99
100 namespace {
101
102 //===----------------------------------------------------------------------===//
103 // BBPassManager
104 //
105 /// BBPassManager manages BasicBlockPass. It batches all the
106 /// pass together and sequence them to process one basic block before
107 /// processing next basic block.
108 class BBPassManager : public PMDataManager, 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 PMDataManager *getAsPMDataManager() { return this; }
130   virtual Pass *getAsPass() { return this; }
131
132   virtual const char *getPassName() const {
133     return "BasicBlock Pass Manager";
134   }
135
136   // Print passes managed by this manager
137   void dumpPassStructure(unsigned Offset) {
138     llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
139     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
140       BasicBlockPass *BP = getContainedPass(Index);
141       BP->dumpPassStructure(Offset + 1);
142       dumpLastUses(BP, Offset+1);
143     }
144   }
145
146   BasicBlockPass *getContainedPass(unsigned N) {
147     assert(N < PassVector.size() && "Pass number out of range!");
148     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
149     return BP;
150   }
151
152   virtual PassManagerType getPassManagerType() const { 
153     return PMT_BasicBlockPassManager; 
154   }
155 };
156
157 char BBPassManager::ID = 0;
158 }
159
160 namespace llvm {
161
162 //===----------------------------------------------------------------------===//
163 // FunctionPassManagerImpl
164 //
165 /// FunctionPassManagerImpl manages FPPassManagers
166 class FunctionPassManagerImpl : public Pass,
167                                 public PMDataManager,
168                                 public PMTopLevelManager {
169 private:
170   bool wasRun;
171 public:
172   static char ID;
173   explicit FunctionPassManagerImpl(int Depth) : 
174     Pass(PT_PassManager, &ID), PMDataManager(Depth), 
175     PMTopLevelManager(TLM_Function), wasRun(false) { }
176
177   /// add - Add a pass to the queue of passes to run.  This passes ownership of
178   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
179   /// will be destroyed as well, so there is no need to delete the pass.  This
180   /// implies that all passes MUST be allocated with 'new'.
181   void add(Pass *P) {
182     schedulePass(P);
183   }
184  
185   // Prepare for running an on the fly pass, freeing memory if needed
186   // from a previous run.
187   void releaseMemoryOnTheFly();
188
189   /// run - Execute all of the passes scheduled for execution.  Keep track of
190   /// whether any of the passes modifies the module, and if so, return true.
191   bool run(Function &F);
192
193   /// doInitialization - Run all of the initializers for the function passes.
194   ///
195   bool doInitialization(Module &M);
196   
197   /// doFinalization - Run all of the finalizers for the function passes.
198   ///
199   bool doFinalization(Module &M);
200
201                                   
202   virtual PMDataManager *getAsPMDataManager() { return this; }
203   virtual Pass *getAsPass() { return this; }
204
205   /// Pass Manager itself does not invalidate any analysis info.
206   void getAnalysisUsage(AnalysisUsage &Info) const {
207     Info.setPreservesAll();
208   }
209
210   inline void addTopLevelPass(Pass *P) {
211     if (ImmutablePass *IP = P->getAsImmutablePass()) {
212       // P is a immutable pass and it will be managed by this
213       // top level manager. Set up analysis resolver to connect them.
214       AnalysisResolver *AR = new AnalysisResolver(*this);
215       P->setResolver(AR);
216       initializeAnalysisImpl(P);
217       addImmutablePass(IP);
218       recordAvailableAnalysis(IP);
219     } else {
220       P->assignPassManager(activeStack);
221     }
222
223   }
224
225   FPPassManager *getContainedManager(unsigned N) {
226     assert(N < PassManagers.size() && "Pass number out of range!");
227     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
228     return FP;
229   }
230 };
231
232 char FunctionPassManagerImpl::ID = 0;
233 //===----------------------------------------------------------------------===//
234 // MPPassManager
235 //
236 /// MPPassManager manages ModulePasses and function pass managers.
237 /// It batches all Module passes and function pass managers together and
238 /// sequences them to process one module.
239 class MPPassManager : public Pass, public PMDataManager {
240 public:
241   static char ID;
242   explicit MPPassManager(int Depth) :
243     Pass(PT_PassManager, &ID), PMDataManager(Depth) { }
244
245   // Delete on the fly managers.
246   virtual ~MPPassManager() {
247     for (std::map<Pass *, FunctionPassManagerImpl *>::iterator 
248            I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
249          I != E; ++I) {
250       FunctionPassManagerImpl *FPP = I->second;
251       delete FPP;
252     }
253   }
254
255   /// run - Execute all of the passes scheduled for execution.  Keep track of
256   /// whether any of the passes modifies the module, and if so, return true.
257   bool runOnModule(Module &M);
258
259   /// Pass Manager itself does not invalidate any analysis info.
260   void getAnalysisUsage(AnalysisUsage &Info) const {
261     Info.setPreservesAll();
262   }
263
264   /// Add RequiredPass into list of lower level passes required by pass P.
265   /// RequiredPass is run on the fly by Pass Manager when P requests it
266   /// through getAnalysis interface.
267   virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
268
269   /// Return function pass corresponding to PassInfo PI, that is 
270   /// required by module pass MP. Instantiate analysis pass, by using
271   /// its runOnFunction() for function F.
272   virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
273
274   virtual const char *getPassName() const {
275     return "Module Pass Manager";
276   }
277
278   virtual PMDataManager *getAsPMDataManager() { return this; }
279   virtual Pass *getAsPass() { return this; }
280
281   // Print passes managed by this manager
282   void dumpPassStructure(unsigned Offset) {
283     llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
284     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
285       ModulePass *MP = getContainedPass(Index);
286       MP->dumpPassStructure(Offset + 1);
287       std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
288         OnTheFlyManagers.find(MP);
289       if (I != OnTheFlyManagers.end())
290         I->second->dumpPassStructure(Offset + 2);
291       dumpLastUses(MP, Offset+1);
292     }
293   }
294
295   ModulePass *getContainedPass(unsigned N) {
296     assert(N < PassVector.size() && "Pass number out of range!");
297     return static_cast<ModulePass *>(PassVector[N]);
298   }
299
300   virtual PassManagerType getPassManagerType() const { 
301     return PMT_ModulePassManager; 
302   }
303
304  private:
305   /// Collection of on the fly FPPassManagers. These managers manage
306   /// function passes that are required by module passes.
307   std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
308 };
309
310 char MPPassManager::ID = 0;
311 //===----------------------------------------------------------------------===//
312 // PassManagerImpl
313 //
314
315 /// PassManagerImpl manages MPPassManagers
316 class PassManagerImpl : public Pass,
317                         public PMDataManager,
318                         public PMTopLevelManager {
319
320 public:
321   static char ID;
322   explicit PassManagerImpl(int Depth) :
323     Pass(PT_PassManager, &ID), PMDataManager(Depth),
324                                PMTopLevelManager(TLM_Pass) { }
325
326   /// add - Add a pass to the queue of passes to run.  This passes ownership of
327   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
328   /// will be destroyed as well, so there is no need to delete the pass.  This
329   /// implies that all passes MUST be allocated with 'new'.
330   void add(Pass *P) {
331     schedulePass(P);
332   }
333  
334   /// run - Execute all of the passes scheduled for execution.  Keep track of
335   /// whether any of the passes modifies the module, and if so, return true.
336   bool run(Module &M);
337
338   /// Pass Manager itself does not invalidate any analysis info.
339   void getAnalysisUsage(AnalysisUsage &Info) const {
340     Info.setPreservesAll();
341   }
342
343   inline void addTopLevelPass(Pass *P) {
344     if (ImmutablePass *IP = P->getAsImmutablePass()) {
345       // P is a immutable pass and it will be managed by this
346       // top level manager. Set up analysis resolver to connect them.
347       AnalysisResolver *AR = new AnalysisResolver(*this);
348       P->setResolver(AR);
349       initializeAnalysisImpl(P);
350       addImmutablePass(IP);
351       recordAvailableAnalysis(IP);
352     } else {
353       P->assignPassManager(activeStack);
354     }
355   }
356
357   virtual PMDataManager *getAsPMDataManager() { return this; }
358   virtual Pass *getAsPass() { return this; }
359
360   MPPassManager *getContainedManager(unsigned N) {
361     assert(N < PassManagers.size() && "Pass number out of range!");
362     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
363     return MP;
364   }
365 };
366
367 char PassManagerImpl::ID = 0;
368 } // End of llvm namespace
369
370 namespace {
371
372 //===----------------------------------------------------------------------===//
373 /// TimingInfo Class - This class is used to calculate information about the
374 /// amount of time each pass takes to execute.  This only happens when
375 /// -time-passes is enabled on the command line.
376 ///
377
378 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
379
380 class TimingInfo {
381   DenseMap<Pass*, Timer> TimingData;
382   TimerGroup TG;
383
384 public:
385   // Use 'create' member to get this.
386   TimingInfo() : TG("... Pass execution timing report ...") {}
387   
388   // TimingDtor - Print out information about timing information
389   ~TimingInfo() {
390     // Delete all of the timers...
391     TimingData.clear();
392     // TimerGroup is deleted next, printing the report.
393   }
394
395   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
396   // to a non null value (if the -time-passes option is enabled) or it leaves it
397   // null.  It may be called multiple times.
398   static void createTheTimeInfo();
399
400   /// getPassTimer - Return the timer for the specified pass if it exists.
401   Timer *getPassTimer(Pass *P) {
402     if (P->getAsPMDataManager()) 
403       return 0;
404
405     sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
406     Timer &T = TimingData[P];
407     if (!T.isInitialized())
408       T.init(P->getPassName(), TG);
409     return &T;
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 getAsPass 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     (*I)->getAsPass()->dumpPassStructure(1);
599 }
600
601 void PMTopLevelManager::dumpArguments() const {
602
603   if (PassDebugging < Arguments)
604     return;
605
606   dbgs() << "Pass Arguments: ";
607   for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
608          E = PassManagers.end(); I != E; ++I)
609     (*I)->dumpPassArguments();
610   dbgs() << "\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 (P1->getAsImmutablePass() == 0 &&
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       TimeRegion PassTimer(getPassTimer(AP));
705       AP->verifyAnalysis();
706     }
707   }
708 }
709
710 /// Remove Analysis not preserved by Pass P
711 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
712   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
713   if (AnUsage->getPreservesAll())
714     return;
715
716   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
717   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
718          E = AvailableAnalysis.end(); I != E; ) {
719     std::map<AnalysisID, Pass*>::iterator Info = I++;
720     if (Info->second->getAsImmutablePass() == 0 &&
721         std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
722         PreservedSet.end()) {
723       // Remove this analysis
724       if (PassDebugging >= Details) {
725         Pass *S = Info->second;
726         dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
727         dbgs() << S->getPassName() << "'\n";
728       }
729       AvailableAnalysis.erase(Info);
730     }
731   }
732
733   // Check inherited analysis also. If P is not preserving analysis
734   // provided by parent manager then remove it here.
735   for (unsigned Index = 0; Index < PMT_Last; ++Index) {
736
737     if (!InheritedAnalysis[Index])
738       continue;
739
740     for (std::map<AnalysisID, Pass*>::iterator 
741            I = InheritedAnalysis[Index]->begin(),
742            E = InheritedAnalysis[Index]->end(); I != E; ) {
743       std::map<AnalysisID, Pass *>::iterator Info = I++;
744       if (Info->second->getAsImmutablePass() == 0 &&
745           std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
746              PreservedSet.end()) {
747         // Remove this analysis
748         if (PassDebugging >= Details) {
749           Pass *S = Info->second;
750           dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
751           dbgs() << S->getPassName() << "'\n";
752         }
753         InheritedAnalysis[Index]->erase(Info);
754       }
755     }
756   }
757 }
758
759 /// Remove analysis passes that are not used any longer
760 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
761                                      enum PassDebuggingString DBG_STR) {
762
763   SmallVector<Pass *, 12> DeadPasses;
764
765   // If this is a on the fly manager then it does not have TPM.
766   if (!TPM)
767     return;
768
769   TPM->collectLastUses(DeadPasses, P);
770
771   if (PassDebugging >= Details && !DeadPasses.empty()) {
772     dbgs() << " -*- '" <<  P->getPassName();
773     dbgs() << "' is the last user of following pass instances.";
774     dbgs() << " Free these instances\n";
775   }
776
777   for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
778          E = DeadPasses.end(); I != E; ++I)
779     freePass(*I, Msg, DBG_STR);
780 }
781
782 void PMDataManager::freePass(Pass *P, StringRef Msg,
783                              enum PassDebuggingString DBG_STR) {
784   dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
785
786   {
787     // If the pass crashes releasing memory, remember this.
788     PassManagerPrettyStackEntry X(P);
789     TimeRegion PassTimer(getPassTimer(P));
790
791     P->releaseMemory();
792   }
793
794   if (const PassInfo *PI = P->getPassInfo()) {
795     // Remove the pass itself (if it is not already removed).
796     AvailableAnalysis.erase(PI);
797
798     // Remove all interfaces this pass implements, for which it is also
799     // listed as the available implementation.
800     const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
801     for (unsigned i = 0, e = II.size(); i != e; ++i) {
802       std::map<AnalysisID, Pass*>::iterator Pos =
803         AvailableAnalysis.find(II[i]);
804       if (Pos != AvailableAnalysis.end() && Pos->second == P)
805         AvailableAnalysis.erase(Pos);
806     }
807   }
808 }
809
810 /// Add pass P into the PassVector. Update 
811 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
812 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
813   // This manager is going to manage pass P. Set up analysis resolver
814   // to connect them.
815   AnalysisResolver *AR = new AnalysisResolver(*this);
816   P->setResolver(AR);
817
818   // If a FunctionPass F is the last user of ModulePass info M
819   // then the F's manager, not F, records itself as a last user of M.
820   SmallVector<Pass *, 12> TransferLastUses;
821
822   if (!ProcessAnalysis) {
823     // Add pass
824     PassVector.push_back(P);
825     return;
826   }
827
828   // At the moment, this pass is the last user of all required passes.
829   SmallVector<Pass *, 12> LastUses;
830   SmallVector<Pass *, 8> RequiredPasses;
831   SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
832
833   unsigned PDepth = this->getDepth();
834
835   collectRequiredAnalysis(RequiredPasses, 
836                           ReqAnalysisNotAvailable, P);
837   for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
838          E = RequiredPasses.end(); I != E; ++I) {
839     Pass *PRequired = *I;
840     unsigned RDepth = 0;
841
842     assert(PRequired->getResolver() && "Analysis Resolver is not set");
843     PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
844     RDepth = DM.getDepth();
845
846     if (PDepth == RDepth)
847       LastUses.push_back(PRequired);
848     else if (PDepth > RDepth) {
849       // Let the parent claim responsibility of last use
850       TransferLastUses.push_back(PRequired);
851       // Keep track of higher level analysis used by this manager.
852       HigherLevelAnalysis.push_back(PRequired);
853     } else 
854       llvm_unreachable("Unable to accomodate Required Pass");
855   }
856
857   // Set P as P's last user until someone starts using P.
858   // However, if P is a Pass Manager then it does not need
859   // to record its last user.
860   if (P->getAsPMDataManager() == 0)
861     LastUses.push_back(P);
862   TPM->setLastUser(LastUses, P);
863
864   if (!TransferLastUses.empty()) {
865     Pass *My_PM = getAsPass();
866     TPM->setLastUser(TransferLastUses, My_PM);
867     TransferLastUses.clear();
868   }
869
870   // Now, take care of required analysises that are not available.
871   for (SmallVector<AnalysisID, 8>::iterator 
872          I = ReqAnalysisNotAvailable.begin(), 
873          E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
874     Pass *AnalysisPass = (*I)->createPass();
875     this->addLowerLevelRequiredPass(P, AnalysisPass);
876   }
877
878   // Take a note of analysis required and made available by this pass.
879   // Remove the analysis not preserved by this pass
880   removeNotPreservedAnalysis(P);
881   recordAvailableAnalysis(P);
882
883   // Add pass
884   PassVector.push_back(P);
885 }
886
887
888 /// Populate RP with analysis pass that are required by
889 /// pass P and are available. Populate RP_NotAvail with analysis
890 /// pass that are required by pass P but are not available.
891 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
892                                        SmallVector<AnalysisID, 8> &RP_NotAvail,
893                                             Pass *P) {
894   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
895   const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
896   for (AnalysisUsage::VectorType::const_iterator 
897          I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
898     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
899       RP.push_back(AnalysisPass);   
900     else
901       RP_NotAvail.push_back(*I);
902   }
903
904   const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
905   for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
906          E = IDs.end(); I != E; ++I) {
907     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
908       RP.push_back(AnalysisPass);   
909     else
910       RP_NotAvail.push_back(*I);
911   }
912 }
913
914 // All Required analyses should be available to the pass as it runs!  Here
915 // we fill in the AnalysisImpls member of the pass so that it can
916 // successfully use the getAnalysis() method to retrieve the
917 // implementations it needs.
918 //
919 void PMDataManager::initializeAnalysisImpl(Pass *P) {
920   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
921
922   for (AnalysisUsage::VectorType::const_iterator
923          I = AnUsage->getRequiredSet().begin(),
924          E = AnUsage->getRequiredSet().end(); I != E; ++I) {
925     Pass *Impl = findAnalysisPass(*I, true);
926     if (Impl == 0)
927       // This may be analysis pass that is initialized on the fly.
928       // If that is not the case then it will raise an assert when it is used.
929       continue;
930     AnalysisResolver *AR = P->getResolver();
931     assert(AR && "Analysis Resolver is not set");
932     AR->addAnalysisImplsPair(*I, Impl);
933   }
934 }
935
936 /// Find the pass that implements Analysis AID. If desired pass is not found
937 /// then return NULL.
938 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
939
940   // Check if AvailableAnalysis map has one entry.
941   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
942
943   if (I != AvailableAnalysis.end())
944     return I->second;
945
946   // Search Parents through TopLevelManager
947   if (SearchParent)
948     return TPM->findAnalysisPass(AID);
949   
950   return NULL;
951 }
952
953 // Print list of passes that are last used by P.
954 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
955
956   SmallVector<Pass *, 12> LUses;
957
958   // If this is a on the fly manager then it does not have TPM.
959   if (!TPM)
960     return;
961
962   TPM->collectLastUses(LUses, P);
963   
964   for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
965          E = LUses.end(); I != E; ++I) {
966     llvm::dbgs() << "--" << std::string(Offset*2, ' ');
967     (*I)->dumpPassStructure(0);
968   }
969 }
970
971 void PMDataManager::dumpPassArguments() const {
972   for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
973         E = PassVector.end(); I != E; ++I) {
974     if (PMDataManager *PMD = (*I)->getAsPMDataManager())
975       PMD->dumpPassArguments();
976     else
977       if (const PassInfo *PI = (*I)->getPassInfo())
978         if (!PI->isAnalysisGroup())
979           dbgs() << " -" << PI->getPassArgument();
980   }
981 }
982
983 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
984                                  enum PassDebuggingString S2,
985                                  StringRef Msg) {
986   if (PassDebugging < Executions)
987     return;
988   dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
989   switch (S1) {
990   case EXECUTION_MSG:
991     dbgs() << "Executing Pass '" << P->getPassName();
992     break;
993   case MODIFICATION_MSG:
994     dbgs() << "Made Modification '" << P->getPassName();
995     break;
996   case FREEING_MSG:
997     dbgs() << " Freeing Pass '" << P->getPassName();
998     break;
999   default:
1000     break;
1001   }
1002   switch (S2) {
1003   case ON_BASICBLOCK_MSG:
1004     dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1005     break;
1006   case ON_FUNCTION_MSG:
1007     dbgs() << "' on Function '" << Msg << "'...\n";
1008     break;
1009   case ON_MODULE_MSG:
1010     dbgs() << "' on Module '"  << Msg << "'...\n";
1011     break;
1012   case ON_LOOP_MSG:
1013     dbgs() << "' on Loop '" << Msg << "'...\n";
1014     break;
1015   case ON_CG_MSG:
1016     dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1017     break;
1018   default:
1019     break;
1020   }
1021 }
1022
1023 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1024   if (PassDebugging < Details)
1025     return;
1026     
1027   AnalysisUsage analysisUsage;
1028   P->getAnalysisUsage(analysisUsage);
1029   dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1030 }
1031
1032 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1033   if (PassDebugging < Details)
1034     return;
1035     
1036   AnalysisUsage analysisUsage;
1037   P->getAnalysisUsage(analysisUsage);
1038   dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1039 }
1040
1041 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1042                                    const AnalysisUsage::VectorType &Set) const {
1043   assert(PassDebugging >= Details);
1044   if (Set.empty())
1045     return;
1046   dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1047   for (unsigned i = 0; i != Set.size(); ++i) {
1048     if (i) dbgs() << ',';
1049     dbgs() << ' ' << Set[i]->getPassName();
1050   }
1051   dbgs() << '\n';
1052 }
1053
1054 /// Add RequiredPass into list of lower level passes required by pass P.
1055 /// RequiredPass is run on the fly by Pass Manager when P requests it
1056 /// through getAnalysis interface.
1057 /// This should be handled by specific pass manager.
1058 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1059   if (TPM) {
1060     TPM->dumpArguments();
1061     TPM->dumpPasses();
1062   }
1063
1064   // Module Level pass may required Function Level analysis info 
1065   // (e.g. dominator info). Pass manager uses on the fly function pass manager 
1066   // to provide this on demand. In that case, in Pass manager terminology, 
1067   // module level pass is requiring lower level analysis info managed by
1068   // lower level pass manager.
1069
1070   // When Pass manager is not able to order required analysis info, Pass manager
1071   // checks whether any lower level manager will be able to provide this 
1072   // analysis info on demand or not.
1073 #ifndef NDEBUG
1074   dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1075   dbgs() << "' required by '" << P->getPassName() << "'\n";
1076 #endif
1077   llvm_unreachable("Unable to schedule pass");
1078 }
1079
1080 // Destructor
1081 PMDataManager::~PMDataManager() {
1082   for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1083          E = PassVector.end(); I != E; ++I)
1084     delete *I;
1085 }
1086
1087 //===----------------------------------------------------------------------===//
1088 // NOTE: Is this the right place to define this method ?
1089 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1090 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1091   return PM.findAnalysisPass(ID, dir);
1092 }
1093
1094 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI, 
1095                                      Function &F) {
1096   return PM.getOnTheFlyPass(P, AnalysisPI, F);
1097 }
1098
1099 //===----------------------------------------------------------------------===//
1100 // BBPassManager implementation
1101
1102 /// Execute all of the passes scheduled for execution by invoking 
1103 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
1104 /// the function, and if so, return true.
1105 bool BBPassManager::runOnFunction(Function &F) {
1106   if (F.isDeclaration())
1107     return false;
1108
1109   bool Changed = doInitialization(F);
1110
1111   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1112     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1113       BasicBlockPass *BP = getContainedPass(Index);
1114       bool LocalChanged = false;
1115
1116       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1117       dumpRequiredSet(BP);
1118
1119       initializeAnalysisImpl(BP);
1120
1121       {
1122         // If the pass crashes, remember this.
1123         PassManagerPrettyStackEntry X(BP, *I);
1124         TimeRegion PassTimer(getPassTimer(BP));
1125
1126         LocalChanged |= BP->runOnBasicBlock(*I);
1127       }
1128
1129       Changed |= LocalChanged;
1130       if (LocalChanged) 
1131         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1132                      I->getName());
1133       dumpPreservedSet(BP);
1134
1135       verifyPreservedAnalysis(BP);
1136       removeNotPreservedAnalysis(BP);
1137       recordAvailableAnalysis(BP);
1138       removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1139     }
1140
1141   return doFinalization(F) || Changed;
1142 }
1143
1144 // Implement doInitialization and doFinalization
1145 bool BBPassManager::doInitialization(Module &M) {
1146   bool Changed = false;
1147
1148   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1149     Changed |= getContainedPass(Index)->doInitialization(M);
1150
1151   return Changed;
1152 }
1153
1154 bool BBPassManager::doFinalization(Module &M) {
1155   bool Changed = false;
1156
1157   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1158     Changed |= getContainedPass(Index)->doFinalization(M);
1159
1160   return Changed;
1161 }
1162
1163 bool BBPassManager::doInitialization(Function &F) {
1164   bool Changed = false;
1165
1166   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1167     BasicBlockPass *BP = getContainedPass(Index);
1168     Changed |= BP->doInitialization(F);
1169   }
1170
1171   return Changed;
1172 }
1173
1174 bool BBPassManager::doFinalization(Function &F) {
1175   bool Changed = false;
1176
1177   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1178     BasicBlockPass *BP = getContainedPass(Index);
1179     Changed |= BP->doFinalization(F);
1180   }
1181
1182   return Changed;
1183 }
1184
1185
1186 //===----------------------------------------------------------------------===//
1187 // FunctionPassManager implementation
1188
1189 /// Create new Function pass manager
1190 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1191   FPM = new FunctionPassManagerImpl(0);
1192   // FPM is the top level manager.
1193   FPM->setTopLevelManager(FPM);
1194
1195   AnalysisResolver *AR = new AnalysisResolver(*FPM);
1196   FPM->setResolver(AR);
1197 }
1198
1199 FunctionPassManager::~FunctionPassManager() {
1200   delete FPM;
1201 }
1202
1203 /// add - Add a pass to the queue of passes to run.  This passes
1204 /// ownership of the Pass to the PassManager.  When the
1205 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1206 /// there is no need to delete the pass. (TODO delete passes.)
1207 /// This implies that all passes MUST be allocated with 'new'.
1208 void FunctionPassManager::add(Pass *P) { 
1209   FPM->add(P);
1210 }
1211
1212 /// run - Execute all of the passes scheduled for execution.  Keep
1213 /// track of whether any of the passes modifies the function, and if
1214 /// so, return true.
1215 ///
1216 bool FunctionPassManager::run(Function &F) {
1217   if (F.isMaterializable()) {
1218     std::string errstr;
1219     if (F.Materialize(&errstr)) {
1220       llvm_report_error("Error reading bitcode file: " + errstr);
1221     }
1222   }
1223   return FPM->run(F);
1224 }
1225
1226
1227 /// doInitialization - Run all of the initializers for the function passes.
1228 ///
1229 bool FunctionPassManager::doInitialization() {
1230   return FPM->doInitialization(*M);
1231 }
1232
1233 /// doFinalization - Run all of the finalizers for the function passes.
1234 ///
1235 bool FunctionPassManager::doFinalization() {
1236   return FPM->doFinalization(*M);
1237 }
1238
1239 //===----------------------------------------------------------------------===//
1240 // FunctionPassManagerImpl implementation
1241 //
1242 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1243   bool Changed = false;
1244
1245   dumpArguments();
1246   dumpPasses();
1247
1248   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1249     Changed |= getContainedManager(Index)->doInitialization(M);
1250
1251   return Changed;
1252 }
1253
1254 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1255   bool Changed = false;
1256
1257   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1258     Changed |= getContainedManager(Index)->doFinalization(M);
1259
1260   return Changed;
1261 }
1262
1263 /// cleanup - After running all passes, clean up pass manager cache.
1264 void FPPassManager::cleanup() {
1265  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1266     FunctionPass *FP = getContainedPass(Index);
1267     AnalysisResolver *AR = FP->getResolver();
1268     assert(AR && "Analysis Resolver is not set");
1269     AR->clearAnalysisImpls();
1270  }
1271 }
1272
1273 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1274   if (!wasRun)
1275     return;
1276   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1277     FPPassManager *FPPM = getContainedManager(Index);
1278     for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1279       FPPM->getContainedPass(Index)->releaseMemory();
1280     }
1281   }
1282   wasRun = false;
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   initializeAllAnalysisInfo();
1292   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1293     Changed |= getContainedManager(Index)->runOnFunction(F);
1294
1295   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1296     getContainedManager(Index)->cleanup();
1297
1298   wasRun = true;
1299   return Changed;
1300 }
1301
1302 //===----------------------------------------------------------------------===//
1303 // FPPassManager implementation
1304
1305 char FPPassManager::ID = 0;
1306 /// Print passes managed by this manager
1307 void FPPassManager::dumpPassStructure(unsigned Offset) {
1308   llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1309   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1310     FunctionPass *FP = getContainedPass(Index);
1311     FP->dumpPassStructure(Offset + 1);
1312     dumpLastUses(FP, Offset+1);
1313   }
1314 }
1315
1316
1317 /// Execute all of the passes scheduled for execution by invoking 
1318 /// runOnFunction method.  Keep track of whether any of the passes modifies 
1319 /// the function, and if so, return true.
1320 bool FPPassManager::runOnFunction(Function &F) {
1321   if (F.isDeclaration())
1322     return false;
1323
1324   bool Changed = false;
1325
1326   // Collect inherited analysis from Module level pass manager.
1327   populateInheritedAnalysis(TPM->activeStack);
1328
1329   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1330     FunctionPass *FP = getContainedPass(Index);
1331     bool LocalChanged = false;
1332
1333     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1334     dumpRequiredSet(FP);
1335
1336     initializeAnalysisImpl(FP);
1337
1338     {
1339       PassManagerPrettyStackEntry X(FP, F);
1340       TimeRegion PassTimer(getPassTimer(FP));
1341
1342       LocalChanged |= FP->runOnFunction(F);
1343     }
1344
1345     Changed |= LocalChanged;
1346     if (LocalChanged)
1347       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1348     dumpPreservedSet(FP);
1349
1350     verifyPreservedAnalysis(FP);
1351     removeNotPreservedAnalysis(FP);
1352     recordAvailableAnalysis(FP);
1353     removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1354   }
1355   return Changed;
1356 }
1357
1358 bool FPPassManager::runOnModule(Module &M) {
1359   bool Changed = doInitialization(M);
1360
1361   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1362     runOnFunction(*I);
1363
1364   return doFinalization(M) || Changed;
1365 }
1366
1367 bool FPPassManager::doInitialization(Module &M) {
1368   bool Changed = false;
1369
1370   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1371     Changed |= getContainedPass(Index)->doInitialization(M);
1372
1373   return Changed;
1374 }
1375
1376 bool FPPassManager::doFinalization(Module &M) {
1377   bool Changed = false;
1378
1379   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1380     Changed |= getContainedPass(Index)->doFinalization(M);
1381
1382   return Changed;
1383 }
1384
1385 //===----------------------------------------------------------------------===//
1386 // MPPassManager implementation
1387
1388 /// Execute all of the passes scheduled for execution by invoking 
1389 /// runOnModule method.  Keep track of whether any of the passes modifies 
1390 /// the module, and if so, return true.
1391 bool
1392 MPPassManager::runOnModule(Module &M) {
1393   bool Changed = false;
1394
1395   // Initialize on-the-fly passes
1396   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1397        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1398        I != E; ++I) {
1399     FunctionPassManagerImpl *FPP = I->second;
1400     Changed |= FPP->doInitialization(M);
1401   }
1402
1403   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1404     ModulePass *MP = getContainedPass(Index);
1405     bool LocalChanged = false;
1406
1407     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1408     dumpRequiredSet(MP);
1409
1410     initializeAnalysisImpl(MP);
1411
1412     {
1413       PassManagerPrettyStackEntry X(MP, M);
1414       TimeRegion PassTimer(getPassTimer(MP));
1415
1416       LocalChanged |= MP->runOnModule(M);
1417     }
1418
1419     Changed |= LocalChanged;
1420     if (LocalChanged)
1421       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1422                    M.getModuleIdentifier());
1423     dumpPreservedSet(MP);
1424     
1425     verifyPreservedAnalysis(MP);
1426     removeNotPreservedAnalysis(MP);
1427     recordAvailableAnalysis(MP);
1428     removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1429   }
1430
1431   // Finalize on-the-fly passes
1432   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1433        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1434        I != E; ++I) {
1435     FunctionPassManagerImpl *FPP = I->second;
1436     // We don't know when is the last time an on-the-fly pass is run,
1437     // so we need to releaseMemory / finalize here
1438     FPP->releaseMemoryOnTheFly();
1439     Changed |= FPP->doFinalization(M);
1440   }
1441   return Changed;
1442 }
1443
1444 /// Add RequiredPass into list of lower level passes required by pass P.
1445 /// RequiredPass is run on the fly by Pass Manager when P requests it
1446 /// through getAnalysis interface.
1447 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1448   assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1449          "Unable to handle Pass that requires lower level Analysis pass");
1450   assert((P->getPotentialPassManagerType() < 
1451           RequiredPass->getPotentialPassManagerType()) &&
1452          "Unable to handle Pass that requires lower level Analysis pass");
1453
1454   FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1455   if (!FPP) {
1456     FPP = new FunctionPassManagerImpl(0);
1457     // FPP is the top level manager.
1458     FPP->setTopLevelManager(FPP);
1459
1460     OnTheFlyManagers[P] = FPP;
1461   }
1462   FPP->add(RequiredPass);
1463
1464   // Register P as the last user of RequiredPass.
1465   SmallVector<Pass *, 12> LU;
1466   LU.push_back(RequiredPass);
1467   FPP->setLastUser(LU,  P);
1468 }
1469
1470 /// Return function pass corresponding to PassInfo PI, that is 
1471 /// required by module pass MP. Instantiate analysis pass, by using
1472 /// its runOnFunction() for function F.
1473 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1474   FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1475   assert(FPP && "Unable to find on the fly pass");
1476   
1477   FPP->releaseMemoryOnTheFly();
1478   FPP->run(F);
1479   return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1480 }
1481
1482
1483 //===----------------------------------------------------------------------===//
1484 // PassManagerImpl implementation
1485 //
1486 /// run - Execute all of the passes scheduled for execution.  Keep track of
1487 /// whether any of the passes modifies the module, and if so, return true.
1488 bool PassManagerImpl::run(Module &M) {
1489   bool Changed = false;
1490   TimingInfo::createTheTimeInfo();
1491
1492   dumpArguments();
1493   dumpPasses();
1494
1495   initializeAllAnalysisInfo();
1496   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1497     Changed |= getContainedManager(Index)->runOnModule(M);
1498   return Changed;
1499 }
1500
1501 //===----------------------------------------------------------------------===//
1502 // PassManager implementation
1503
1504 /// Create new pass manager
1505 PassManager::PassManager() {
1506   PM = new PassManagerImpl(0);
1507   // PM is the top level manager
1508   PM->setTopLevelManager(PM);
1509 }
1510
1511 PassManager::~PassManager() {
1512   delete PM;
1513 }
1514
1515 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1516 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1517 /// will be destroyed as well, so there is no need to delete the pass.  This
1518 /// implies that all passes MUST be allocated with 'new'.
1519 void PassManager::add(Pass *P) {
1520   PM->add(P);
1521 }
1522
1523 /// run - Execute all of the passes scheduled for execution.  Keep track of
1524 /// whether any of the passes modifies the module, and if so, return true.
1525 bool PassManager::run(Module &M) {
1526   return PM->run(M);
1527 }
1528
1529 //===----------------------------------------------------------------------===//
1530 // TimingInfo Class - This class is used to calculate information about the
1531 // amount of time each pass takes to execute.  This only happens with
1532 // -time-passes is enabled on the command line.
1533 //
1534 bool llvm::TimePassesIsEnabled = false;
1535 static cl::opt<bool,true>
1536 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1537             cl::desc("Time each pass, printing elapsed time for each on exit"));
1538
1539 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1540 // a non null value (if the -time-passes option is enabled) or it leaves it
1541 // null.  It may be called multiple times.
1542 void TimingInfo::createTheTimeInfo() {
1543   if (!TimePassesIsEnabled || TheTimeInfo) return;
1544
1545   // Constructed the first time this is called, iff -time-passes is enabled.
1546   // This guarantees that the object will be constructed before static globals,
1547   // thus it will be destroyed before them.
1548   static ManagedStatic<TimingInfo> TTI;
1549   TheTimeInfo = &*TTI;
1550 }
1551
1552 /// If TimingInfo is enabled then start pass timer.
1553 Timer *llvm::getPassTimer(Pass *P) {
1554   if (TheTimeInfo) 
1555     return TheTimeInfo->getPassTimer(P);
1556   return 0;
1557 }
1558
1559 //===----------------------------------------------------------------------===//
1560 // PMStack implementation
1561 //
1562
1563 // Pop Pass Manager from the stack and clear its analysis info.
1564 void PMStack::pop() {
1565
1566   PMDataManager *Top = this->top();
1567   Top->initializeAnalysisInfo();
1568
1569   S.pop_back();
1570 }
1571
1572 // Push PM on the stack and set its top level manager.
1573 void PMStack::push(PMDataManager *PM) {
1574   assert(PM && "Unable to push. Pass Manager expected");
1575
1576   if (!this->empty()) {
1577     PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1578
1579     assert(TPM && "Unable to find top level manager");
1580     TPM->addIndirectPassManager(PM);
1581     PM->setTopLevelManager(TPM);
1582   }
1583
1584   S.push_back(PM);
1585 }
1586
1587 // Dump content of the pass manager stack.
1588 void PMStack::dump() {
1589   for (std::deque<PMDataManager *>::iterator I = S.begin(),
1590          E = S.end(); I != E; ++I)
1591     printf("%s ", (*I)->getAsPass()->getPassName());
1592
1593   if (!S.empty())
1594     printf("\n");
1595 }
1596
1597 /// Find appropriate Module Pass Manager in the PM Stack and
1598 /// add self into that manager. 
1599 void ModulePass::assignPassManager(PMStack &PMS, 
1600                                    PassManagerType PreferredType) {
1601   // Find Module Pass Manager
1602   while(!PMS.empty()) {
1603     PassManagerType TopPMType = PMS.top()->getPassManagerType();
1604     if (TopPMType == PreferredType)
1605       break; // We found desired pass manager
1606     else if (TopPMType > PMT_ModulePassManager)
1607       PMS.pop();    // Pop children pass managers
1608     else
1609       break;
1610   }
1611   assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1612   PMS.top()->add(this);
1613 }
1614
1615 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1616 /// in the PM Stack and add self into that manager. 
1617 void FunctionPass::assignPassManager(PMStack &PMS,
1618                                      PassManagerType PreferredType) {
1619
1620   // Find Module Pass Manager
1621   while (!PMS.empty()) {
1622     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1623       PMS.pop();
1624     else
1625       break; 
1626   }
1627
1628   // Create new Function Pass Manager if needed.
1629   FPPassManager *FPP;
1630   if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1631     FPP = (FPPassManager *)PMS.top();
1632   } else {
1633     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1634     PMDataManager *PMD = PMS.top();
1635
1636     // [1] Create new Function Pass Manager
1637     FPP = new FPPassManager(PMD->getDepth() + 1);
1638     FPP->populateInheritedAnalysis(PMS);
1639
1640     // [2] Set up new manager's top level manager
1641     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1642     TPM->addIndirectPassManager(FPP);
1643
1644     // [3] Assign manager to manage this new manager. This may create
1645     // and push new managers into PMS
1646     FPP->assignPassManager(PMS, PMD->getPassManagerType());
1647
1648     // [4] Push new manager into PMS
1649     PMS.push(FPP);
1650   }
1651
1652   // Assign FPP as the manager of this pass.
1653   FPP->add(this);
1654 }
1655
1656 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1657 /// in the PM Stack and add self into that manager. 
1658 void BasicBlockPass::assignPassManager(PMStack &PMS,
1659                                        PassManagerType PreferredType) {
1660   BBPassManager *BBP;
1661
1662   // Basic Pass Manager is a leaf pass manager. It does not handle
1663   // any other pass manager.
1664   if (!PMS.empty() && 
1665       PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1666     BBP = (BBPassManager *)PMS.top();
1667   } else {
1668     // If leaf manager is not Basic Block Pass manager then create new
1669     // basic Block Pass manager.
1670     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1671     PMDataManager *PMD = PMS.top();
1672
1673     // [1] Create new Basic Block Manager
1674     BBP = new BBPassManager(PMD->getDepth() + 1);
1675
1676     // [2] Set up new manager's top level manager
1677     // Basic Block Pass Manager does not live by itself
1678     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1679     TPM->addIndirectPassManager(BBP);
1680
1681     // [3] Assign manager to manage this new manager. This may create
1682     // and push new managers into PMS
1683     BBP->assignPassManager(PMS);
1684
1685     // [4] Push new manager into PMS
1686     PMS.push(BBP);
1687   }
1688
1689   // Assign BBP as the manager of this pass.
1690   BBP->add(this);
1691 }
1692
1693 PassManagerBase::~PassManagerBase() {}
1694   
1695 /*===-- C Bindings --------------------------------------------------------===*/
1696
1697 LLVMPassManagerRef LLVMCreatePassManager() {
1698   return wrap(new PassManager());
1699 }
1700
1701 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
1702   return wrap(new FunctionPassManager(unwrap(M)));
1703 }
1704
1705 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1706   return LLVMCreateFunctionPassManagerForModule(
1707                                             reinterpret_cast<LLVMModuleRef>(P));
1708 }
1709
1710 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1711   return unwrap<PassManager>(PM)->run(*unwrap(M));
1712 }
1713
1714 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1715   return unwrap<FunctionPassManager>(FPM)->doInitialization();
1716 }
1717
1718 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1719   return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1720 }
1721
1722 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1723   return unwrap<FunctionPassManager>(FPM)->doFinalization();
1724 }
1725
1726 void LLVMDisposePassManager(LLVMPassManagerRef PM) {
1727   delete unwrap(PM);
1728 }