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