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