1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/PassManagers.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/DebugInfoProbe.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Timer.h"
23 #include "llvm/Module.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/PassNameParser.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/Mutex.h"
29 #include "llvm/ADT/StringMap.h"
34 // See PassManagers.h for Pass Manager infrastructure overview.
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.
45 // Different debug levels that can be enabled...
47 None, Arguments, Structure, Executions, Details
50 static cl::opt<enum PassDebugLevel>
51 PassDebugging("debug-pass", cl::Hidden,
52 cl::desc("Print PassManager debugging information"),
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"),
61 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
64 // Print IR out before/after specified passes.
66 PrintBefore("print-before",
67 llvm::cl::desc("Print IR before specified passes"),
71 PrintAfter("print-after",
72 llvm::cl::desc("Print IR after specified passes"),
76 PrintBeforeAll("print-before-all",
77 llvm::cl::desc("Print IR before each pass"),
80 PrintAfterAll("print-after-all",
81 llvm::cl::desc("Print IR after each pass"),
84 /// This is a helper to determine whether to print IR before or
87 static bool ShouldPrintBeforeOrAfterPass(const void *PassID,
88 PassOptionList &PassesToPrint) {
89 if (const llvm::PassInfo *PI =
90 PassRegistry::getPassRegistry()->getPassInfo(PassID)) {
91 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
92 const llvm::PassInfo *PassInf = PassesToPrint[i];
94 if (PassInf->getPassArgument() == PI->getPassArgument()) {
103 /// This is a utility to check whether a pass should have IR dumped
105 static bool ShouldPrintBeforePass(const void *PassID) {
106 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefore);
109 /// This is a utility to check whether a pass should have IR dumped
111 static bool ShouldPrintAfterPass(const void *PassID) {
112 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
115 } // End of llvm namespace
117 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
118 /// or higher is specified.
119 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
120 return PassDebugging >= Executions;
126 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
127 if (V == 0 && M == 0)
128 OS << "Releasing pass '";
130 OS << "Running pass '";
132 OS << P->getPassName() << "'";
135 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
144 if (isa<Function>(V))
146 else if (isa<BasicBlock>(V))
152 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
159 //===----------------------------------------------------------------------===//
162 /// BBPassManager manages BasicBlockPass. It batches all the
163 /// pass together and sequence them to process one basic block before
164 /// processing next basic block.
165 class BBPassManager : public PMDataManager, public FunctionPass {
169 explicit BBPassManager()
170 : PMDataManager(), FunctionPass(ID) {}
172 /// Execute all of the passes scheduled for execution. Keep track of
173 /// whether any of the passes modifies the function, and if so, return true.
174 bool runOnFunction(Function &F);
176 /// Pass Manager itself does not invalidate any analysis info.
177 void getAnalysisUsage(AnalysisUsage &Info) const {
178 Info.setPreservesAll();
181 bool doInitialization(Module &M);
182 bool doInitialization(Function &F);
183 bool doFinalization(Module &M);
184 bool doFinalization(Function &F);
186 virtual PMDataManager *getAsPMDataManager() { return this; }
187 virtual Pass *getAsPass() { return this; }
189 virtual const char *getPassName() const {
190 return "BasicBlock Pass Manager";
193 // Print passes managed by this manager
194 void dumpPassStructure(unsigned Offset) {
195 llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
196 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
197 BasicBlockPass *BP = getContainedPass(Index);
198 BP->dumpPassStructure(Offset + 1);
199 dumpLastUses(BP, Offset+1);
203 BasicBlockPass *getContainedPass(unsigned N) {
204 assert(N < PassVector.size() && "Pass number out of range!");
205 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
209 virtual PassManagerType getPassManagerType() const {
210 return PMT_BasicBlockPassManager;
214 char BBPassManager::ID = 0;
219 //===----------------------------------------------------------------------===//
220 // FunctionPassManagerImpl
222 /// FunctionPassManagerImpl manages FPPassManagers
223 class FunctionPassManagerImpl : public Pass,
224 public PMDataManager,
225 public PMTopLevelManager {
226 virtual void anchor();
231 explicit FunctionPassManagerImpl() :
232 Pass(PT_PassManager, ID), PMDataManager(),
233 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
235 /// add - Add a pass to the queue of passes to run. This passes ownership of
236 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
237 /// will be destroyed as well, so there is no need to delete the pass. This
238 /// implies that all passes MUST be allocated with 'new'.
243 /// createPrinterPass - Get a function printer pass.
244 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
245 return createPrintFunctionPass(Banner, &O);
248 // Prepare for running an on the fly pass, freeing memory if needed
249 // from a previous run.
250 void releaseMemoryOnTheFly();
252 /// run - Execute all of the passes scheduled for execution. Keep track of
253 /// whether any of the passes modifies the module, and if so, return true.
254 bool run(Function &F);
256 /// doInitialization - Run all of the initializers for the function passes.
258 bool doInitialization(Module &M);
260 /// doFinalization - Run all of the finalizers for the function passes.
262 bool doFinalization(Module &M);
265 virtual PMDataManager *getAsPMDataManager() { return this; }
266 virtual Pass *getAsPass() { return this; }
268 /// Pass Manager itself does not invalidate any analysis info.
269 void getAnalysisUsage(AnalysisUsage &Info) const {
270 Info.setPreservesAll();
273 void addTopLevelPass(Pass *P) {
274 if (ImmutablePass *IP = P->getAsImmutablePass()) {
275 // P is a immutable pass and it will be managed by this
276 // top level manager. Set up analysis resolver to connect them.
277 AnalysisResolver *AR = new AnalysisResolver(*this);
279 initializeAnalysisImpl(P);
280 addImmutablePass(IP);
281 recordAvailableAnalysis(IP);
283 P->assignPassManager(activeStack, PMT_FunctionPassManager);
288 FPPassManager *getContainedManager(unsigned N) {
289 assert(N < PassManagers.size() && "Pass number out of range!");
290 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
295 void FunctionPassManagerImpl::anchor() {}
297 char FunctionPassManagerImpl::ID = 0;
299 //===----------------------------------------------------------------------===//
302 /// MPPassManager manages ModulePasses and function pass managers.
303 /// It batches all Module passes and function pass managers together and
304 /// sequences them to process one module.
305 class MPPassManager : public Pass, public PMDataManager {
308 explicit MPPassManager() :
309 Pass(PT_PassManager, ID), PMDataManager() { }
311 // Delete on the fly managers.
312 virtual ~MPPassManager() {
313 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
314 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
316 FunctionPassManagerImpl *FPP = I->second;
321 /// createPrinterPass - Get a module printer pass.
322 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
323 return createPrintModulePass(&O, false, Banner);
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 runOnModule(Module &M);
330 /// Pass Manager itself does not invalidate any analysis info.
331 void getAnalysisUsage(AnalysisUsage &Info) const {
332 Info.setPreservesAll();
335 /// Add RequiredPass into list of lower level passes required by pass P.
336 /// RequiredPass is run on the fly by Pass Manager when P requests it
337 /// through getAnalysis interface.
338 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
340 /// Return function pass corresponding to PassInfo PI, that is
341 /// required by module pass MP. Instantiate analysis pass, by using
342 /// its runOnFunction() for function F.
343 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
345 virtual const char *getPassName() const {
346 return "Module Pass Manager";
349 virtual PMDataManager *getAsPMDataManager() { return this; }
350 virtual Pass *getAsPass() { return this; }
352 // Print passes managed by this manager
353 void dumpPassStructure(unsigned Offset) {
354 llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
355 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
356 ModulePass *MP = getContainedPass(Index);
357 MP->dumpPassStructure(Offset + 1);
358 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
359 OnTheFlyManagers.find(MP);
360 if (I != OnTheFlyManagers.end())
361 I->second->dumpPassStructure(Offset + 2);
362 dumpLastUses(MP, Offset+1);
366 ModulePass *getContainedPass(unsigned N) {
367 assert(N < PassVector.size() && "Pass number out of range!");
368 return static_cast<ModulePass *>(PassVector[N]);
371 virtual PassManagerType getPassManagerType() const {
372 return PMT_ModulePassManager;
376 /// Collection of on the fly FPPassManagers. These managers manage
377 /// function passes that are required by module passes.
378 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
381 char MPPassManager::ID = 0;
382 //===----------------------------------------------------------------------===//
386 /// PassManagerImpl manages MPPassManagers
387 class PassManagerImpl : public Pass,
388 public PMDataManager,
389 public PMTopLevelManager {
390 virtual void anchor();
394 explicit PassManagerImpl() :
395 Pass(PT_PassManager, ID), PMDataManager(),
396 PMTopLevelManager(new MPPassManager()) {}
398 /// add - Add a pass to the queue of passes to run. This passes ownership of
399 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
400 /// will be destroyed as well, so there is no need to delete the pass. This
401 /// implies that all passes MUST be allocated with 'new'.
406 /// createPrinterPass - Get a module printer pass.
407 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
408 return createPrintModulePass(&O, false, Banner);
411 /// run - Execute all of the passes scheduled for execution. Keep track of
412 /// whether any of the passes modifies the module, and if so, return true.
415 /// Pass Manager itself does not invalidate any analysis info.
416 void getAnalysisUsage(AnalysisUsage &Info) const {
417 Info.setPreservesAll();
420 void addTopLevelPass(Pass *P) {
421 if (ImmutablePass *IP = P->getAsImmutablePass()) {
422 // P is a immutable pass and it will be managed by this
423 // top level manager. Set up analysis resolver to connect them.
424 AnalysisResolver *AR = new AnalysisResolver(*this);
426 initializeAnalysisImpl(P);
427 addImmutablePass(IP);
428 recordAvailableAnalysis(IP);
430 P->assignPassManager(activeStack, PMT_ModulePassManager);
434 virtual PMDataManager *getAsPMDataManager() { return this; }
435 virtual Pass *getAsPass() { return this; }
437 MPPassManager *getContainedManager(unsigned N) {
438 assert(N < PassManagers.size() && "Pass number out of range!");
439 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
444 void PassManagerImpl::anchor() {}
446 char PassManagerImpl::ID = 0;
447 } // End of llvm namespace
451 //===----------------------------------------------------------------------===//
454 static DebugInfoProbeInfo *TheDebugProbe;
455 static void createDebugInfoProbe() {
456 if (TheDebugProbe) return;
458 // Constructed the first time this is called. This guarantees that the
459 // object will be constructed, if -enable-debug-info-probe is set,
460 // before static globals, thus it will be destroyed before them.
461 static ManagedStatic<DebugInfoProbeInfo> DIP;
462 TheDebugProbe = &*DIP;
465 //===----------------------------------------------------------------------===//
466 /// TimingInfo Class - This class is used to calculate information about the
467 /// amount of time each pass takes to execute. This only happens when
468 /// -time-passes is enabled on the command line.
471 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
474 DenseMap<Pass*, Timer*> TimingData;
477 // Use 'create' member to get this.
478 TimingInfo() : TG("... Pass execution timing report ...") {}
480 // TimingDtor - Print out information about timing information
482 // Delete all of the timers, which accumulate their info into the
484 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
485 E = TimingData.end(); I != E; ++I)
487 // TimerGroup is deleted next, printing the report.
490 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
491 // to a non null value (if the -time-passes option is enabled) or it leaves it
492 // null. It may be called multiple times.
493 static void createTheTimeInfo();
495 /// getPassTimer - Return the timer for the specified pass if it exists.
496 Timer *getPassTimer(Pass *P) {
497 if (P->getAsPMDataManager())
500 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
501 Timer *&T = TimingData[P];
503 T = new Timer(P->getPassName(), TG);
508 } // End of anon namespace
510 static TimingInfo *TheTimeInfo;
512 //===----------------------------------------------------------------------===//
513 // PMTopLevelManager implementation
515 /// Initialize top level manager. Create first pass manager.
516 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
517 PMDM->setTopLevelManager(this);
518 addPassManager(PMDM);
519 activeStack.push(PMDM);
522 /// Set pass P as the last user of the given analysis passes.
524 PMTopLevelManager::setLastUser(const SmallVectorImpl<Pass *> &AnalysisPasses,
527 if (P->getResolver())
528 PDepth = P->getResolver()->getPMDataManager().getDepth();
530 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
531 E = AnalysisPasses.end(); I != E; ++I) {
538 // Update the last users of passes that are required transitive by AP.
539 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
540 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
541 SmallVector<Pass *, 12> LastUses;
542 SmallVector<Pass *, 12> LastPMUses;
543 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
544 E = IDs.end(); I != E; ++I) {
545 Pass *AnalysisPass = findAnalysisPass(*I);
546 assert(AnalysisPass && "Expected analysis pass to exist.");
547 AnalysisResolver *AR = AnalysisPass->getResolver();
548 assert(AR && "Expected analysis resolver to exist.");
549 unsigned APDepth = AR->getPMDataManager().getDepth();
551 if (PDepth == APDepth)
552 LastUses.push_back(AnalysisPass);
553 else if (PDepth > APDepth)
554 LastPMUses.push_back(AnalysisPass);
557 setLastUser(LastUses, P);
559 // If this pass has a corresponding pass manager, push higher level
560 // analysis to this pass manager.
561 if (P->getResolver())
562 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
565 // If AP is the last user of other passes then make P last user of
567 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
568 LUE = LastUser.end(); LUI != LUE; ++LUI) {
569 if (LUI->second == AP)
570 // DenseMap iterator is not invalidated here because
571 // this is just updating existing entries.
572 LastUser[LUI->first] = P;
577 /// Collect passes whose last user is P
578 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
580 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
581 InversedLastUser.find(P);
582 if (DMI == InversedLastUser.end())
585 SmallPtrSet<Pass *, 8> &LU = DMI->second;
586 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
587 E = LU.end(); I != E; ++I) {
588 LastUses.push_back(*I);
593 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
594 AnalysisUsage *AnUsage = NULL;
595 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
596 if (DMI != AnUsageMap.end())
597 AnUsage = DMI->second;
599 AnUsage = new AnalysisUsage();
600 P->getAnalysisUsage(*AnUsage);
601 AnUsageMap[P] = AnUsage;
606 /// Schedule pass P for execution. Make sure that passes required by
607 /// P are run before P is run. Update analysis info maintained by
608 /// the manager. Remove dead passes. This is a recursive function.
609 void PMTopLevelManager::schedulePass(Pass *P) {
611 // TODO : Allocate function manager for this pass, other wise required set
612 // may be inserted into previous function manager
614 // Give pass a chance to prepare the stage.
615 P->preparePassManager(activeStack);
617 // If P is an analysis pass and it is available then do not
618 // generate the analysis again. Stale analysis info should not be
619 // available at this point.
621 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
622 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
627 AnalysisUsage *AnUsage = findAnalysisUsage(P);
629 bool checkAnalysis = true;
630 while (checkAnalysis) {
631 checkAnalysis = false;
633 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
634 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
635 E = RequiredSet.end(); I != E; ++I) {
637 Pass *AnalysisPass = findAnalysisPass(*I);
639 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
640 assert(PI && "Expected required passes to be initialized");
641 AnalysisPass = PI->createPass();
642 if (P->getPotentialPassManagerType () ==
643 AnalysisPass->getPotentialPassManagerType())
644 // Schedule analysis pass that is managed by the same pass manager.
645 schedulePass(AnalysisPass);
646 else if (P->getPotentialPassManagerType () >
647 AnalysisPass->getPotentialPassManagerType()) {
648 // Schedule analysis pass that is managed by a new manager.
649 schedulePass(AnalysisPass);
650 // Recheck analysis passes to ensure that required analyses that
651 // are already checked are still available.
652 checkAnalysis = true;
655 // Do not schedule this analysis. Lower level analsyis
656 // passes are run on the fly.
662 // Now all required passes are available.
666 /// Find the pass that implements Analysis AID. Search immutable
667 /// passes and all pass managers. If desired pass is not found
668 /// then return NULL.
669 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
671 // Check pass managers
672 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
673 E = PassManagers.end(); I != E; ++I)
674 if (Pass *P = (*I)->findAnalysisPass(AID, false))
677 // Check other pass managers
678 for (SmallVectorImpl<PMDataManager *>::iterator
679 I = IndirectPassManagers.begin(),
680 E = IndirectPassManagers.end(); I != E; ++I)
681 if (Pass *P = (*I)->findAnalysisPass(AID, false))
684 // Check the immutable passes. Iterate in reverse order so that we find
685 // the most recently registered passes first.
686 for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
687 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
688 AnalysisID PI = (*I)->getPassID();
692 // If Pass not found then check the interfaces implemented by Immutable Pass
693 const PassInfo *PassInf =
694 PassRegistry::getPassRegistry()->getPassInfo(PI);
695 assert(PassInf && "Expected all immutable passes to be initialized");
696 const std::vector<const PassInfo*> &ImmPI =
697 PassInf->getInterfacesImplemented();
698 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
699 EE = ImmPI.end(); II != EE; ++II) {
700 if ((*II)->getTypeInfo() == AID)
708 // Print passes managed by this top level manager.
709 void PMTopLevelManager::dumpPasses() const {
711 if (PassDebugging < Structure)
714 // Print out the immutable passes
715 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
716 ImmutablePasses[i]->dumpPassStructure(0);
719 // Every class that derives from PMDataManager also derives from Pass
720 // (sometimes indirectly), but there's no inheritance relationship
721 // between PMDataManager and Pass, so we have to getAsPass to get
722 // from a PMDataManager* to a Pass*.
723 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
724 E = PassManagers.end(); I != E; ++I)
725 (*I)->getAsPass()->dumpPassStructure(1);
728 void PMTopLevelManager::dumpArguments() const {
730 if (PassDebugging < Arguments)
733 dbgs() << "Pass Arguments: ";
734 for (SmallVector<ImmutablePass *, 8>::const_iterator I =
735 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
736 if (const PassInfo *PI =
737 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
738 assert(PI && "Expected all immutable passes to be initialized");
739 if (!PI->isAnalysisGroup())
740 dbgs() << " -" << PI->getPassArgument();
742 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
743 E = PassManagers.end(); I != E; ++I)
744 (*I)->dumpPassArguments();
748 void PMTopLevelManager::initializeAllAnalysisInfo() {
749 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
750 E = PassManagers.end(); I != E; ++I)
751 (*I)->initializeAnalysisInfo();
753 // Initailize other pass managers
754 for (SmallVectorImpl<PMDataManager *>::iterator
755 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
757 (*I)->initializeAnalysisInfo();
759 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
760 DME = LastUser.end(); DMI != DME; ++DMI) {
761 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
762 InversedLastUser.find(DMI->second);
763 if (InvDMI != InversedLastUser.end()) {
764 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
765 L.insert(DMI->first);
767 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
768 InversedLastUser[DMI->second] = L;
774 PMTopLevelManager::~PMTopLevelManager() {
775 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
776 E = PassManagers.end(); I != E; ++I)
779 for (SmallVectorImpl<ImmutablePass *>::iterator
780 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
783 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
784 DME = AnUsageMap.end(); DMI != DME; ++DMI)
788 //===----------------------------------------------------------------------===//
789 // PMDataManager implementation
791 /// Augement AvailableAnalysis by adding analysis made available by pass P.
792 void PMDataManager::recordAvailableAnalysis(Pass *P) {
793 AnalysisID PI = P->getPassID();
795 AvailableAnalysis[PI] = P;
797 assert(!AvailableAnalysis.empty());
799 // This pass is the current implementation of all of the interfaces it
800 // implements as well.
801 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
802 if (PInf == 0) return;
803 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
804 for (unsigned i = 0, e = II.size(); i != e; ++i)
805 AvailableAnalysis[II[i]->getTypeInfo()] = P;
808 // Return true if P preserves high level analysis used by other
809 // passes managed by this manager
810 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
811 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
812 if (AnUsage->getPreservesAll())
815 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
816 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
817 E = HigherLevelAnalysis.end(); I != E; ++I) {
819 if (P1->getAsImmutablePass() == 0 &&
820 std::find(PreservedSet.begin(), PreservedSet.end(),
829 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
830 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
831 // Don't do this unless assertions are enabled.
835 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
836 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
838 // Verify preserved analysis
839 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
840 E = PreservedSet.end(); I != E; ++I) {
842 if (Pass *AP = findAnalysisPass(AID, true)) {
843 TimeRegion PassTimer(getPassTimer(AP));
844 AP->verifyAnalysis();
849 /// Remove Analysis not preserved by Pass P
850 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
851 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
852 if (AnUsage->getPreservesAll())
855 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
856 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
857 E = AvailableAnalysis.end(); I != E; ) {
858 std::map<AnalysisID, Pass*>::iterator Info = I++;
859 if (Info->second->getAsImmutablePass() == 0 &&
860 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
861 PreservedSet.end()) {
862 // Remove this analysis
863 if (PassDebugging >= Details) {
864 Pass *S = Info->second;
865 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
866 dbgs() << S->getPassName() << "'\n";
868 AvailableAnalysis.erase(Info);
872 // Check inherited analysis also. If P is not preserving analysis
873 // provided by parent manager then remove it here.
874 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
876 if (!InheritedAnalysis[Index])
879 for (std::map<AnalysisID, Pass*>::iterator
880 I = InheritedAnalysis[Index]->begin(),
881 E = InheritedAnalysis[Index]->end(); I != E; ) {
882 std::map<AnalysisID, Pass *>::iterator Info = I++;
883 if (Info->second->getAsImmutablePass() == 0 &&
884 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
885 PreservedSet.end()) {
886 // Remove this analysis
887 if (PassDebugging >= Details) {
888 Pass *S = Info->second;
889 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
890 dbgs() << S->getPassName() << "'\n";
892 InheritedAnalysis[Index]->erase(Info);
898 /// Remove analysis passes that are not used any longer
899 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
900 enum PassDebuggingString DBG_STR) {
902 SmallVector<Pass *, 12> DeadPasses;
904 // If this is a on the fly manager then it does not have TPM.
908 TPM->collectLastUses(DeadPasses, P);
910 if (PassDebugging >= Details && !DeadPasses.empty()) {
911 dbgs() << " -*- '" << P->getPassName();
912 dbgs() << "' is the last user of following pass instances.";
913 dbgs() << " Free these instances\n";
916 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
917 E = DeadPasses.end(); I != E; ++I)
918 freePass(*I, Msg, DBG_STR);
921 void PMDataManager::freePass(Pass *P, StringRef Msg,
922 enum PassDebuggingString DBG_STR) {
923 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
926 // If the pass crashes releasing memory, remember this.
927 PassManagerPrettyStackEntry X(P);
928 TimeRegion PassTimer(getPassTimer(P));
933 AnalysisID PI = P->getPassID();
934 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
935 // Remove the pass itself (if it is not already removed).
936 AvailableAnalysis.erase(PI);
938 // Remove all interfaces this pass implements, for which it is also
939 // listed as the available implementation.
940 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
941 for (unsigned i = 0, e = II.size(); i != e; ++i) {
942 std::map<AnalysisID, Pass*>::iterator Pos =
943 AvailableAnalysis.find(II[i]->getTypeInfo());
944 if (Pos != AvailableAnalysis.end() && Pos->second == P)
945 AvailableAnalysis.erase(Pos);
950 /// Add pass P into the PassVector. Update
951 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
952 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
953 // This manager is going to manage pass P. Set up analysis resolver
955 AnalysisResolver *AR = new AnalysisResolver(*this);
958 // If a FunctionPass F is the last user of ModulePass info M
959 // then the F's manager, not F, records itself as a last user of M.
960 SmallVector<Pass *, 12> TransferLastUses;
962 if (!ProcessAnalysis) {
964 PassVector.push_back(P);
968 // At the moment, this pass is the last user of all required passes.
969 SmallVector<Pass *, 12> LastUses;
970 SmallVector<Pass *, 8> RequiredPasses;
971 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
973 unsigned PDepth = this->getDepth();
975 collectRequiredAnalysis(RequiredPasses,
976 ReqAnalysisNotAvailable, P);
977 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
978 E = RequiredPasses.end(); I != E; ++I) {
979 Pass *PRequired = *I;
982 assert(PRequired->getResolver() && "Analysis Resolver is not set");
983 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
984 RDepth = DM.getDepth();
986 if (PDepth == RDepth)
987 LastUses.push_back(PRequired);
988 else if (PDepth > RDepth) {
989 // Let the parent claim responsibility of last use
990 TransferLastUses.push_back(PRequired);
991 // Keep track of higher level analysis used by this manager.
992 HigherLevelAnalysis.push_back(PRequired);
994 llvm_unreachable("Unable to accommodate Required Pass");
997 // Set P as P's last user until someone starts using P.
998 // However, if P is a Pass Manager then it does not need
999 // to record its last user.
1000 if (P->getAsPMDataManager() == 0)
1001 LastUses.push_back(P);
1002 TPM->setLastUser(LastUses, P);
1004 if (!TransferLastUses.empty()) {
1005 Pass *My_PM = getAsPass();
1006 TPM->setLastUser(TransferLastUses, My_PM);
1007 TransferLastUses.clear();
1010 // Now, take care of required analyses that are not available.
1011 for (SmallVectorImpl<AnalysisID>::iterator
1012 I = ReqAnalysisNotAvailable.begin(),
1013 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1014 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1015 Pass *AnalysisPass = PI->createPass();
1016 this->addLowerLevelRequiredPass(P, AnalysisPass);
1019 // Take a note of analysis required and made available by this pass.
1020 // Remove the analysis not preserved by this pass
1021 removeNotPreservedAnalysis(P);
1022 recordAvailableAnalysis(P);
1025 PassVector.push_back(P);
1029 /// Populate RP with analysis pass that are required by
1030 /// pass P and are available. Populate RP_NotAvail with analysis
1031 /// pass that are required by pass P but are not available.
1032 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1033 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1035 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1036 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1037 for (AnalysisUsage::VectorType::const_iterator
1038 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1039 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1040 RP.push_back(AnalysisPass);
1042 RP_NotAvail.push_back(*I);
1045 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1046 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1047 E = IDs.end(); I != E; ++I) {
1048 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1049 RP.push_back(AnalysisPass);
1051 RP_NotAvail.push_back(*I);
1055 // All Required analyses should be available to the pass as it runs! Here
1056 // we fill in the AnalysisImpls member of the pass so that it can
1057 // successfully use the getAnalysis() method to retrieve the
1058 // implementations it needs.
1060 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1061 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1063 for (AnalysisUsage::VectorType::const_iterator
1064 I = AnUsage->getRequiredSet().begin(),
1065 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1066 Pass *Impl = findAnalysisPass(*I, true);
1068 // This may be analysis pass that is initialized on the fly.
1069 // If that is not the case then it will raise an assert when it is used.
1071 AnalysisResolver *AR = P->getResolver();
1072 assert(AR && "Analysis Resolver is not set");
1073 AR->addAnalysisImplsPair(*I, Impl);
1077 /// Find the pass that implements Analysis AID. If desired pass is not found
1078 /// then return NULL.
1079 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1081 // Check if AvailableAnalysis map has one entry.
1082 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1084 if (I != AvailableAnalysis.end())
1087 // Search Parents through TopLevelManager
1089 return TPM->findAnalysisPass(AID);
1094 // Print list of passes that are last used by P.
1095 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1097 SmallVector<Pass *, 12> LUses;
1099 // If this is a on the fly manager then it does not have TPM.
1103 TPM->collectLastUses(LUses, P);
1105 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1106 E = LUses.end(); I != E; ++I) {
1107 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1108 (*I)->dumpPassStructure(0);
1112 void PMDataManager::dumpPassArguments() const {
1113 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1114 E = PassVector.end(); I != E; ++I) {
1115 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1116 PMD->dumpPassArguments();
1118 if (const PassInfo *PI =
1119 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1120 if (!PI->isAnalysisGroup())
1121 dbgs() << " -" << PI->getPassArgument();
1125 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1126 enum PassDebuggingString S2,
1128 if (PassDebugging < Executions)
1130 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1133 dbgs() << "Executing Pass '" << P->getPassName();
1135 case MODIFICATION_MSG:
1136 dbgs() << "Made Modification '" << P->getPassName();
1139 dbgs() << " Freeing Pass '" << P->getPassName();
1145 case ON_BASICBLOCK_MSG:
1146 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1148 case ON_FUNCTION_MSG:
1149 dbgs() << "' on Function '" << Msg << "'...\n";
1152 dbgs() << "' on Module '" << Msg << "'...\n";
1155 dbgs() << "' on Region '" << Msg << "'...\n";
1158 dbgs() << "' on Loop '" << Msg << "'...\n";
1161 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1168 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1169 if (PassDebugging < Details)
1172 AnalysisUsage analysisUsage;
1173 P->getAnalysisUsage(analysisUsage);
1174 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1177 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1178 if (PassDebugging < Details)
1181 AnalysisUsage analysisUsage;
1182 P->getAnalysisUsage(analysisUsage);
1183 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1186 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1187 const AnalysisUsage::VectorType &Set) const {
1188 assert(PassDebugging >= Details);
1191 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1192 for (unsigned i = 0; i != Set.size(); ++i) {
1193 if (i) dbgs() << ',';
1194 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1196 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1198 dbgs() << " Uninitialized Pass";
1201 dbgs() << ' ' << PInf->getPassName();
1206 /// Add RequiredPass into list of lower level passes required by pass P.
1207 /// RequiredPass is run on the fly by Pass Manager when P requests it
1208 /// through getAnalysis interface.
1209 /// This should be handled by specific pass manager.
1210 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1212 TPM->dumpArguments();
1216 // Module Level pass may required Function Level analysis info
1217 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1218 // to provide this on demand. In that case, in Pass manager terminology,
1219 // module level pass is requiring lower level analysis info managed by
1220 // lower level pass manager.
1222 // When Pass manager is not able to order required analysis info, Pass manager
1223 // checks whether any lower level manager will be able to provide this
1224 // analysis info on demand or not.
1226 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1227 dbgs() << "' required by '" << P->getPassName() << "'\n";
1229 llvm_unreachable("Unable to schedule pass");
1232 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1233 assert(0 && "Unable to find on the fly pass");
1238 PMDataManager::~PMDataManager() {
1239 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1240 E = PassVector.end(); I != E; ++I)
1244 //===----------------------------------------------------------------------===//
1245 // NOTE: Is this the right place to define this method ?
1246 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1247 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1248 return PM.findAnalysisPass(ID, dir);
1251 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1253 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1256 //===----------------------------------------------------------------------===//
1257 // BBPassManager implementation
1259 /// Execute all of the passes scheduled for execution by invoking
1260 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1261 /// the function, and if so, return true.
1262 bool BBPassManager::runOnFunction(Function &F) {
1263 if (F.isDeclaration())
1266 bool Changed = doInitialization(F);
1268 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1269 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1270 BasicBlockPass *BP = getContainedPass(Index);
1271 bool LocalChanged = false;
1273 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1274 dumpRequiredSet(BP);
1276 initializeAnalysisImpl(BP);
1279 // If the pass crashes, remember this.
1280 PassManagerPrettyStackEntry X(BP, *I);
1281 TimeRegion PassTimer(getPassTimer(BP));
1283 LocalChanged |= BP->runOnBasicBlock(*I);
1286 Changed |= LocalChanged;
1288 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1290 dumpPreservedSet(BP);
1292 verifyPreservedAnalysis(BP);
1293 removeNotPreservedAnalysis(BP);
1294 recordAvailableAnalysis(BP);
1295 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1298 return doFinalization(F) || Changed;
1301 // Implement doInitialization and doFinalization
1302 bool BBPassManager::doInitialization(Module &M) {
1303 bool Changed = false;
1305 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1306 Changed |= getContainedPass(Index)->doInitialization(M);
1311 bool BBPassManager::doFinalization(Module &M) {
1312 bool Changed = false;
1314 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1315 Changed |= getContainedPass(Index)->doFinalization(M);
1320 bool BBPassManager::doInitialization(Function &F) {
1321 bool Changed = false;
1323 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1324 BasicBlockPass *BP = getContainedPass(Index);
1325 Changed |= BP->doInitialization(F);
1331 bool BBPassManager::doFinalization(Function &F) {
1332 bool Changed = false;
1334 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1335 BasicBlockPass *BP = getContainedPass(Index);
1336 Changed |= BP->doFinalization(F);
1343 //===----------------------------------------------------------------------===//
1344 // FunctionPassManager implementation
1346 /// Create new Function pass manager
1347 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1348 FPM = new FunctionPassManagerImpl();
1349 // FPM is the top level manager.
1350 FPM->setTopLevelManager(FPM);
1352 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1353 FPM->setResolver(AR);
1356 FunctionPassManager::~FunctionPassManager() {
1360 /// addImpl - Add a pass to the queue of passes to run, without
1361 /// checking whether to add a printer pass.
1362 void FunctionPassManager::addImpl(Pass *P) {
1366 /// add - Add a pass to the queue of passes to run. This passes
1367 /// ownership of the Pass to the PassManager. When the
1368 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1369 /// there is no need to delete the pass. (TODO delete passes.)
1370 /// This implies that all passes MUST be allocated with 'new'.
1371 void FunctionPassManager::add(Pass *P) {
1372 // If this is a not a function pass, don't add a printer for it.
1373 const void *PassID = P->getPassID();
1374 if (P->getPassKind() == PT_Function)
1375 if (ShouldPrintBeforePass(PassID))
1376 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1377 + P->getPassName() + " ***"));
1381 if (P->getPassKind() == PT_Function)
1382 if (ShouldPrintAfterPass(PassID))
1383 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1384 + P->getPassName() + " ***"));
1387 /// run - Execute all of the passes scheduled for execution. Keep
1388 /// track of whether any of the passes modifies the function, and if
1389 /// so, return true.
1391 bool FunctionPassManager::run(Function &F) {
1392 if (F.isMaterializable()) {
1394 if (F.Materialize(&errstr))
1395 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1401 /// doInitialization - Run all of the initializers for the function passes.
1403 bool FunctionPassManager::doInitialization() {
1404 return FPM->doInitialization(*M);
1407 /// doFinalization - Run all of the finalizers for the function passes.
1409 bool FunctionPassManager::doFinalization() {
1410 return FPM->doFinalization(*M);
1413 //===----------------------------------------------------------------------===//
1414 // FunctionPassManagerImpl implementation
1416 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1417 bool Changed = false;
1422 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1423 Changed |= getContainedManager(Index)->doInitialization(M);
1428 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1429 bool Changed = false;
1431 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1432 Changed |= getContainedManager(Index)->doFinalization(M);
1437 /// cleanup - After running all passes, clean up pass manager cache.
1438 void FPPassManager::cleanup() {
1439 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1440 FunctionPass *FP = getContainedPass(Index);
1441 AnalysisResolver *AR = FP->getResolver();
1442 assert(AR && "Analysis Resolver is not set");
1443 AR->clearAnalysisImpls();
1447 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1450 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1451 FPPassManager *FPPM = getContainedManager(Index);
1452 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1453 FPPM->getContainedPass(Index)->releaseMemory();
1459 // Execute all the passes managed by this top level manager.
1460 // Return true if any function is modified by a pass.
1461 bool FunctionPassManagerImpl::run(Function &F) {
1462 bool Changed = false;
1463 TimingInfo::createTheTimeInfo();
1464 createDebugInfoProbe();
1466 initializeAllAnalysisInfo();
1467 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1468 Changed |= getContainedManager(Index)->runOnFunction(F);
1470 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1471 getContainedManager(Index)->cleanup();
1477 //===----------------------------------------------------------------------===//
1478 // FPPassManager implementation
1480 char FPPassManager::ID = 0;
1481 /// Print passes managed by this manager
1482 void FPPassManager::dumpPassStructure(unsigned Offset) {
1483 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1484 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1485 FunctionPass *FP = getContainedPass(Index);
1486 FP->dumpPassStructure(Offset + 1);
1487 dumpLastUses(FP, Offset+1);
1492 /// Execute all of the passes scheduled for execution by invoking
1493 /// runOnFunction method. Keep track of whether any of the passes modifies
1494 /// the function, and if so, return true.
1495 bool FPPassManager::runOnFunction(Function &F) {
1496 if (F.isDeclaration())
1499 bool Changed = false;
1501 // Collect inherited analysis from Module level pass manager.
1502 populateInheritedAnalysis(TPM->activeStack);
1504 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1505 FunctionPass *FP = getContainedPass(Index);
1506 bool LocalChanged = false;
1508 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1509 dumpRequiredSet(FP);
1511 initializeAnalysisImpl(FP);
1513 TheDebugProbe->initialize(FP, F);
1515 PassManagerPrettyStackEntry X(FP, F);
1516 TimeRegion PassTimer(getPassTimer(FP));
1518 LocalChanged |= FP->runOnFunction(F);
1521 TheDebugProbe->finalize(FP, F);
1523 Changed |= LocalChanged;
1525 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1526 dumpPreservedSet(FP);
1528 verifyPreservedAnalysis(FP);
1529 removeNotPreservedAnalysis(FP);
1530 recordAvailableAnalysis(FP);
1531 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1536 bool FPPassManager::runOnModule(Module &M) {
1537 bool Changed = doInitialization(M);
1539 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1540 Changed |= runOnFunction(*I);
1542 return doFinalization(M) || Changed;
1545 bool FPPassManager::doInitialization(Module &M) {
1546 bool Changed = false;
1548 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1549 Changed |= getContainedPass(Index)->doInitialization(M);
1554 bool FPPassManager::doFinalization(Module &M) {
1555 bool Changed = false;
1557 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1558 Changed |= getContainedPass(Index)->doFinalization(M);
1563 //===----------------------------------------------------------------------===//
1564 // MPPassManager implementation
1566 /// Execute all of the passes scheduled for execution by invoking
1567 /// runOnModule method. Keep track of whether any of the passes modifies
1568 /// the module, and if so, return true.
1570 MPPassManager::runOnModule(Module &M) {
1571 bool Changed = false;
1573 // Initialize on-the-fly passes
1574 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1575 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1577 FunctionPassManagerImpl *FPP = I->second;
1578 Changed |= FPP->doInitialization(M);
1581 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1582 ModulePass *MP = getContainedPass(Index);
1583 bool LocalChanged = false;
1585 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1586 dumpRequiredSet(MP);
1588 initializeAnalysisImpl(MP);
1591 PassManagerPrettyStackEntry X(MP, M);
1592 TimeRegion PassTimer(getPassTimer(MP));
1594 LocalChanged |= MP->runOnModule(M);
1597 Changed |= LocalChanged;
1599 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1600 M.getModuleIdentifier());
1601 dumpPreservedSet(MP);
1603 verifyPreservedAnalysis(MP);
1604 removeNotPreservedAnalysis(MP);
1605 recordAvailableAnalysis(MP);
1606 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1609 // Finalize on-the-fly passes
1610 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1611 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1613 FunctionPassManagerImpl *FPP = I->second;
1614 // We don't know when is the last time an on-the-fly pass is run,
1615 // so we need to releaseMemory / finalize here
1616 FPP->releaseMemoryOnTheFly();
1617 Changed |= FPP->doFinalization(M);
1622 /// Add RequiredPass into list of lower level passes required by pass P.
1623 /// RequiredPass is run on the fly by Pass Manager when P requests it
1624 /// through getAnalysis interface.
1625 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1626 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1627 "Unable to handle Pass that requires lower level Analysis pass");
1628 assert((P->getPotentialPassManagerType() <
1629 RequiredPass->getPotentialPassManagerType()) &&
1630 "Unable to handle Pass that requires lower level Analysis pass");
1632 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1634 FPP = new FunctionPassManagerImpl();
1635 // FPP is the top level manager.
1636 FPP->setTopLevelManager(FPP);
1638 OnTheFlyManagers[P] = FPP;
1640 FPP->add(RequiredPass);
1642 // Register P as the last user of RequiredPass.
1644 SmallVector<Pass *, 1> LU;
1645 LU.push_back(RequiredPass);
1646 FPP->setLastUser(LU, P);
1650 /// Return function pass corresponding to PassInfo PI, that is
1651 /// required by module pass MP. Instantiate analysis pass, by using
1652 /// its runOnFunction() for function F.
1653 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1654 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1655 assert(FPP && "Unable to find on the fly pass");
1657 FPP->releaseMemoryOnTheFly();
1659 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1663 //===----------------------------------------------------------------------===//
1664 // PassManagerImpl implementation
1666 /// run - Execute all of the passes scheduled for execution. Keep track of
1667 /// whether any of the passes modifies the module, and if so, return true.
1668 bool PassManagerImpl::run(Module &M) {
1669 bool Changed = false;
1670 TimingInfo::createTheTimeInfo();
1671 createDebugInfoProbe();
1676 initializeAllAnalysisInfo();
1677 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1678 Changed |= getContainedManager(Index)->runOnModule(M);
1682 //===----------------------------------------------------------------------===//
1683 // PassManager implementation
1685 /// Create new pass manager
1686 PassManager::PassManager() {
1687 PM = new PassManagerImpl();
1688 // PM is the top level manager
1689 PM->setTopLevelManager(PM);
1692 PassManager::~PassManager() {
1696 /// addImpl - Add a pass to the queue of passes to run, without
1697 /// checking whether to add a printer pass.
1698 void PassManager::addImpl(Pass *P) {
1702 /// add - Add a pass to the queue of passes to run. This passes ownership of
1703 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1704 /// will be destroyed as well, so there is no need to delete the pass. This
1705 /// implies that all passes MUST be allocated with 'new'.
1706 void PassManager::add(Pass *P) {
1707 const void* PassID = P->getPassID();
1708 if (ShouldPrintBeforePass(PassID))
1709 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1710 + P->getPassName() + " ***"));
1714 if (ShouldPrintAfterPass(PassID))
1715 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1716 + P->getPassName() + " ***"));
1719 /// run - Execute all of the passes scheduled for execution. Keep track of
1720 /// whether any of the passes modifies the module, and if so, return true.
1721 bool PassManager::run(Module &M) {
1725 //===----------------------------------------------------------------------===//
1726 // TimingInfo Class - This class is used to calculate information about the
1727 // amount of time each pass takes to execute. This only happens with
1728 // -time-passes is enabled on the command line.
1730 bool llvm::TimePassesIsEnabled = false;
1731 static cl::opt<bool,true>
1732 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1733 cl::desc("Time each pass, printing elapsed time for each on exit"));
1735 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1736 // a non null value (if the -time-passes option is enabled) or it leaves it
1737 // null. It may be called multiple times.
1738 void TimingInfo::createTheTimeInfo() {
1739 if (!TimePassesIsEnabled || TheTimeInfo) return;
1741 // Constructed the first time this is called, iff -time-passes is enabled.
1742 // This guarantees that the object will be constructed before static globals,
1743 // thus it will be destroyed before them.
1744 static ManagedStatic<TimingInfo> TTI;
1745 TheTimeInfo = &*TTI;
1748 /// If TimingInfo is enabled then start pass timer.
1749 Timer *llvm::getPassTimer(Pass *P) {
1751 return TheTimeInfo->getPassTimer(P);
1755 //===----------------------------------------------------------------------===//
1756 // PMStack implementation
1759 // Pop Pass Manager from the stack and clear its analysis info.
1760 void PMStack::pop() {
1762 PMDataManager *Top = this->top();
1763 Top->initializeAnalysisInfo();
1768 // Push PM on the stack and set its top level manager.
1769 void PMStack::push(PMDataManager *PM) {
1770 assert(PM && "Unable to push. Pass Manager expected");
1771 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1773 if (!this->empty()) {
1774 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1775 && "pushing bad pass manager to PMStack");
1776 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1778 assert(TPM && "Unable to find top level manager");
1779 TPM->addIndirectPassManager(PM);
1780 PM->setTopLevelManager(TPM);
1781 PM->setDepth(this->top()->getDepth()+1);
1784 assert((PM->getPassManagerType() == PMT_ModulePassManager
1785 || PM->getPassManagerType() == PMT_FunctionPassManager)
1786 && "pushing bad pass manager to PMStack");
1793 // Dump content of the pass manager stack.
1794 void PMStack::dump() const {
1795 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1796 E = S.end(); I != E; ++I)
1797 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1803 /// Find appropriate Module Pass Manager in the PM Stack and
1804 /// add self into that manager.
1805 void ModulePass::assignPassManager(PMStack &PMS,
1806 PassManagerType PreferredType) {
1807 // Find Module Pass Manager
1808 while (!PMS.empty()) {
1809 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1810 if (TopPMType == PreferredType)
1811 break; // We found desired pass manager
1812 else if (TopPMType > PMT_ModulePassManager)
1813 PMS.pop(); // Pop children pass managers
1817 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1818 PMS.top()->add(this);
1821 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1822 /// in the PM Stack and add self into that manager.
1823 void FunctionPass::assignPassManager(PMStack &PMS,
1824 PassManagerType PreferredType) {
1826 // Find Module Pass Manager
1827 while (!PMS.empty()) {
1828 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1834 // Create new Function Pass Manager if needed.
1836 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1837 FPP = (FPPassManager *)PMS.top();
1839 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1840 PMDataManager *PMD = PMS.top();
1842 // [1] Create new Function Pass Manager
1843 FPP = new FPPassManager();
1844 FPP->populateInheritedAnalysis(PMS);
1846 // [2] Set up new manager's top level manager
1847 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1848 TPM->addIndirectPassManager(FPP);
1850 // [3] Assign manager to manage this new manager. This may create
1851 // and push new managers into PMS
1852 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1854 // [4] Push new manager into PMS
1858 // Assign FPP as the manager of this pass.
1862 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1863 /// in the PM Stack and add self into that manager.
1864 void BasicBlockPass::assignPassManager(PMStack &PMS,
1865 PassManagerType PreferredType) {
1868 // Basic Pass Manager is a leaf pass manager. It does not handle
1869 // any other pass manager.
1871 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1872 BBP = (BBPassManager *)PMS.top();
1874 // If leaf manager is not Basic Block Pass manager then create new
1875 // basic Block Pass manager.
1876 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1877 PMDataManager *PMD = PMS.top();
1879 // [1] Create new Basic Block Manager
1880 BBP = new BBPassManager();
1882 // [2] Set up new manager's top level manager
1883 // Basic Block Pass Manager does not live by itself
1884 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1885 TPM->addIndirectPassManager(BBP);
1887 // [3] Assign manager to manage this new manager. This may create
1888 // and push new managers into PMS
1889 BBP->assignPassManager(PMS, PreferredType);
1891 // [4] Push new manager into PMS
1895 // Assign BBP as the manager of this pass.
1899 PassManagerBase::~PassManagerBase() {}