Now, there is additional layer, referred in the comment,
[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/PassManager.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 using namespace llvm;
26 class llvm::PMDataManager;
27
28 //===----------------------------------------------------------------------===//
29 // Overview:
30 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
31 // 
32 //   o Manage optimization pass execution order
33 //   o Make required Analysis information available before pass P is run
34 //   o Release memory occupied by dead passes
35 //   o If Analysis information is dirtied by a pass then regenerate Analysis 
36 //     information before it is consumed by another pass.
37 //
38 // Pass Manager Infrastructure uses multiple pass managers.  They are
39 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
40 // This class hierarcy uses multiple inheritance but pass managers do not derive
41 // from another pass manager.
42 //
43 // PassManager and FunctionPassManager are two top-level pass manager that
44 // represents the external interface of this entire pass manager infrastucture.
45 //
46 // Important classes :
47 //
48 // [o] class PMTopLevelManager;
49 //
50 // Two top level managers, PassManager and FunctionPassManager, derive from 
51 // PMTopLevelManager. PMTopLevelManager manages information used by top level 
52 // managers such as last user info.
53 //
54 // [o] class PMDataManager;
55 //
56 // PMDataManager manages information, e.g. list of available analysis info, 
57 // used by a pass manager to manage execution order of passes. It also provides
58 // a place to implement common pass manager APIs. All pass managers derive from
59 // PMDataManager.
60 //
61 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
62 //
63 // BBPassManager manages BasicBlockPasses.
64 //
65 // [o] class FunctionPassManager;
66 //
67 // This is a external interface used by JIT to manage FunctionPasses. This
68 // interface relies on FunctionPassManagerImpl to do all the tasks.
69 //
70 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
71 //                                     public PMTopLevelManager;
72 //
73 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
74 //
75 // [o] class FPPassManager : public ModulePass, public PMDataManager;
76 //
77 // FPPassManager manages FunctionPasses and BBPassManagers
78 //
79 // [o] class MPPassManager : public Pass, public PMDataManager;
80 //
81 // MPPassManager manages ModulePasses and FPPassManagers
82 //
83 // [o] class PassManager;
84 //
85 // This is a external interface used by various tools to manages passes. It
86 // relies on PassManagerImpl to do all the tasks.
87 //
88 // [o] class PassManagerImpl : public Pass, public PMDataManager,
89 //                             public PMDTopLevelManager
90 //
91 // PassManagerImpl is a top level pass manager responsible for managing
92 // MPPassManagers.
93 //===----------------------------------------------------------------------===//
94
95 namespace llvm {
96
97 //===----------------------------------------------------------------------===//
98 // Pass debugging information.  Often it is useful to find out what pass is
99 // running when a crash occurs in a utility.  When this library is compiled with
100 // debugging on, a command line option (--debug-pass) is enabled that causes the
101 // pass name to be printed before it executes.
102 //
103
104 // Different debug levels that can be enabled...
105 enum PassDebugLevel {
106   None, Arguments, Structure, Executions, Details
107 };
108
109 static cl::opt<enum PassDebugLevel>
110 PassDebugging_New("debug-pass", cl::Hidden,
111                   cl::desc("Print PassManager debugging information"),
112                   cl::values(
113   clEnumVal(None      , "disable debug output"),
114   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
115   clEnumVal(Structure , "print pass structure before run()"),
116   clEnumVal(Executions, "print pass name before it is executed"),
117   clEnumVal(Details   , "print pass details when it is executed"),
118                              clEnumValEnd));
119 } // End of llvm namespace
120
121 #ifndef USE_OLD_PASSMANAGER
122 namespace {
123
124 //===----------------------------------------------------------------------===//
125 // PMTopLevelManager
126 //
127 /// PMTopLevelManager manages LastUser info and collects common APIs used by
128 /// top level pass managers.
129 class VISIBILITY_HIDDEN PMTopLevelManager {
130 public:
131
132   virtual unsigned getNumContainedManagers() {
133     return PassManagers.size();
134   }
135
136   /// Schedule pass P for execution. Make sure that passes required by
137   /// P are run before P is run. Update analysis info maintained by
138   /// the manager. Remove dead passes. This is a recursive function.
139   void schedulePass(Pass *P);
140
141   /// This is implemented by top level pass manager and used by 
142   /// schedulePass() to add analysis info passes that are not available.
143   virtual void addTopLevelPass(Pass  *P) = 0;
144
145   /// Set pass P as the last user of the given analysis passes.
146   void setLastUser(std::vector<Pass *> &AnalysisPasses, Pass *P);
147
148   /// Collect passes whose last user is P
149   void collectLastUses(std::vector<Pass *> &LastUses, Pass *P);
150
151   /// Find the pass that implements Analysis AID. Search immutable
152   /// passes and all pass managers. If desired pass is not found
153   /// then return NULL.
154   Pass *findAnalysisPass(AnalysisID AID);
155
156   virtual ~PMTopLevelManager() {
157     for (std::vector<Pass *>::iterator I = PassManagers.begin(),
158            E = PassManagers.end(); I != E; ++I)
159       delete *I;
160
161     for (std::vector<ImmutablePass *>::iterator
162            I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
163       delete *I;
164
165     PassManagers.clear();
166   }
167
168   /// Add immutable pass and initialize it.
169   inline void addImmutablePass(ImmutablePass *P) {
170     P->initializePass();
171     ImmutablePasses.push_back(P);
172   }
173
174   inline std::vector<ImmutablePass *>& getImmutablePasses() {
175     return ImmutablePasses;
176   }
177
178   void addPassManager(Pass *Manager) {
179     PassManagers.push_back(Manager);
180   }
181
182   // Add Manager into the list of managers that are not directly
183   // maintained by this top level pass manager
184   inline void addIndirectPassManager(PMDataManager *Manager) {
185     IndirectPassManagers.push_back(Manager);
186   }
187
188   // Print passes managed by this top level manager.
189   void dumpPasses() const;
190   void dumpArguments() const;
191
192 protected:
193   
194   /// Collection of pass managers
195   std::vector<Pass *> PassManagers;
196
197 private:
198
199   /// Collection of pass managers that are not directly maintained
200   /// by this pass manager
201   std::vector<PMDataManager *> IndirectPassManagers;
202
203   // Map to keep track of last user of the analysis pass.
204   // LastUser->second is the last user of Lastuser->first.
205   std::map<Pass *, Pass *> LastUser;
206
207   /// Immutable passes are managed by top level manager.
208   std::vector<ImmutablePass *> ImmutablePasses;
209 };
210
211 } // End of anon namespace
212   
213 //===----------------------------------------------------------------------===//
214 // PMDataManager
215
216 namespace llvm {
217 /// PMDataManager provides the common place to manage the analysis data
218 /// used by pass managers.
219 class PMDataManager {
220 public:
221   PMDataManager(int Depth) : TPM(NULL), Depth(Depth) {
222     initializeAnalysisInfo();
223   }
224
225   virtual ~PMDataManager() {
226
227     for (std::vector<Pass *>::iterator I = PassVector.begin(),
228            E = PassVector.end(); I != E; ++I)
229       delete *I;
230
231     PassVector.clear();
232   }
233
234   /// Return true IFF pass P's required analysis set does not required new
235   /// manager.
236   bool manageablePass(Pass *P);
237
238   /// Augment AvailableAnalysis by adding analysis made available by pass P.
239   void recordAvailableAnalysis(Pass *P);
240
241   /// Remove Analysis that is not preserved by the pass
242   void removeNotPreservedAnalysis(Pass *P);
243   
244   /// Remove dead passes
245   void removeDeadPasses(Pass *P, std::string &Msg);
246
247   /// Add pass P into the PassVector. Update 
248   /// AvailableAnalysis appropriately if ProcessAnalysis is true.
249   void addPassToManager(Pass *P, bool ProcessAnalysis = true);
250
251   /// Initialize available analysis information.
252   void initializeAnalysisInfo() { 
253     TransferLastUses.clear();
254     AvailableAnalysis.clear();
255   }
256
257   /// Populate RequiredPasses with the analysis pass that are required by
258   /// pass P.
259   void collectRequiredAnalysisPasses(std::vector<Pass *> &RequiredPasses,
260                                      Pass *P);
261
262   /// All Required analyses should be available to the pass as it runs!  Here
263   /// we fill in the AnalysisImpls member of the pass so that it can
264   /// successfully use the getAnalysis() method to retrieve the
265   /// implementations it needs.
266   void initializeAnalysisImpl(Pass *P);
267
268   /// Find the pass that implements Analysis AID. If desired pass is not found
269   /// then return NULL.
270   Pass *findAnalysisPass(AnalysisID AID, bool Direction);
271
272   // Access toplevel manager
273   PMTopLevelManager *getTopLevelManager() { return TPM; }
274   void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
275
276   unsigned getDepth() const { return Depth; }
277
278   // Print routines used by debug-pass
279   void dumpLastUses(Pass *P, unsigned Offset) const;
280   void dumpPassArguments() const;
281   void dumpPassInfo(Pass *P,  std::string &Msg1, std::string &Msg2) const;
282   void dumpAnalysisSetInfo(const char *Msg, Pass *P,
283                            const std::vector<AnalysisID> &Set) const;
284
285   std::vector<Pass *>& getTransferredLastUses() {
286     return TransferLastUses;
287   }
288
289   virtual unsigned getNumContainedPasses() { 
290     return PassVector.size();
291   }
292
293 protected:
294
295   // If a FunctionPass F is the last user of ModulePass info M
296   // then the F's manager, not F, records itself as a last user of M.
297   // Current pass manage is requesting parent manager to record parent
298   // manager as the last user of these TrransferLastUses passes.
299   std::vector<Pass *> TransferLastUses;
300
301   // Top level manager.
302   PMTopLevelManager *TPM;
303
304   // Collection of pass that are managed by this manager
305   std::vector<Pass *> PassVector;
306
307 private:
308   // Set of available Analysis. This information is used while scheduling 
309   // pass. If a pass requires an analysis which is not not available then 
310   // equired analysis pass is scheduled to run before the pass itself is 
311   // scheduled to run.
312   std::map<AnalysisID, Pass*> AvailableAnalysis;
313
314   unsigned Depth;
315 };
316
317 //===----------------------------------------------------------------------===//
318 // BBPassManager
319 //
320 /// BBPassManager manages BasicBlockPass. It batches all the
321 /// pass together and sequence them to process one basic block before
322 /// processing next basic block.
323 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager, 
324                                         public FunctionPass {
325
326 public:
327   BBPassManager(int Depth) : PMDataManager(Depth) { }
328
329   /// Add a pass into a passmanager queue. 
330   bool addPass(Pass *p);
331   
332   /// Execute all of the passes scheduled for execution.  Keep track of
333   /// whether any of the passes modifies the function, and if so, return true.
334   bool runOnFunction(Function &F);
335
336   /// Pass Manager itself does not invalidate any analysis info.
337   void getAnalysisUsage(AnalysisUsage &Info) const {
338     Info.setPreservesAll();
339   }
340
341   bool doInitialization(Module &M);
342   bool doInitialization(Function &F);
343   bool doFinalization(Module &M);
344   bool doFinalization(Function &F);
345
346   // Print passes managed by this manager
347   void dumpPassStructure(unsigned Offset) {
348     llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
349     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
350       BasicBlockPass *BP = getContainedPass(Index);
351       BP->dumpPassStructure(Offset + 1);
352       dumpLastUses(BP, Offset+1);
353     }
354   }
355
356   BasicBlockPass *getContainedPass(unsigned N) {
357     assert ( N < PassVector.size() && "Pass number out of range!");
358     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
359     return BP;
360   }
361 };
362
363 //===----------------------------------------------------------------------===//
364 // FPPassManager
365 //
366 /// FPPassManager manages BBPassManagers and FunctionPasses.
367 /// It batches all function passes and basic block pass managers together and 
368 /// sequence them to process one function at a time before processing next 
369 /// function.
370
371 class FPPassManager : public ModulePass, public PMDataManager {
372  
373 public:
374   FPPassManager(int Depth) : PMDataManager(Depth) { 
375     activeBBPassManager = NULL; 
376   }
377   
378   /// Add a pass into a passmanager queue. 
379   bool addPass(Pass *p);
380   
381   /// run - Execute all of the passes scheduled for execution.  Keep track of
382   /// whether any of the passes modifies the module, and if so, return true.
383   bool runOnFunction(Function &F);
384   bool runOnModule(Module &M);
385
386   /// doInitialization - Run all of the initializers for the function passes.
387   ///
388   bool doInitialization(Module &M);
389   
390   /// doFinalization - Run all of the initializers for the function passes.
391   ///
392   bool doFinalization(Module &M);
393
394   /// Pass Manager itself does not invalidate any analysis info.
395   void getAnalysisUsage(AnalysisUsage &Info) const {
396     Info.setPreservesAll();
397   }
398
399   // Print passes managed by this manager
400   void dumpPassStructure(unsigned Offset) {
401     llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
402     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
403       FunctionPass *FP = getContainedPass(Index);
404       FP->dumpPassStructure(Offset + 1);
405       dumpLastUses(FP, Offset+1);
406     }
407   }
408
409   FunctionPass *getContainedPass(unsigned N) {
410     assert ( N < PassVector.size() && "Pass number out of range!");
411     FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
412     return FP;
413   }
414
415 private:
416   // Active Pass Manager
417   BBPassManager *activeBBPassManager;
418 };
419
420 //===----------------------------------------------------------------------===//
421 // FunctionPassManagerImpl
422 //
423 /// FunctionPassManagerImpl manages FPPassManagers
424 class FunctionPassManagerImpl : public Pass,
425                                     public PMDataManager,
426                                     public PMTopLevelManager {
427
428 public:
429
430   FunctionPassManagerImpl(int Depth) : PMDataManager(Depth) {
431     activeManager = NULL;
432   }
433
434   /// add - Add a pass to the queue of passes to run.  This passes ownership of
435   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
436   /// will be destroyed as well, so there is no need to delete the pass.  This
437   /// implies that all passes MUST be allocated with 'new'.
438   void add(Pass *P) {
439     schedulePass(P);
440   }
441  
442   /// run - Execute all of the passes scheduled for execution.  Keep track of
443   /// whether any of the passes modifies the module, and if so, return true.
444   bool run(Function &F);
445
446   /// doInitialization - Run all of the initializers for the function passes.
447   ///
448   bool doInitialization(Module &M);
449   
450   /// doFinalization - Run all of the initializers for the function passes.
451   ///
452   bool doFinalization(Module &M);
453
454   /// Pass Manager itself does not invalidate any analysis info.
455   void getAnalysisUsage(AnalysisUsage &Info) const {
456     Info.setPreservesAll();
457   }
458
459   inline void addTopLevelPass(Pass *P) {
460
461     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
462       
463       // P is a immutable pass and it will be managed by this
464       // top level manager. Set up analysis resolver to connect them.
465       AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
466       P->setResolver(AR);
467       initializeAnalysisImpl(P);
468       addImmutablePass(IP);
469       recordAvailableAnalysis(IP);
470     }
471     else 
472       addPass(P);
473   }
474
475   FPPassManager *getContainedManager(unsigned N) {
476     assert ( N < PassManagers.size() && "Pass number out of range!");
477     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
478     return FP;
479   }
480
481   /// Add a pass into a passmanager queue.
482   bool addPass(Pass *p);
483
484 private:
485
486   // Active Pass Manager
487   FPPassManager *activeManager;
488 };
489
490 //===----------------------------------------------------------------------===//
491 // MPPassManager
492 //
493 /// MPPassManager manages ModulePasses and function pass managers.
494 /// It batches all Module passes  passes and function pass managers together and
495 /// sequence them to process one module.
496 class MPPassManager : public Pass, public PMDataManager {
497  
498 public:
499   MPPassManager(int Depth) : PMDataManager(Depth) { 
500     activeFunctionPassManager = NULL; 
501   }
502   
503   /// Add a pass into a passmanager queue. 
504   bool addPass(Pass *p);
505   
506   /// run - Execute all of the passes scheduled for execution.  Keep track of
507   /// whether any of the passes modifies the module, and if so, return true.
508   bool runOnModule(Module &M);
509
510   /// Pass Manager itself does not invalidate any analysis info.
511   void getAnalysisUsage(AnalysisUsage &Info) const {
512     Info.setPreservesAll();
513   }
514
515   // Print passes managed by this manager
516   void dumpPassStructure(unsigned Offset) {
517     llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
518     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
519       ModulePass *MP = getContainedPass(Index);
520       MP->dumpPassStructure(Offset + 1);
521       dumpLastUses(MP, Offset+1);
522     }
523   }
524
525   ModulePass *getContainedPass(unsigned N) {
526     assert ( N < PassVector.size() && "Pass number out of range!");
527     ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
528     return MP;
529   }
530
531 private:
532   // Active Pass Manager
533   FPPassManager *activeFunctionPassManager;
534 };
535
536 //===----------------------------------------------------------------------===//
537 // PassManagerImpl
538 //
539 /// PassManagerImpl manages MPPassManagers
540 class PassManagerImpl : public Pass,
541                             public PMDataManager,
542                             public PMTopLevelManager {
543
544 public:
545
546   PassManagerImpl(int Depth) : PMDataManager(Depth) {
547     activeManager = NULL;
548   }
549
550   /// add - Add a pass to the queue of passes to run.  This passes ownership of
551   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
552   /// will be destroyed as well, so there is no need to delete the pass.  This
553   /// implies that all passes MUST be allocated with 'new'.
554   void add(Pass *P) {
555     schedulePass(P);
556   }
557  
558   /// run - Execute all of the passes scheduled for execution.  Keep track of
559   /// whether any of the passes modifies the module, and if so, return true.
560   bool run(Module &M);
561
562   /// Pass Manager itself does not invalidate any analysis info.
563   void getAnalysisUsage(AnalysisUsage &Info) const {
564     Info.setPreservesAll();
565   }
566
567   inline void addTopLevelPass(Pass *P) {
568
569     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
570       
571       // P is a immutable pass and it will be managed by this
572       // top level manager. Set up analysis resolver to connect them.
573       AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
574       P->setResolver(AR);
575       initializeAnalysisImpl(P);
576       addImmutablePass(IP);
577       recordAvailableAnalysis(IP);
578     }
579     else 
580       addPass(P);
581   }
582
583   MPPassManager *getContainedManager(unsigned N) {
584     assert ( N < PassManagers.size() && "Pass number out of range!");
585     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
586     return MP;
587   }
588
589 private:
590
591   /// Add a pass into a passmanager queue.
592   bool addPass(Pass *p);
593
594   // Active Pass Manager
595   MPPassManager *activeManager;
596 };
597
598 } // End of llvm namespace
599
600 namespace {
601
602 //===----------------------------------------------------------------------===//
603 // TimingInfo Class - This class is used to calculate information about the
604 // amount of time each pass takes to execute.  This only happens when
605 // -time-passes is enabled on the command line.
606 //
607
608 class VISIBILITY_HIDDEN TimingInfo {
609   std::map<Pass*, Timer> TimingData;
610   TimerGroup TG;
611
612 public:
613   // Use 'create' member to get this.
614   TimingInfo() : TG("... Pass execution timing report ...") {}
615   
616   // TimingDtor - Print out information about timing information
617   ~TimingInfo() {
618     // Delete all of the timers...
619     TimingData.clear();
620     // TimerGroup is deleted next, printing the report.
621   }
622
623   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
624   // to a non null value (if the -time-passes option is enabled) or it leaves it
625   // null.  It may be called multiple times.
626   static void createTheTimeInfo();
627
628   void passStarted(Pass *P) {
629
630     if (dynamic_cast<PMDataManager *>(P)) 
631       return;
632
633     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
634     if (I == TimingData.end())
635       I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
636     I->second.startTimer();
637   }
638   void passEnded(Pass *P) {
639
640     if (dynamic_cast<PMDataManager *>(P)) 
641       return;
642
643     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
644     assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
645     I->second.stopTimer();
646   }
647 };
648
649 static TimingInfo *TheTimeInfo;
650
651 } // End of anon namespace
652
653 //===----------------------------------------------------------------------===//
654 // PMTopLevelManager implementation
655
656 /// Set pass P as the last user of the given analysis passes.
657 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses, 
658                                     Pass *P) {
659
660   for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
661          E = AnalysisPasses.end(); I != E; ++I) {
662     Pass *AP = *I;
663     LastUser[AP] = P;
664     // If AP is the last user of other passes then make P last user of
665     // such passes.
666     for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
667            LUE = LastUser.end(); LUI != LUE; ++LUI) {
668       if (LUI->second == AP)
669         LastUser[LUI->first] = P;
670     }
671   }
672 }
673
674 /// Collect passes whose last user is P
675 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
676                                             Pass *P) {
677    for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
678           LUE = LastUser.end(); LUI != LUE; ++LUI)
679       if (LUI->second == P)
680         LastUses.push_back(LUI->first);
681 }
682
683 /// Schedule pass P for execution. Make sure that passes required by
684 /// P are run before P is run. Update analysis info maintained by
685 /// the manager. Remove dead passes. This is a recursive function.
686 void PMTopLevelManager::schedulePass(Pass *P) {
687
688   // TODO : Allocate function manager for this pass, other wise required set
689   // may be inserted into previous function manager
690
691   AnalysisUsage AnUsage;
692   P->getAnalysisUsage(AnUsage);
693   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
694   for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
695          E = RequiredSet.end(); I != E; ++I) {
696
697     Pass *AnalysisPass = findAnalysisPass(*I);
698     if (!AnalysisPass) {
699       // Schedule this analysis run first.
700       AnalysisPass = (*I)->createPass();
701       schedulePass(AnalysisPass);
702     }
703   }
704
705   // Now all required passes are available.
706   addTopLevelPass(P);
707 }
708
709 /// Find the pass that implements Analysis AID. Search immutable
710 /// passes and all pass managers. If desired pass is not found
711 /// then return NULL.
712 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
713
714   Pass *P = NULL;
715   // Check pass managers
716   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
717          E = PassManagers.end(); P == NULL && I != E; ++I) {
718     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
719     assert(PMD && "This is not a PassManager");
720     P = PMD->findAnalysisPass(AID, false);
721   }
722
723   // Check other pass managers
724   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
725          E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
726     P = (*I)->findAnalysisPass(AID, false);
727
728   for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
729          E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
730     const PassInfo *PI = (*I)->getPassInfo();
731     if (PI == AID)
732       P = *I;
733
734     // If Pass not found then check the interfaces implemented by Immutable Pass
735     if (!P) {
736       const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
737       if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
738         P = *I;
739     }
740   }
741
742   return P;
743 }
744
745 // Print passes managed by this top level manager.
746 void PMTopLevelManager::dumpPasses() const {
747
748   if (PassDebugging_New < Structure)
749     return;
750
751   // Print out the immutable passes
752   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
753     ImmutablePasses[i]->dumpPassStructure(0);
754   }
755   
756   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
757          E = PassManagers.end(); I != E; ++I)
758     (*I)->dumpPassStructure(1);
759 }
760
761 void PMTopLevelManager::dumpArguments() const {
762
763   if (PassDebugging_New < Arguments)
764     return;
765
766   cerr << "Pass Arguments: ";
767   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
768          E = PassManagers.end(); I != E; ++I) {
769     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
770     assert(PMD && "This is not a PassManager");
771     PMD->dumpPassArguments();
772   }
773   cerr << "\n";
774 }
775
776 //===----------------------------------------------------------------------===//
777 // PMDataManager implementation
778
779 /// Return true IFF pass P's required analysis set does not required new
780 /// manager.
781 bool PMDataManager::manageablePass(Pass *P) {
782
783   // TODO 
784   // If this pass is not preserving information that is required by a
785   // pass maintained by higher level pass manager then do not insert
786   // this pass into current manager. Use new manager. For example,
787   // For example, If FunctionPass F is not preserving ModulePass Info M1
788   // that is used by another ModulePass M2 then do not insert F in
789   // current function pass manager.
790   return true;
791 }
792
793 /// Augement AvailableAnalysis by adding analysis made available by pass P.
794 void PMDataManager::recordAvailableAnalysis(Pass *P) {
795                                                 
796   if (const PassInfo *PI = P->getPassInfo()) {
797     AvailableAnalysis[PI] = P;
798
799     //This pass is the current implementation of all of the interfaces it
800     //implements as well.
801     const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
802     for (unsigned i = 0, e = II.size(); i != e; ++i)
803       AvailableAnalysis[II[i]] = P;
804   }
805 }
806
807 /// Remove Analyss not preserved by Pass P
808 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
809   AnalysisUsage AnUsage;
810   P->getAnalysisUsage(AnUsage);
811
812   if (AnUsage.getPreservesAll())
813     return;
814
815   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
816   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
817          E = AvailableAnalysis.end(); I != E; ) {
818     std::map<AnalysisID, Pass*>::iterator Info = I++;
819     if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
820         PreservedSet.end()) {
821       // Remove this analysis
822       if (!dynamic_cast<ImmutablePass*>(Info->second))
823         AvailableAnalysis.erase(Info);
824     }
825   }
826 }
827
828 /// Remove analysis passes that are not used any longer
829 void PMDataManager::removeDeadPasses(Pass *P, std::string &Msg) {
830
831   std::vector<Pass *> DeadPasses;
832   TPM->collectLastUses(DeadPasses, P);
833
834   for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
835          E = DeadPasses.end(); I != E; ++I) {
836
837     std::string Msg1 = "  Freeing Pass '";
838     dumpPassInfo(*I, Msg1, Msg);
839
840     if (TheTimeInfo) TheTimeInfo->passStarted(P);
841     (*I)->releaseMemory();
842     if (TheTimeInfo) TheTimeInfo->passEnded(P);
843
844     std::map<AnalysisID, Pass*>::iterator Pos = 
845       AvailableAnalysis.find((*I)->getPassInfo());
846     
847     // It is possible that pass is already removed from the AvailableAnalysis
848     if (Pos != AvailableAnalysis.end())
849       AvailableAnalysis.erase(Pos);
850   }
851 }
852
853 /// Add pass P into the PassVector. Update 
854 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
855 void PMDataManager::addPassToManager(Pass *P, 
856                                      bool ProcessAnalysis) {
857
858   // This manager is going to manage pass P. Set up analysis resolver
859   // to connect them.
860   AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
861   P->setResolver(AR);
862
863   if (ProcessAnalysis) {
864
865     // At the moment, this pass is the last user of all required passes.
866     std::vector<Pass *> LastUses;
867     std::vector<Pass *> RequiredPasses;
868     unsigned PDepth = this->getDepth();
869
870     collectRequiredAnalysisPasses(RequiredPasses, P);
871     for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
872            E = RequiredPasses.end(); I != E; ++I) {
873       Pass *PRequired = *I;
874       unsigned RDepth = 0;
875
876       PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
877       RDepth = DM.getDepth();
878
879       if (PDepth == RDepth)
880         LastUses.push_back(PRequired);
881       else if (PDepth >  RDepth) {
882         // Let the parent claim responsibility of last use
883         TransferLastUses.push_back(PRequired);
884       } else {
885         // Note : This feature is not yet implemented
886         assert (0 && 
887                 "Unable to handle Pass that requires lower level Analysis pass");
888       }
889     }
890
891     LastUses.push_back(P);
892     TPM->setLastUser(LastUses, P);
893
894     // Take a note of analysis required and made available by this pass.
895     // Remove the analysis not preserved by this pass
896     removeNotPreservedAnalysis(P);
897     recordAvailableAnalysis(P);
898   }
899
900   // Add pass
901   PassVector.push_back(P);
902 }
903
904 /// Populate RequiredPasses with the analysis pass that are required by
905 /// pass P.
906 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
907                                                   Pass *P) {
908   AnalysisUsage AnUsage;
909   P->getAnalysisUsage(AnUsage);
910   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
911   for (std::vector<AnalysisID>::const_iterator 
912          I = RequiredSet.begin(), E = RequiredSet.end();
913        I != E; ++I) {
914     Pass *AnalysisPass = findAnalysisPass(*I, true);
915     assert (AnalysisPass && "Analysis pass is not available");
916     RP.push_back(AnalysisPass);
917   }
918
919   const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
920   for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
921          E = IDs.end(); I != E; ++I) {
922     Pass *AnalysisPass = findAnalysisPass(*I, true);
923     assert (AnalysisPass && "Analysis pass is not available");
924     RP.push_back(AnalysisPass);
925   }
926 }
927
928 // All Required analyses should be available to the pass as it runs!  Here
929 // we fill in the AnalysisImpls member of the pass so that it can
930 // successfully use the getAnalysis() method to retrieve the
931 // implementations it needs.
932 //
933 void PMDataManager::initializeAnalysisImpl(Pass *P) {
934   AnalysisUsage AnUsage;
935   P->getAnalysisUsage(AnUsage);
936  
937   for (std::vector<const PassInfo *>::const_iterator
938          I = AnUsage.getRequiredSet().begin(),
939          E = AnUsage.getRequiredSet().end(); I != E; ++I) {
940     Pass *Impl = findAnalysisPass(*I, true);
941     if (Impl == 0)
942       assert(0 && "Analysis used but not available!");
943     AnalysisResolver_New *AR = P->getResolver();
944     AR->addAnalysisImplsPair(*I, Impl);
945   }
946 }
947
948 /// Find the pass that implements Analysis AID. If desired pass is not found
949 /// then return NULL.
950 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
951
952   // Check if AvailableAnalysis map has one entry.
953   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
954
955   if (I != AvailableAnalysis.end())
956     return I->second;
957
958   // Search Parents through TopLevelManager
959   if (SearchParent)
960     return TPM->findAnalysisPass(AID);
961   
962   return NULL;
963 }
964
965 // Print list of passes that are last used by P.
966 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
967
968   std::vector<Pass *> LUses;
969   
970   assert (TPM && "Top Level Manager is missing");
971   TPM->collectLastUses(LUses, P);
972   
973   for (std::vector<Pass *>::iterator I = LUses.begin(),
974          E = LUses.end(); I != E; ++I) {
975     llvm::cerr << "--" << std::string(Offset*2, ' ');
976     (*I)->dumpPassStructure(0);
977   }
978 }
979
980 void PMDataManager::dumpPassArguments() const {
981   for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
982         E = PassVector.end(); I != E; ++I) {
983     if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
984       PMD->dumpPassArguments();
985     else
986       if (const PassInfo *PI = (*I)->getPassInfo())
987         if (!PI->isAnalysisGroup())
988           cerr << " -" << PI->getPassArgument();
989   }
990 }
991
992 void PMDataManager:: dumpPassInfo(Pass *P,  std::string &Msg1, 
993                                   std::string &Msg2) const {
994   if (PassDebugging_New < Executions)
995     return;
996   cerr << (void*)this << std::string(getDepth()*2+1, ' ');
997   cerr << Msg1;
998   cerr << P->getPassName();
999   cerr << Msg2;
1000 }
1001
1002 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
1003                                         const std::vector<AnalysisID> &Set) 
1004   const {
1005   if (PassDebugging_New >= Details && !Set.empty()) {
1006     cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1007       for (unsigned i = 0; i != Set.size(); ++i) {
1008         if (i) cerr << ",";
1009         cerr << " " << Set[i]->getPassName();
1010       }
1011       cerr << "\n";
1012   }
1013 }
1014
1015 //===----------------------------------------------------------------------===//
1016 // NOTE: Is this the right place to define this method ?
1017 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
1018 Pass *AnalysisResolver_New::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
1019   return PM.findAnalysisPass(ID, dir);
1020 }
1021
1022 //===----------------------------------------------------------------------===//
1023 // BBPassManager implementation
1024
1025 /// Add pass P into PassVector and return true. If this pass is not
1026 /// manageable by this manager then return false.
1027 bool
1028 BBPassManager::addPass(Pass *P) {
1029
1030   BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
1031   if (!BP)
1032     return false;
1033
1034   // If this pass does not preserve analysis that is used by other passes
1035   // managed by this manager than it is not a suitable pass for this manager.
1036   if (!manageablePass(P))
1037     return false;
1038
1039   addPassToManager(BP);
1040
1041   return true;
1042 }
1043
1044 /// Execute all of the passes scheduled for execution by invoking 
1045 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
1046 /// the function, and if so, return true.
1047 bool
1048 BBPassManager::runOnFunction(Function &F) {
1049
1050   if (F.isExternal())
1051     return false;
1052
1053   bool Changed = doInitialization(F);
1054   initializeAnalysisInfo();
1055
1056   std::string Msg1 = "Executing Pass '";
1057   std::string Msg3 = "' Made Modification '";
1058
1059   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1060     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1061       BasicBlockPass *BP = getContainedPass(Index);
1062       AnalysisUsage AnUsage;
1063       BP->getAnalysisUsage(AnUsage);
1064
1065       std::string Msg2 = "' on BasicBlock '" + (*I).getName() + "'...\n";
1066       dumpPassInfo(BP, Msg1, Msg2);
1067       dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
1068
1069       initializeAnalysisImpl(BP);
1070
1071       if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1072       Changed |= BP->runOnBasicBlock(*I);
1073       if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1074
1075       if (Changed)
1076         dumpPassInfo(BP, Msg3, Msg2);
1077       dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
1078
1079       removeNotPreservedAnalysis(BP);
1080       recordAvailableAnalysis(BP);
1081       removeDeadPasses(BP, Msg2);
1082     }
1083   return Changed |= doFinalization(F);
1084 }
1085
1086 // Implement doInitialization and doFinalization
1087 inline bool BBPassManager::doInitialization(Module &M) {
1088   bool Changed = false;
1089
1090   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1091     BasicBlockPass *BP = getContainedPass(Index);
1092     Changed |= BP->doInitialization(M);
1093   }
1094
1095   return Changed;
1096 }
1097
1098 inline bool BBPassManager::doFinalization(Module &M) {
1099   bool Changed = false;
1100
1101   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1102     BasicBlockPass *BP = getContainedPass(Index);
1103     Changed |= BP->doFinalization(M);
1104   }
1105
1106   return Changed;
1107 }
1108
1109 inline bool BBPassManager::doInitialization(Function &F) {
1110   bool Changed = false;
1111
1112   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1113     BasicBlockPass *BP = getContainedPass(Index);
1114     Changed |= BP->doInitialization(F);
1115   }
1116
1117   return Changed;
1118 }
1119
1120 inline bool BBPassManager::doFinalization(Function &F) {
1121   bool Changed = false;
1122
1123   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1124     BasicBlockPass *BP = getContainedPass(Index);
1125     Changed |= BP->doFinalization(F);
1126   }
1127
1128   return Changed;
1129 }
1130
1131
1132 //===----------------------------------------------------------------------===//
1133 // FunctionPassManager implementation
1134
1135 /// Create new Function pass manager
1136 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1137   FPM = new FunctionPassManagerImpl(0);
1138   // FPM is the top level manager.
1139   FPM->setTopLevelManager(FPM);
1140
1141   PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
1142   AnalysisResolver_New *AR = new AnalysisResolver_New(*PMD);
1143   FPM->setResolver(AR);
1144   
1145   MP = P;
1146 }
1147
1148 FunctionPassManager::~FunctionPassManager() {
1149   delete FPM;
1150 }
1151
1152 /// add - Add a pass to the queue of passes to run.  This passes
1153 /// ownership of the Pass to the PassManager.  When the
1154 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1155 /// there is no need to delete the pass. (TODO delete passes.)
1156 /// This implies that all passes MUST be allocated with 'new'.
1157 void FunctionPassManager::add(Pass *P) { 
1158   FPM->add(P);
1159 }
1160
1161 /// run - Execute all of the passes scheduled for execution.  Keep
1162 /// track of whether any of the passes modifies the function, and if
1163 /// so, return true.
1164 ///
1165 bool FunctionPassManager::run(Function &F) {
1166   std::string errstr;
1167   if (MP->materializeFunction(&F, &errstr)) {
1168     cerr << "Error reading bytecode file: " << errstr << "\n";
1169     abort();
1170   }
1171   return FPM->run(F);
1172 }
1173
1174
1175 /// doInitialization - Run all of the initializers for the function passes.
1176 ///
1177 bool FunctionPassManager::doInitialization() {
1178   return FPM->doInitialization(*MP->getModule());
1179 }
1180
1181 /// doFinalization - Run all of the initializers for the function passes.
1182 ///
1183 bool FunctionPassManager::doFinalization() {
1184   return FPM->doFinalization(*MP->getModule());
1185 }
1186
1187 //===----------------------------------------------------------------------===//
1188 // FunctionPassManagerImpl implementation
1189 //
1190 /// Add P into active pass manager or use new module pass manager to
1191 /// manage it.
1192 bool FunctionPassManagerImpl::addPass(Pass *P) {
1193
1194   if (!activeManager || !activeManager->addPass(P)) {
1195     activeManager = new FPPassManager(getDepth() + 1);
1196     // Inherit top level manager
1197     activeManager->setTopLevelManager(this->getTopLevelManager());
1198
1199     // This top level manager is going to manage activeManager. 
1200     // Set up analysis resolver to connect them.
1201     AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
1202     activeManager->setResolver(AR);
1203
1204     addPassManager(activeManager);
1205     return activeManager->addPass(P);
1206   }
1207   return true;
1208 }
1209
1210 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1211   bool Changed = false;
1212
1213   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1214     FPPassManager *FP = getContainedManager(Index);
1215     Changed |= FP->doInitialization(M);
1216   }
1217
1218   return Changed;
1219 }
1220
1221 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1222   bool Changed = false;
1223
1224   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1225     FPPassManager *FP = getContainedManager(Index);
1226     Changed |= FP->doFinalization(M);
1227   }
1228
1229   return Changed;
1230 }
1231
1232 // Execute all the passes managed by this top level manager.
1233 // Return true if any function is modified by a pass.
1234 bool FunctionPassManagerImpl::run(Function &F) {
1235
1236   bool Changed = false;
1237
1238   TimingInfo::createTheTimeInfo();
1239
1240   dumpArguments();
1241   dumpPasses();
1242
1243   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1244     FPPassManager *FP = getContainedManager(Index);
1245     Changed |= FP->runOnFunction(F);
1246   }
1247   return Changed;
1248 }
1249
1250 //===----------------------------------------------------------------------===//
1251 // FPPassManager implementation
1252
1253 /// Add pass P into the pass manager queue. If P is a BasicBlockPass then
1254 /// either use it into active basic block pass manager or create new basic
1255 /// block pass manager to handle pass P.
1256 bool
1257 FPPassManager::addPass(Pass *P) {
1258
1259   // If P is a BasicBlockPass then use BBPassManager.
1260   if (BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P)) {
1261
1262     if (!activeBBPassManager || !activeBBPassManager->addPass(BP)) {
1263
1264       // If active manager exists then clear its analysis info.
1265       if (activeBBPassManager)
1266         activeBBPassManager->initializeAnalysisInfo();
1267
1268       // Create and add new manager
1269       activeBBPassManager = new BBPassManager(getDepth() + 1);
1270       // Inherit top level manager
1271       activeBBPassManager->setTopLevelManager(this->getTopLevelManager());
1272
1273       // Add new manager into current manager's list.
1274       addPassToManager(activeBBPassManager, false);
1275
1276       // Add new manager into top level manager's indirect passes list
1277       PMDataManager *PMD = dynamic_cast<PMDataManager *>(activeBBPassManager);
1278       assert (PMD && "Manager is not Pass Manager");
1279       TPM->addIndirectPassManager(PMD);
1280
1281       // Add pass into new manager. This time it must succeed.
1282       if (!activeBBPassManager->addPass(BP))
1283         assert(0 && "Unable to add Pass");
1284
1285       // If activeBBPassManager transfered any Last Uses then handle them here.
1286       std::vector<Pass *> &TLU = activeBBPassManager->getTransferredLastUses();
1287       if (!TLU.empty())
1288         TPM->setLastUser(TLU, this);
1289
1290     }
1291
1292     return true;
1293   }
1294
1295   FunctionPass *FP = dynamic_cast<FunctionPass *>(P);
1296   if (!FP)
1297     return false;
1298
1299   // If this pass does not preserve analysis that is used by other passes
1300   // managed by this manager than it is not a suitable pass for this manager.
1301   if (!manageablePass(P))
1302     return false;
1303
1304   addPassToManager (FP);
1305
1306   // If active manager exists then clear its analysis info.
1307   if (activeBBPassManager) {
1308     activeBBPassManager->initializeAnalysisInfo();
1309     activeBBPassManager = NULL;
1310   }
1311
1312   return true;
1313 }
1314
1315 /// Execute all of the passes scheduled for execution by invoking 
1316 /// runOnFunction method.  Keep track of whether any of the passes modifies 
1317 /// the function, and if so, return true.
1318 bool FPPassManager::runOnFunction(Function &F) {
1319
1320   bool Changed = false;
1321
1322   if (F.isExternal())
1323     return false;
1324
1325   initializeAnalysisInfo();
1326
1327   std::string Msg1 = "Executing Pass '";
1328   std::string Msg3 = "' Made Modification '";
1329
1330   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1331     FunctionPass *FP = getContainedPass(Index);
1332
1333     AnalysisUsage AnUsage;
1334     FP->getAnalysisUsage(AnUsage);
1335
1336     std::string Msg2 = "' on Function '" + F.getName() + "'...\n";
1337     dumpPassInfo(FP, Msg1, Msg2);
1338     dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1339
1340     initializeAnalysisImpl(FP);
1341
1342     if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1343     Changed |= FP->runOnFunction(F);
1344     if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1345
1346     if (Changed)
1347       dumpPassInfo(FP, Msg3, Msg2);
1348     dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1349
1350     removeNotPreservedAnalysis(FP);
1351     recordAvailableAnalysis(FP);
1352     removeDeadPasses(FP, Msg2);
1353   }
1354   return Changed;
1355 }
1356
1357 bool FPPassManager::runOnModule(Module &M) {
1358
1359   bool Changed = doInitialization(M);
1360   initializeAnalysisInfo();
1361
1362   for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1363     this->runOnFunction(*I);
1364
1365   return Changed |= doFinalization(M);
1366 }
1367
1368 inline bool FPPassManager::doInitialization(Module &M) {
1369   bool Changed = false;
1370
1371   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1372     FunctionPass *FP = getContainedPass(Index);
1373     Changed |= FP->doInitialization(M);
1374   }
1375
1376   return Changed;
1377 }
1378
1379 inline bool FPPassManager::doFinalization(Module &M) {
1380   bool Changed = false;
1381
1382   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1383     FunctionPass *FP = getContainedPass(Index);
1384     Changed |= FP->doFinalization(M);
1385   }
1386
1387   return Changed;
1388 }
1389
1390 //===----------------------------------------------------------------------===//
1391 // MPPassManager implementation
1392
1393 /// Add P into pass vector if it is manageble. If P is a FunctionPass
1394 /// then use FPPassManager to manage it. Return false if P
1395 /// is not manageable by this manager.
1396 bool
1397 MPPassManager::addPass(Pass *P) {
1398
1399   // If P is FunctionPass then use function pass maanager.
1400   if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P)) {
1401
1402     if (!activeFunctionPassManager || !activeFunctionPassManager->addPass(P)) {
1403
1404       // If active manager exists then clear its analysis info.
1405       if (activeFunctionPassManager) 
1406         activeFunctionPassManager->initializeAnalysisInfo();
1407
1408       // Create and add new manager
1409       activeFunctionPassManager = 
1410         new FPPassManager(getDepth() + 1);
1411       
1412       // Add new manager into current manager's list
1413       addPassToManager(activeFunctionPassManager, false);
1414
1415       // Inherit top level manager
1416       activeFunctionPassManager->setTopLevelManager(this->getTopLevelManager());
1417
1418       // Add new manager into top level manager's indirect passes list
1419       PMDataManager *PMD =
1420         dynamic_cast<PMDataManager *>(activeFunctionPassManager);
1421       assert(PMD && "Manager is not Pass Manager");
1422       TPM->addIndirectPassManager(PMD);
1423       
1424       // Add pass into new manager. This time it must succeed.
1425       if (!activeFunctionPassManager->addPass(FP))
1426         assert(0 && "Unable to add pass");
1427
1428       // If activeFunctionPassManager transfered any Last Uses then 
1429       // handle them here.
1430       std::vector<Pass *> &TLU = 
1431         activeFunctionPassManager->getTransferredLastUses();
1432       if (!TLU.empty())
1433         TPM->setLastUser(TLU, this);
1434     }
1435
1436     return true;
1437   }
1438
1439   ModulePass *MP = dynamic_cast<ModulePass *>(P);
1440   if (!MP)
1441     return false;
1442
1443   // If this pass does not preserve analysis that is used by other passes
1444   // managed by this manager than it is not a suitable pass for this manager.
1445   if (!manageablePass(P))
1446     return false;
1447
1448   addPassToManager(MP);
1449   // If active manager exists then clear its analysis info.
1450   if (activeFunctionPassManager) {
1451     activeFunctionPassManager->initializeAnalysisInfo();
1452     activeFunctionPassManager = NULL;
1453   }
1454
1455   return true;
1456 }
1457
1458
1459 /// Execute all of the passes scheduled for execution by invoking 
1460 /// runOnModule method.  Keep track of whether any of the passes modifies 
1461 /// the module, and if so, return true.
1462 bool
1463 MPPassManager::runOnModule(Module &M) {
1464   bool Changed = false;
1465   initializeAnalysisInfo();
1466
1467   std::string Msg1 = "Executing Pass '";
1468   std::string Msg3 = "' Made Modification '";
1469
1470   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1471     ModulePass *MP = getContainedPass(Index);
1472
1473     AnalysisUsage AnUsage;
1474     MP->getAnalysisUsage(AnUsage);
1475
1476     std::string Msg2 = "' on Module '" + M.getModuleIdentifier() + "'...\n";
1477     dumpPassInfo(MP, Msg1, Msg2);
1478     dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1479
1480     initializeAnalysisImpl(MP);
1481
1482     if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1483     Changed |= MP->runOnModule(M);
1484     if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1485
1486     if (Changed)
1487       dumpPassInfo(MP, Msg3, Msg2);
1488     dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1489       
1490     removeNotPreservedAnalysis(MP);
1491     recordAvailableAnalysis(MP);
1492     removeDeadPasses(MP, Msg2);
1493   }
1494   return Changed;
1495 }
1496
1497 //===----------------------------------------------------------------------===//
1498 // PassManagerImpl implementation
1499 //
1500 /// Add P into active pass manager or use new module pass manager to
1501 /// manage it.
1502 bool PassManagerImpl::addPass(Pass *P) {
1503
1504   if (!activeManager || !activeManager->addPass(P)) {
1505     activeManager = new MPPassManager(getDepth() + 1);
1506     // Inherit top level manager
1507     activeManager->setTopLevelManager(this->getTopLevelManager());
1508
1509     // This top level manager is going to manage activeManager. 
1510     // Set up analysis resolver to connect them.
1511     AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
1512     activeManager->setResolver(AR);
1513
1514     addPassManager(activeManager);
1515     return activeManager->addPass(P);
1516   }
1517   return true;
1518 }
1519
1520 /// run - Execute all of the passes scheduled for execution.  Keep track of
1521 /// whether any of the passes modifies the module, and if so, return true.
1522 bool PassManagerImpl::run(Module &M) {
1523
1524   bool Changed = false;
1525
1526   TimingInfo::createTheTimeInfo();
1527
1528   dumpArguments();
1529   dumpPasses();
1530
1531   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1532     MPPassManager *MP = getContainedManager(Index);
1533     Changed |= MP->runOnModule(M);
1534   }
1535   return Changed;
1536 }
1537
1538 //===----------------------------------------------------------------------===//
1539 // PassManager implementation
1540
1541 /// Create new pass manager
1542 PassManager::PassManager() {
1543   PM = new PassManagerImpl(0);
1544   // PM is the top level manager
1545   PM->setTopLevelManager(PM);
1546 }
1547
1548 PassManager::~PassManager() {
1549   delete PM;
1550 }
1551
1552 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1553 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1554 /// will be destroyed as well, so there is no need to delete the pass.  This
1555 /// implies that all passes MUST be allocated with 'new'.
1556 void 
1557 PassManager::add(Pass *P) {
1558   PM->add(P);
1559 }
1560
1561 /// run - Execute all of the passes scheduled for execution.  Keep track of
1562 /// whether any of the passes modifies the module, and if so, return true.
1563 bool
1564 PassManager::run(Module &M) {
1565   return PM->run(M);
1566 }
1567
1568 //===----------------------------------------------------------------------===//
1569 // TimingInfo Class - This class is used to calculate information about the
1570 // amount of time each pass takes to execute.  This only happens with
1571 // -time-passes is enabled on the command line.
1572 //
1573 bool llvm::TimePassesIsEnabled = false;
1574 static cl::opt<bool,true>
1575 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1576             cl::desc("Time each pass, printing elapsed time for each on exit"));
1577
1578 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1579 // a non null value (if the -time-passes option is enabled) or it leaves it
1580 // null.  It may be called multiple times.
1581 void TimingInfo::createTheTimeInfo() {
1582   if (!TimePassesIsEnabled || TheTimeInfo) return;
1583
1584   // Constructed the first time this is called, iff -time-passes is enabled.
1585   // This guarantees that the object will be constructed before static globals,
1586   // thus it will be destroyed before them.
1587   static ManagedStatic<TimingInfo> TTI;
1588   TheTimeInfo = &*TTI;
1589 }
1590
1591 #endif