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