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