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