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