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