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