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