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