s/addPassToManager/add/g
[oota-llvm.git] / lib / VMCore / PassManager.cpp
1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVM Pass Manager infrastructure. 
11 //
12 //===----------------------------------------------------------------------===//
13
14
15 #include "llvm/PassManagers.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include <vector>
23 #include <map>
24
25 // See PassManagers.h for Pass Manager infrastructure overview.
26
27 namespace llvm {
28
29 //===----------------------------------------------------------------------===//
30 // Pass debugging information.  Often it is useful to find out what pass is
31 // running when a crash occurs in a utility.  When this library is compiled with
32 // debugging on, a command line option (--debug-pass) is enabled that causes the
33 // pass name to be printed before it executes.
34 //
35
36 // Different debug levels that can be enabled...
37 enum PassDebugLevel {
38   None, Arguments, Structure, Executions, Details
39 };
40
41 static cl::opt<enum PassDebugLevel>
42 PassDebugging_New("debug-pass", cl::Hidden,
43                   cl::desc("Print PassManager debugging information"),
44                   cl::values(
45   clEnumVal(None      , "disable debug output"),
46   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
47   clEnumVal(Structure , "print pass structure before run()"),
48   clEnumVal(Executions, "print pass name before it is executed"),
49   clEnumVal(Details   , "print pass details when it is executed"),
50                              clEnumValEnd));
51 } // End of llvm namespace
52
53 namespace {
54
55 //===----------------------------------------------------------------------===//
56 // BBPassManager
57 //
58 /// BBPassManager manages BasicBlockPass. It batches all the
59 /// pass together and sequence them to process one basic block before
60 /// processing next basic block.
61 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager, 
62                                         public FunctionPass {
63
64 public:
65   BBPassManager(int Depth) : PMDataManager(Depth) { }
66
67   /// Execute all of the passes scheduled for execution.  Keep track of
68   /// whether any of the passes modifies the function, and if so, return true.
69   bool runOnFunction(Function &F);
70
71   /// Pass Manager itself does not invalidate any analysis info.
72   void getAnalysisUsage(AnalysisUsage &Info) const {
73     Info.setPreservesAll();
74   }
75
76   bool doInitialization(Module &M);
77   bool doInitialization(Function &F);
78   bool doFinalization(Module &M);
79   bool doFinalization(Function &F);
80
81   // Print passes managed by this manager
82   void dumpPassStructure(unsigned Offset) {
83     llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
84     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
85       BasicBlockPass *BP = getContainedPass(Index);
86       BP->dumpPassStructure(Offset + 1);
87       dumpLastUses(BP, Offset+1);
88     }
89   }
90
91   BasicBlockPass *getContainedPass(unsigned N) {
92     assert ( N < PassVector.size() && "Pass number out of range!");
93     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
94     return BP;
95   }
96
97   virtual PassManagerType getPassManagerType() { 
98     return PMT_BasicBlockPassManager; 
99   }
100 };
101
102 }
103
104 namespace llvm {
105
106 //===----------------------------------------------------------------------===//
107 // FunctionPassManagerImpl
108 //
109 /// FunctionPassManagerImpl manages FPPassManagers
110 class FunctionPassManagerImpl : public Pass,
111                                 public PMDataManager,
112                                 public PMTopLevelManager {
113 public:
114
115   FunctionPassManagerImpl(int Depth) : PMDataManager(Depth) { }
116
117   /// add - Add a pass to the queue of passes to run.  This passes ownership of
118   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
119   /// will be destroyed as well, so there is no need to delete the pass.  This
120   /// implies that all passes MUST be allocated with 'new'.
121   void add(Pass *P) {
122     schedulePass(P);
123   }
124  
125   /// run - Execute all of the passes scheduled for execution.  Keep track of
126   /// whether any of the passes modifies the module, and if so, return true.
127   bool run(Function &F);
128
129   /// doInitialization - Run all of the initializers for the function passes.
130   ///
131   bool doInitialization(Module &M);
132   
133   /// doFinalization - Run all of the initializers for the function passes.
134   ///
135   bool doFinalization(Module &M);
136
137   /// Pass Manager itself does not invalidate any analysis info.
138   void getAnalysisUsage(AnalysisUsage &Info) const {
139     Info.setPreservesAll();
140   }
141
142   inline void addTopLevelPass(Pass *P) {
143
144     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
145       
146       // P is a immutable pass and it will be managed by this
147       // top level manager. Set up analysis resolver to connect them.
148       AnalysisResolver *AR = new AnalysisResolver(*this);
149       P->setResolver(AR);
150       initializeAnalysisImpl(P);
151       addImmutablePass(IP);
152       recordAvailableAnalysis(IP);
153     } else {
154       // Assign manager
155       if (activeStack.empty()) {
156         FPPassManager *FPP = new FPPassManager(getDepth() + 1);
157         FPP->setTopLevelManager(this->getTopLevelManager());
158         addPassManager(FPP);
159         activeStack.push(FPP);
160       }
161       P->assignPassManager(activeStack);
162     }
163
164   }
165
166   FPPassManager *getContainedManager(unsigned N) {
167     assert ( N < PassManagers.size() && "Pass number out of range!");
168     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
169     return FP;
170   }
171
172 };
173
174 //===----------------------------------------------------------------------===//
175 // MPPassManager
176 //
177 /// MPPassManager manages ModulePasses and function pass managers.
178 /// It batches all Module passes  passes and function pass managers together and
179 /// sequence them to process one module.
180 class MPPassManager : public Pass, public PMDataManager {
181  
182 public:
183   MPPassManager(int Depth) : PMDataManager(Depth) { }
184   
185   /// run - Execute all of the passes scheduled for execution.  Keep track of
186   /// whether any of the passes modifies the module, and if so, return true.
187   bool runOnModule(Module &M);
188
189   /// Pass Manager itself does not invalidate any analysis info.
190   void getAnalysisUsage(AnalysisUsage &Info) const {
191     Info.setPreservesAll();
192   }
193
194   // Print passes managed by this manager
195   void dumpPassStructure(unsigned Offset) {
196     llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
197     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
198       ModulePass *MP = getContainedPass(Index);
199       MP->dumpPassStructure(Offset + 1);
200       dumpLastUses(MP, Offset+1);
201     }
202   }
203
204   ModulePass *getContainedPass(unsigned N) {
205     assert ( N < PassVector.size() && "Pass number out of range!");
206     ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
207     return MP;
208   }
209
210   virtual PassManagerType getPassManagerType() { return PMT_ModulePassManager; }
211 };
212
213 //===----------------------------------------------------------------------===//
214 // PassManagerImpl
215 //
216 /// PassManagerImpl manages MPPassManagers
217 class PassManagerImpl : public Pass,
218                         public PMDataManager,
219                         public PMTopLevelManager {
220
221 public:
222
223   PassManagerImpl(int Depth) : PMDataManager(Depth) { }
224
225   /// add - Add a pass to the queue of passes to run.  This passes ownership of
226   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
227   /// will be destroyed as well, so there is no need to delete the pass.  This
228   /// implies that all passes MUST be allocated with 'new'.
229   void add(Pass *P) {
230     schedulePass(P);
231   }
232  
233   /// run - Execute all of the passes scheduled for execution.  Keep track of
234   /// whether any of the passes modifies the module, and if so, return true.
235   bool run(Module &M);
236
237   /// Pass Manager itself does not invalidate any analysis info.
238   void getAnalysisUsage(AnalysisUsage &Info) const {
239     Info.setPreservesAll();
240   }
241
242   inline void addTopLevelPass(Pass *P) {
243
244     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
245       
246       // P is a immutable pass and it will be managed by this
247       // top level manager. Set up analysis resolver to connect them.
248       AnalysisResolver *AR = new AnalysisResolver(*this);
249       P->setResolver(AR);
250       initializeAnalysisImpl(P);
251       addImmutablePass(IP);
252       recordAvailableAnalysis(IP);
253     } else {
254
255       // Assign manager
256       if (activeStack.empty()) {
257         MPPassManager *MPP = new MPPassManager(getDepth() + 1);
258         MPP->setTopLevelManager(this->getTopLevelManager());
259         addPassManager(MPP);
260         activeStack.push(MPP);
261       }
262       
263       P->assignPassManager(activeStack);
264     }
265
266   }
267
268   MPPassManager *getContainedManager(unsigned N) {
269     assert ( N < PassManagers.size() && "Pass number out of range!");
270     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
271     return MP;
272   }
273
274 };
275
276 } // End of llvm namespace
277
278 namespace {
279
280 //===----------------------------------------------------------------------===//
281 // TimingInfo Class - This class is used to calculate information about the
282 // amount of time each pass takes to execute.  This only happens when
283 // -time-passes is enabled on the command line.
284 //
285
286 class VISIBILITY_HIDDEN TimingInfo {
287   std::map<Pass*, Timer> TimingData;
288   TimerGroup TG;
289
290 public:
291   // Use 'create' member to get this.
292   TimingInfo() : TG("... Pass execution timing report ...") {}
293   
294   // TimingDtor - Print out information about timing information
295   ~TimingInfo() {
296     // Delete all of the timers...
297     TimingData.clear();
298     // TimerGroup is deleted next, printing the report.
299   }
300
301   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
302   // to a non null value (if the -time-passes option is enabled) or it leaves it
303   // null.  It may be called multiple times.
304   static void createTheTimeInfo();
305
306   void passStarted(Pass *P) {
307
308     if (dynamic_cast<PMDataManager *>(P)) 
309       return;
310
311     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
312     if (I == TimingData.end())
313       I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
314     I->second.startTimer();
315   }
316   void passEnded(Pass *P) {
317
318     if (dynamic_cast<PMDataManager *>(P)) 
319       return;
320
321     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
322     assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
323     I->second.stopTimer();
324   }
325 };
326
327 static TimingInfo *TheTimeInfo;
328
329 } // End of anon namespace
330
331 //===----------------------------------------------------------------------===//
332 // PMTopLevelManager implementation
333
334 /// Set pass P as the last user of the given analysis passes.
335 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses, 
336                                     Pass *P) {
337
338   for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
339          E = AnalysisPasses.end(); I != E; ++I) {
340     Pass *AP = *I;
341     LastUser[AP] = P;
342     // If AP is the last user of other passes then make P last user of
343     // such passes.
344     for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
345            LUE = LastUser.end(); LUI != LUE; ++LUI) {
346       if (LUI->second == AP)
347         LastUser[LUI->first] = P;
348     }
349   }
350 }
351
352 /// Collect passes whose last user is P
353 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
354                                             Pass *P) {
355    for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
356           LUE = LastUser.end(); LUI != LUE; ++LUI)
357       if (LUI->second == P)
358         LastUses.push_back(LUI->first);
359 }
360
361 /// Schedule pass P for execution. Make sure that passes required by
362 /// P are run before P is run. Update analysis info maintained by
363 /// the manager. Remove dead passes. This is a recursive function.
364 void PMTopLevelManager::schedulePass(Pass *P) {
365
366   // TODO : Allocate function manager for this pass, other wise required set
367   // may be inserted into previous function manager
368
369   AnalysisUsage AnUsage;
370   P->getAnalysisUsage(AnUsage);
371   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
372   for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
373          E = RequiredSet.end(); I != E; ++I) {
374
375     Pass *AnalysisPass = findAnalysisPass(*I);
376     if (!AnalysisPass) {
377       // Schedule this analysis run first.
378       AnalysisPass = (*I)->createPass();
379       schedulePass(AnalysisPass);
380     }
381   }
382
383   // Now all required passes are available.
384   addTopLevelPass(P);
385 }
386
387 /// Find the pass that implements Analysis AID. Search immutable
388 /// passes and all pass managers. If desired pass is not found
389 /// then return NULL.
390 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
391
392   Pass *P = NULL;
393   // Check pass managers
394   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
395          E = PassManagers.end(); P == NULL && I != E; ++I) {
396     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
397     assert(PMD && "This is not a PassManager");
398     P = PMD->findAnalysisPass(AID, false);
399   }
400
401   // Check other pass managers
402   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
403          E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
404     P = (*I)->findAnalysisPass(AID, false);
405
406   for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
407          E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
408     const PassInfo *PI = (*I)->getPassInfo();
409     if (PI == AID)
410       P = *I;
411
412     // If Pass not found then check the interfaces implemented by Immutable Pass
413     if (!P) {
414       const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
415       if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
416         P = *I;
417     }
418   }
419
420   return P;
421 }
422
423 // Print passes managed by this top level manager.
424 void PMTopLevelManager::dumpPasses() const {
425
426   if (PassDebugging_New < Structure)
427     return;
428
429   // Print out the immutable passes
430   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
431     ImmutablePasses[i]->dumpPassStructure(0);
432   }
433   
434   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
435          E = PassManagers.end(); I != E; ++I)
436     (*I)->dumpPassStructure(1);
437 }
438
439 void PMTopLevelManager::dumpArguments() const {
440
441   if (PassDebugging_New < Arguments)
442     return;
443
444   cerr << "Pass Arguments: ";
445   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
446          E = PassManagers.end(); I != E; ++I) {
447     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
448     assert(PMD && "This is not a PassManager");
449     PMD->dumpPassArguments();
450   }
451   cerr << "\n";
452 }
453
454 void PMTopLevelManager::initializeAllAnalysisInfo() {
455   
456   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
457          E = PassManagers.end(); I != E; ++I) {
458     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
459     assert(PMD && "This is not a PassManager");
460     PMD->initializeAnalysisInfo();
461   }
462   
463   // Initailize other pass managers
464   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
465          E = IndirectPassManagers.end(); I != E; ++I)
466     (*I)->initializeAnalysisInfo();
467 }
468
469 /// Destructor
470 PMTopLevelManager::~PMTopLevelManager() {
471   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
472          E = PassManagers.end(); I != E; ++I)
473     delete *I;
474   
475   for (std::vector<ImmutablePass *>::iterator
476          I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
477     delete *I;
478   
479   PassManagers.clear();
480 }
481
482 //===----------------------------------------------------------------------===//
483 // PMDataManager implementation
484
485 /// Return true IFF pass P's required analysis set does not required new
486 /// manager.
487 bool PMDataManager::manageablePass(Pass *P) {
488
489   // TODO 
490   // If this pass is not preserving information that is required by a
491   // pass maintained by higher level pass manager then do not insert
492   // this pass into current manager. Use new manager. For example,
493   // For example, If FunctionPass F is not preserving ModulePass Info M1
494   // that is used by another ModulePass M2 then do not insert F in
495   // current function pass manager.
496   return true;
497 }
498
499 /// Augement AvailableAnalysis by adding analysis made available by pass P.
500 void PMDataManager::recordAvailableAnalysis(Pass *P) {
501                                                 
502   if (const PassInfo *PI = P->getPassInfo()) {
503     AvailableAnalysis[PI] = P;
504
505     //This pass is the current implementation of all of the interfaces it
506     //implements as well.
507     const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
508     for (unsigned i = 0, e = II.size(); i != e; ++i)
509       AvailableAnalysis[II[i]] = P;
510   }
511 }
512
513 /// Remove Analyss not preserved by Pass P
514 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
515   AnalysisUsage AnUsage;
516   P->getAnalysisUsage(AnUsage);
517
518   if (AnUsage.getPreservesAll())
519     return;
520
521   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
522   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
523          E = AvailableAnalysis.end(); I != E; ) {
524     std::map<AnalysisID, Pass*>::iterator Info = I++;
525     if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
526         PreservedSet.end()) {
527       // Remove this analysis
528       if (!dynamic_cast<ImmutablePass*>(Info->second))
529         AvailableAnalysis.erase(Info);
530     }
531   }
532 }
533
534 /// Remove analysis passes that are not used any longer
535 void PMDataManager::removeDeadPasses(Pass *P, std::string &Msg) {
536
537   std::vector<Pass *> DeadPasses;
538   TPM->collectLastUses(DeadPasses, P);
539
540   for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
541          E = DeadPasses.end(); I != E; ++I) {
542
543     std::string Msg1 = "  Freeing Pass '";
544     dumpPassInfo(*I, Msg1, Msg);
545
546     if (TheTimeInfo) TheTimeInfo->passStarted(P);
547     (*I)->releaseMemory();
548     if (TheTimeInfo) TheTimeInfo->passEnded(P);
549
550     std::map<AnalysisID, Pass*>::iterator Pos = 
551       AvailableAnalysis.find((*I)->getPassInfo());
552     
553     // It is possible that pass is already removed from the AvailableAnalysis
554     if (Pos != AvailableAnalysis.end())
555       AvailableAnalysis.erase(Pos);
556   }
557 }
558
559 /// Add pass P into the PassVector. Update 
560 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
561 void PMDataManager::add(Pass *P, 
562                                      bool ProcessAnalysis) {
563
564   // This manager is going to manage pass P. Set up analysis resolver
565   // to connect them.
566   AnalysisResolver *AR = new AnalysisResolver(*this);
567   P->setResolver(AR);
568
569   if (ProcessAnalysis) {
570
571     // At the moment, this pass is the last user of all required passes.
572     std::vector<Pass *> LastUses;
573     std::vector<Pass *> RequiredPasses;
574     unsigned PDepth = this->getDepth();
575
576     collectRequiredAnalysisPasses(RequiredPasses, P);
577     for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
578            E = RequiredPasses.end(); I != E; ++I) {
579       Pass *PRequired = *I;
580       unsigned RDepth = 0;
581
582       PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
583       RDepth = DM.getDepth();
584
585       if (PDepth == RDepth)
586         LastUses.push_back(PRequired);
587       else if (PDepth >  RDepth) {
588         // Let the parent claim responsibility of last use
589         TransferLastUses.push_back(PRequired);
590       } else {
591         // Note : This feature is not yet implemented
592         assert (0 && 
593                 "Unable to handle Pass that requires lower level Analysis pass");
594       }
595     }
596
597     LastUses.push_back(P);
598     TPM->setLastUser(LastUses, P);
599
600     // Take a note of analysis required and made available by this pass.
601     // Remove the analysis not preserved by this pass
602     removeNotPreservedAnalysis(P);
603     recordAvailableAnalysis(P);
604   }
605
606   // Add pass
607   PassVector.push_back(P);
608 }
609
610 /// Populate RequiredPasses with the analysis pass that are required by
611 /// pass P.
612 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
613                                                   Pass *P) {
614   AnalysisUsage AnUsage;
615   P->getAnalysisUsage(AnUsage);
616   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
617   for (std::vector<AnalysisID>::const_iterator 
618          I = RequiredSet.begin(), E = RequiredSet.end();
619        I != E; ++I) {
620     Pass *AnalysisPass = findAnalysisPass(*I, true);
621     assert (AnalysisPass && "Analysis pass is not available");
622     RP.push_back(AnalysisPass);
623   }
624
625   const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
626   for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
627          E = IDs.end(); I != E; ++I) {
628     Pass *AnalysisPass = findAnalysisPass(*I, true);
629     assert (AnalysisPass && "Analysis pass is not available");
630     RP.push_back(AnalysisPass);
631   }
632 }
633
634 // All Required analyses should be available to the pass as it runs!  Here
635 // we fill in the AnalysisImpls member of the pass so that it can
636 // successfully use the getAnalysis() method to retrieve the
637 // implementations it needs.
638 //
639 void PMDataManager::initializeAnalysisImpl(Pass *P) {
640   AnalysisUsage AnUsage;
641   P->getAnalysisUsage(AnUsage);
642  
643   for (std::vector<const PassInfo *>::const_iterator
644          I = AnUsage.getRequiredSet().begin(),
645          E = AnUsage.getRequiredSet().end(); I != E; ++I) {
646     Pass *Impl = findAnalysisPass(*I, true);
647     if (Impl == 0)
648       assert(0 && "Analysis used but not available!");
649     AnalysisResolver *AR = P->getResolver();
650     AR->addAnalysisImplsPair(*I, Impl);
651   }
652 }
653
654 /// Find the pass that implements Analysis AID. If desired pass is not found
655 /// then return NULL.
656 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
657
658   // Check if AvailableAnalysis map has one entry.
659   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
660
661   if (I != AvailableAnalysis.end())
662     return I->second;
663
664   // Search Parents through TopLevelManager
665   if (SearchParent)
666     return TPM->findAnalysisPass(AID);
667   
668   return NULL;
669 }
670
671 // Print list of passes that are last used by P.
672 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
673
674   std::vector<Pass *> LUses;
675   
676   assert (TPM && "Top Level Manager is missing");
677   TPM->collectLastUses(LUses, P);
678   
679   for (std::vector<Pass *>::iterator I = LUses.begin(),
680          E = LUses.end(); I != E; ++I) {
681     llvm::cerr << "--" << std::string(Offset*2, ' ');
682     (*I)->dumpPassStructure(0);
683   }
684 }
685
686 void PMDataManager::dumpPassArguments() const {
687   for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
688         E = PassVector.end(); I != E; ++I) {
689     if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
690       PMD->dumpPassArguments();
691     else
692       if (const PassInfo *PI = (*I)->getPassInfo())
693         if (!PI->isAnalysisGroup())
694           cerr << " -" << PI->getPassArgument();
695   }
696 }
697
698 void PMDataManager:: dumpPassInfo(Pass *P,  std::string &Msg1, 
699                                   std::string &Msg2) const {
700   if (PassDebugging_New < Executions)
701     return;
702   cerr << (void*)this << std::string(getDepth()*2+1, ' ');
703   cerr << Msg1;
704   cerr << P->getPassName();
705   cerr << Msg2;
706 }
707
708 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
709                                         const std::vector<AnalysisID> &Set) 
710   const {
711   if (PassDebugging_New >= Details && !Set.empty()) {
712     cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
713       for (unsigned i = 0; i != Set.size(); ++i) {
714         if (i) cerr << ",";
715         cerr << " " << Set[i]->getPassName();
716       }
717       cerr << "\n";
718   }
719 }
720
721 // Destructor
722 PMDataManager::~PMDataManager() {
723   
724   for (std::vector<Pass *>::iterator I = PassVector.begin(),
725          E = PassVector.end(); I != E; ++I)
726     delete *I;
727   
728   PassVector.clear();
729 }
730
731 //===----------------------------------------------------------------------===//
732 // NOTE: Is this the right place to define this method ?
733 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
734 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
735   return PM.findAnalysisPass(ID, dir);
736 }
737
738 //===----------------------------------------------------------------------===//
739 // BBPassManager implementation
740
741 /// Execute all of the passes scheduled for execution by invoking 
742 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
743 /// the function, and if so, return true.
744 bool
745 BBPassManager::runOnFunction(Function &F) {
746
747   if (F.isExternal())
748     return false;
749
750   bool Changed = doInitialization(F);
751
752   std::string Msg1 = "Executing Pass '";
753   std::string Msg3 = "' Made Modification '";
754
755   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
756     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
757       BasicBlockPass *BP = getContainedPass(Index);
758       AnalysisUsage AnUsage;
759       BP->getAnalysisUsage(AnUsage);
760
761       std::string Msg2 = "' on BasicBlock '" + (*I).getName() + "'...\n";
762       dumpPassInfo(BP, Msg1, Msg2);
763       dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
764
765       initializeAnalysisImpl(BP);
766
767       if (TheTimeInfo) TheTimeInfo->passStarted(BP);
768       Changed |= BP->runOnBasicBlock(*I);
769       if (TheTimeInfo) TheTimeInfo->passEnded(BP);
770
771       if (Changed)
772         dumpPassInfo(BP, Msg3, Msg2);
773       dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
774
775       removeNotPreservedAnalysis(BP);
776       recordAvailableAnalysis(BP);
777       removeDeadPasses(BP, Msg2);
778     }
779   return Changed |= doFinalization(F);
780 }
781
782 // Implement doInitialization and doFinalization
783 inline bool BBPassManager::doInitialization(Module &M) {
784   bool Changed = false;
785
786   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
787     BasicBlockPass *BP = getContainedPass(Index);
788     Changed |= BP->doInitialization(M);
789   }
790
791   return Changed;
792 }
793
794 inline bool BBPassManager::doFinalization(Module &M) {
795   bool Changed = false;
796
797   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
798     BasicBlockPass *BP = getContainedPass(Index);
799     Changed |= BP->doFinalization(M);
800   }
801
802   return Changed;
803 }
804
805 inline bool BBPassManager::doInitialization(Function &F) {
806   bool Changed = false;
807
808   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
809     BasicBlockPass *BP = getContainedPass(Index);
810     Changed |= BP->doInitialization(F);
811   }
812
813   return Changed;
814 }
815
816 inline bool BBPassManager::doFinalization(Function &F) {
817   bool Changed = false;
818
819   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
820     BasicBlockPass *BP = getContainedPass(Index);
821     Changed |= BP->doFinalization(F);
822   }
823
824   return Changed;
825 }
826
827
828 //===----------------------------------------------------------------------===//
829 // FunctionPassManager implementation
830
831 /// Create new Function pass manager
832 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
833   FPM = new FunctionPassManagerImpl(0);
834   // FPM is the top level manager.
835   FPM->setTopLevelManager(FPM);
836
837   PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
838   AnalysisResolver *AR = new AnalysisResolver(*PMD);
839   FPM->setResolver(AR);
840   
841   MP = P;
842 }
843
844 FunctionPassManager::~FunctionPassManager() {
845   delete FPM;
846 }
847
848 /// add - Add a pass to the queue of passes to run.  This passes
849 /// ownership of the Pass to the PassManager.  When the
850 /// PassManager_X is destroyed, the pass will be destroyed as well, so
851 /// there is no need to delete the pass. (TODO delete passes.)
852 /// This implies that all passes MUST be allocated with 'new'.
853 void FunctionPassManager::add(Pass *P) { 
854   FPM->add(P);
855 }
856
857 /// run - Execute all of the passes scheduled for execution.  Keep
858 /// track of whether any of the passes modifies the function, and if
859 /// so, return true.
860 ///
861 bool FunctionPassManager::run(Function &F) {
862   std::string errstr;
863   if (MP->materializeFunction(&F, &errstr)) {
864     cerr << "Error reading bytecode file: " << errstr << "\n";
865     abort();
866   }
867   return FPM->run(F);
868 }
869
870
871 /// doInitialization - Run all of the initializers for the function passes.
872 ///
873 bool FunctionPassManager::doInitialization() {
874   return FPM->doInitialization(*MP->getModule());
875 }
876
877 /// doFinalization - Run all of the initializers for the function passes.
878 ///
879 bool FunctionPassManager::doFinalization() {
880   return FPM->doFinalization(*MP->getModule());
881 }
882
883 //===----------------------------------------------------------------------===//
884 // FunctionPassManagerImpl implementation
885 //
886 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
887   bool Changed = false;
888
889   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
890     FPPassManager *FP = getContainedManager(Index);
891     Changed |= FP->doInitialization(M);
892   }
893
894   return Changed;
895 }
896
897 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
898   bool Changed = false;
899
900   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
901     FPPassManager *FP = getContainedManager(Index);
902     Changed |= FP->doFinalization(M);
903   }
904
905   return Changed;
906 }
907
908 // Execute all the passes managed by this top level manager.
909 // Return true if any function is modified by a pass.
910 bool FunctionPassManagerImpl::run(Function &F) {
911
912   bool Changed = false;
913
914   TimingInfo::createTheTimeInfo();
915
916   dumpArguments();
917   dumpPasses();
918
919   initializeAllAnalysisInfo();
920   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
921     FPPassManager *FP = getContainedManager(Index);
922     Changed |= FP->runOnFunction(F);
923   }
924   return Changed;
925 }
926
927 //===----------------------------------------------------------------------===//
928 // FPPassManager implementation
929
930 /// Print passes managed by this manager
931 void FPPassManager::dumpPassStructure(unsigned Offset) {
932   llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
933   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
934     FunctionPass *FP = getContainedPass(Index);
935     FP->dumpPassStructure(Offset + 1);
936     dumpLastUses(FP, Offset+1);
937   }
938 }
939
940
941 /// Execute all of the passes scheduled for execution by invoking 
942 /// runOnFunction method.  Keep track of whether any of the passes modifies 
943 /// the function, and if so, return true.
944 bool FPPassManager::runOnFunction(Function &F) {
945
946   bool Changed = false;
947
948   if (F.isExternal())
949     return false;
950
951   std::string Msg1 = "Executing Pass '";
952   std::string Msg3 = "' Made Modification '";
953
954   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
955     FunctionPass *FP = getContainedPass(Index);
956
957     AnalysisUsage AnUsage;
958     FP->getAnalysisUsage(AnUsage);
959
960     std::string Msg2 = "' on Function '" + F.getName() + "'...\n";
961     dumpPassInfo(FP, Msg1, Msg2);
962     dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
963
964     initializeAnalysisImpl(FP);
965
966     if (TheTimeInfo) TheTimeInfo->passStarted(FP);
967     Changed |= FP->runOnFunction(F);
968     if (TheTimeInfo) TheTimeInfo->passEnded(FP);
969
970     if (Changed)
971       dumpPassInfo(FP, Msg3, Msg2);
972     dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
973
974     removeNotPreservedAnalysis(FP);
975     recordAvailableAnalysis(FP);
976     removeDeadPasses(FP, Msg2);
977   }
978   return Changed;
979 }
980
981 bool FPPassManager::runOnModule(Module &M) {
982
983   bool Changed = doInitialization(M);
984
985   for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
986     this->runOnFunction(*I);
987
988   return Changed |= doFinalization(M);
989 }
990
991 inline bool FPPassManager::doInitialization(Module &M) {
992   bool Changed = false;
993
994   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
995     FunctionPass *FP = getContainedPass(Index);
996     Changed |= FP->doInitialization(M);
997   }
998
999   return Changed;
1000 }
1001
1002 inline bool FPPassManager::doFinalization(Module &M) {
1003   bool Changed = false;
1004
1005   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1006     FunctionPass *FP = getContainedPass(Index);
1007     Changed |= FP->doFinalization(M);
1008   }
1009
1010   return Changed;
1011 }
1012
1013 //===----------------------------------------------------------------------===//
1014 // MPPassManager implementation
1015
1016 /// Execute all of the passes scheduled for execution by invoking 
1017 /// runOnModule method.  Keep track of whether any of the passes modifies 
1018 /// the module, and if so, return true.
1019 bool
1020 MPPassManager::runOnModule(Module &M) {
1021   bool Changed = false;
1022
1023   std::string Msg1 = "Executing Pass '";
1024   std::string Msg3 = "' Made Modification '";
1025
1026   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1027     ModulePass *MP = getContainedPass(Index);
1028
1029     AnalysisUsage AnUsage;
1030     MP->getAnalysisUsage(AnUsage);
1031
1032     std::string Msg2 = "' on Module '" + M.getModuleIdentifier() + "'...\n";
1033     dumpPassInfo(MP, Msg1, Msg2);
1034     dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1035
1036     initializeAnalysisImpl(MP);
1037
1038     if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1039     Changed |= MP->runOnModule(M);
1040     if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1041
1042     if (Changed)
1043       dumpPassInfo(MP, Msg3, Msg2);
1044     dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1045       
1046     removeNotPreservedAnalysis(MP);
1047     recordAvailableAnalysis(MP);
1048     removeDeadPasses(MP, Msg2);
1049   }
1050   return Changed;
1051 }
1052
1053 //===----------------------------------------------------------------------===//
1054 // PassManagerImpl implementation
1055 //
1056 /// run - Execute all of the passes scheduled for execution.  Keep track of
1057 /// whether any of the passes modifies the module, and if so, return true.
1058 bool PassManagerImpl::run(Module &M) {
1059
1060   bool Changed = false;
1061
1062   TimingInfo::createTheTimeInfo();
1063
1064   dumpArguments();
1065   dumpPasses();
1066
1067   initializeAllAnalysisInfo();
1068   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1069     MPPassManager *MP = getContainedManager(Index);
1070     Changed |= MP->runOnModule(M);
1071   }
1072   return Changed;
1073 }
1074
1075 //===----------------------------------------------------------------------===//
1076 // PassManager implementation
1077
1078 /// Create new pass manager
1079 PassManager::PassManager() {
1080   PM = new PassManagerImpl(0);
1081   // PM is the top level manager
1082   PM->setTopLevelManager(PM);
1083 }
1084
1085 PassManager::~PassManager() {
1086   delete PM;
1087 }
1088
1089 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1090 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1091 /// will be destroyed as well, so there is no need to delete the pass.  This
1092 /// implies that all passes MUST be allocated with 'new'.
1093 void 
1094 PassManager::add(Pass *P) {
1095   PM->add(P);
1096 }
1097
1098 /// run - Execute all of the passes scheduled for execution.  Keep track of
1099 /// whether any of the passes modifies the module, and if so, return true.
1100 bool
1101 PassManager::run(Module &M) {
1102   return PM->run(M);
1103 }
1104
1105 //===----------------------------------------------------------------------===//
1106 // TimingInfo Class - This class is used to calculate information about the
1107 // amount of time each pass takes to execute.  This only happens with
1108 // -time-passes is enabled on the command line.
1109 //
1110 bool llvm::TimePassesIsEnabled = false;
1111 static cl::opt<bool,true>
1112 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1113             cl::desc("Time each pass, printing elapsed time for each on exit"));
1114
1115 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1116 // a non null value (if the -time-passes option is enabled) or it leaves it
1117 // null.  It may be called multiple times.
1118 void TimingInfo::createTheTimeInfo() {
1119   if (!TimePassesIsEnabled || TheTimeInfo) return;
1120
1121   // Constructed the first time this is called, iff -time-passes is enabled.
1122   // This guarantees that the object will be constructed before static globals,
1123   // thus it will be destroyed before them.
1124   static ManagedStatic<TimingInfo> TTI;
1125   TheTimeInfo = &*TTI;
1126 }
1127
1128 //===----------------------------------------------------------------------===//
1129 // PMStack implementation
1130 //
1131
1132 // Pop Pass Manager from the stack and clear its analysis info.
1133 void PMStack::pop() {
1134
1135   PMDataManager *Top = this->top();
1136   Top->initializeAnalysisInfo();
1137
1138   S.pop_back();
1139 }
1140
1141 // Push PM on the stack and set its top level manager.
1142 void PMStack::push(Pass *P) {
1143
1144   PMDataManager *Top = NULL;
1145   PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1146   assert (PM && "Unable to push. Pass Manager expected");
1147
1148   if (this->empty()) {
1149     Top = PM;
1150   } 
1151   else {
1152     Top = this->top();
1153     PMTopLevelManager *TPM = Top->getTopLevelManager();
1154
1155     assert (TPM && "Unable to find top level manager");
1156     TPM->addIndirectPassManager(PM);
1157     PM->setTopLevelManager(TPM);
1158   }
1159
1160   AnalysisResolver *AR = new AnalysisResolver(*Top);
1161   P->setResolver(AR);
1162
1163   S.push_back(PM);
1164 }
1165
1166 // Dump content of the pass manager stack.
1167 void PMStack::dump() {
1168   for(std::deque<PMDataManager *>::iterator I = S.begin(),
1169         E = S.end(); I != E; ++I) {
1170     Pass *P = dynamic_cast<Pass *>(*I);
1171     printf ("%s ", P->getPassName());
1172   }
1173   if (!S.empty())
1174     printf ("\n");
1175 }
1176
1177 // Walk Pass Manager stack and set LastUse markers if any
1178 // manager is transfering this priviledge to its parent manager
1179 void PMStack::handleLastUserOverflow() {
1180
1181   for(PMStack::iterator I = this->begin(), E = this->end(); I != E;) {
1182
1183     PMDataManager *Child = *I++;
1184     if (I != E) {
1185       PMDataManager *Parent = *I++;
1186       PMTopLevelManager *TPM = Parent->getTopLevelManager();
1187       std::vector<Pass *> &TLU = Child->getTransferredLastUses();
1188       if (!TLU.empty()) {
1189         Pass *P = dynamic_cast<Pass *>(Parent);
1190         TPM->setLastUser(TLU, P);
1191       }
1192     }
1193   }
1194 }
1195
1196 /// Find appropriate Module Pass Manager in the PM Stack and
1197 /// add self into that manager. 
1198 void ModulePass::assignPassManager(PMStack &PMS) {
1199
1200   // Find Module Pass Manager
1201   while(!PMS.empty()) {
1202     if (PMS.top()->getPassManagerType() > PMT_ModulePassManager)
1203       PMS.pop();    // Pop children pass managers
1204     else
1205       break;
1206   }
1207   MPPassManager *MPP = dynamic_cast<MPPassManager *>(PMS.top());
1208
1209   assert(MPP && "Unable to find Module Pass Manager");
1210   MPP->add(this);
1211 }
1212
1213 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1214 /// in the PM Stack and add self into that manager. 
1215 void FunctionPass::assignPassManager(PMStack &PMS) {
1216
1217   // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1218   while(!PMS.empty()) {
1219     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1220       PMS.pop();
1221     else
1222       break; 
1223   }
1224   FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1225
1226   // Create new Function Pass Manager
1227   if (!FPP) {
1228     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1229     PMDataManager *PMD = PMS.top();
1230
1231     // [1] Create new Function Pass Manager
1232     FPP = new FPPassManager(PMD->getDepth() + 1);
1233
1234     // [2] Set up new manager's top level manager
1235     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1236     TPM->addIndirectPassManager(FPP);
1237
1238     // [3] Assign manager to manage this new manager. This may create
1239     // and push new managers into PMS
1240     Pass *P = dynamic_cast<Pass *>(FPP);
1241     P->assignPassManager(PMS);
1242
1243     // [4] Push new manager into PMS
1244     PMS.push(FPP);
1245   }
1246
1247   // Assign FPP as the manager of this pass.
1248   FPP->add(this);
1249 }
1250
1251 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1252 /// in the PM Stack and add self into that manager. 
1253 void BasicBlockPass::assignPassManager(PMStack &PMS) {
1254
1255   BBPassManager *BBP = NULL;
1256
1257   // Basic Pass Manager is a leaf pass manager. It does not handle
1258   // any other pass manager.
1259   if (!PMS.empty()) {
1260     BBP = dynamic_cast<BBPassManager *>(PMS.top());
1261   }
1262
1263   // If leaf manager is not Basic Block Pass manager then create new
1264   // basic Block Pass manager.
1265
1266   if (!BBP) {
1267     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1268     PMDataManager *PMD = PMS.top();
1269
1270     // [1] Create new Basic Block Manager
1271     BBP = new BBPassManager(PMD->getDepth() + 1);
1272
1273     // [2] Set up new manager's top level manager
1274     // Basic Block Pass Manager does not live by itself
1275     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1276     TPM->addIndirectPassManager(BBP);
1277
1278     // [3] Assign manager to manage this new manager. This may create
1279     // and push new managers into PMS
1280     Pass *P = dynamic_cast<Pass *>(BBP);
1281     P->assignPassManager(PMS);
1282
1283     // [4] Push new manager into PMS
1284     PMS.push(BBP);
1285   }
1286
1287   // Assign BBP as the manager of this pass.
1288   BBP->add(this);
1289 }
1290
1291