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