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