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