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