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