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