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/Assembly/PrintModulePass.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/PassNameParser.h"
26 #include "llvm/Support/Timer.h"
27 #include "llvm/Support/raw_ostream.h"
32 // See PassManagers.h for Pass Manager infrastructure overview.
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information. Often it is useful to find out what pass is
38 // running when a crash occurs in a utility. When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
43 // Different debug levels that can be enabled...
45 Disabled, Arguments, Structure, Executions, Details
48 static cl::opt<enum PassDebugLevel>
49 PassDebugging("debug-pass", cl::Hidden,
50 cl::desc("Print PassManager debugging information"),
52 clEnumVal(Disabled , "disable debug output"),
53 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54 clEnumVal(Structure , "print pass structure before run()"),
55 clEnumVal(Executions, "print pass name before it is executed"),
56 clEnumVal(Details , "print pass details when it is executed"),
59 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
62 // Print IR out before/after specified passes.
64 PrintBefore("print-before",
65 llvm::cl::desc("Print IR before specified passes"),
69 PrintAfter("print-after",
70 llvm::cl::desc("Print IR after specified passes"),
74 PrintBeforeAll("print-before-all",
75 llvm::cl::desc("Print IR before each pass"),
78 PrintAfterAll("print-after-all",
79 llvm::cl::desc("Print IR after each pass"),
82 /// This is a helper to determine whether to print IR before or
85 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
86 PassOptionList &PassesToPrint) {
87 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
88 const llvm::PassInfo *PassInf = PassesToPrint[i];
90 if (PassInf->getPassArgument() == PI->getPassArgument()) {
97 /// This is a utility to check whether a pass should have IR dumped
99 static bool ShouldPrintBeforePass(const PassInfo *PI) {
100 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
103 /// This is a utility to check whether a pass should have IR dumped
105 static bool ShouldPrintAfterPass(const PassInfo *PI) {
106 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
109 } // End of llvm namespace
111 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
112 /// or higher is specified.
113 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
114 return PassDebugging >= Executions;
120 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
121 if (V == 0 && M == 0)
122 OS << "Releasing pass '";
124 OS << "Running pass '";
126 OS << P->getPassName() << "'";
129 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
138 if (isa<Function>(V))
140 else if (isa<BasicBlock>(V))
146 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
153 //===----------------------------------------------------------------------===//
156 /// BBPassManager manages BasicBlockPass. It batches all the
157 /// pass together and sequence them to process one basic block before
158 /// processing next basic block.
159 class BBPassManager : public PMDataManager, public FunctionPass {
163 explicit BBPassManager()
164 : PMDataManager(), FunctionPass(ID) {}
166 /// Execute all of the passes scheduled for execution. Keep track of
167 /// whether any of the passes modifies the function, and if so, return true.
168 bool runOnFunction(Function &F);
170 /// Pass Manager itself does not invalidate any analysis info.
171 void getAnalysisUsage(AnalysisUsage &Info) const {
172 Info.setPreservesAll();
175 bool doInitialization(Module &M);
176 bool doInitialization(Function &F);
177 bool doFinalization(Module &M);
178 bool doFinalization(Function &F);
180 virtual PMDataManager *getAsPMDataManager() { return this; }
181 virtual Pass *getAsPass() { return this; }
183 virtual const char *getPassName() const {
184 return "BasicBlock Pass Manager";
187 // Print passes managed by this manager
188 void dumpPassStructure(unsigned Offset) {
189 llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
190 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
191 BasicBlockPass *BP = getContainedPass(Index);
192 BP->dumpPassStructure(Offset + 1);
193 dumpLastUses(BP, Offset+1);
197 BasicBlockPass *getContainedPass(unsigned N) {
198 assert(N < PassVector.size() && "Pass number out of range!");
199 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
203 virtual PassManagerType getPassManagerType() const {
204 return PMT_BasicBlockPassManager;
208 char BBPassManager::ID = 0;
213 //===----------------------------------------------------------------------===//
214 // FunctionPassManagerImpl
216 /// FunctionPassManagerImpl manages FPPassManagers
217 class FunctionPassManagerImpl : public Pass,
218 public PMDataManager,
219 public PMTopLevelManager {
220 virtual void anchor();
225 explicit FunctionPassManagerImpl() :
226 Pass(PT_PassManager, ID), PMDataManager(),
227 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
229 /// add - Add a pass to the queue of passes to run. This passes ownership of
230 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
231 /// will be destroyed as well, so there is no need to delete the pass. This
232 /// implies that all passes MUST be allocated with 'new'.
237 /// createPrinterPass - Get a function printer pass.
238 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
239 return createPrintFunctionPass(Banner, &O);
242 // Prepare for running an on the fly pass, freeing memory if needed
243 // from a previous run.
244 void releaseMemoryOnTheFly();
246 /// run - Execute all of the passes scheduled for execution. Keep track of
247 /// whether any of the passes modifies the module, and if so, return true.
248 bool run(Function &F);
250 /// doInitialization - Run all of the initializers for the function passes.
252 bool doInitialization(Module &M);
254 /// doFinalization - Run all of the finalizers for the function passes.
256 bool doFinalization(Module &M);
259 virtual PMDataManager *getAsPMDataManager() { return this; }
260 virtual Pass *getAsPass() { return this; }
261 virtual PassManagerType getTopLevelPassManagerType() {
262 return PMT_FunctionPassManager;
265 /// Pass Manager itself does not invalidate any analysis info.
266 void getAnalysisUsage(AnalysisUsage &Info) const {
267 Info.setPreservesAll();
270 FPPassManager *getContainedManager(unsigned N) {
271 assert(N < PassManagers.size() && "Pass number out of range!");
272 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
277 void FunctionPassManagerImpl::anchor() {}
279 char FunctionPassManagerImpl::ID = 0;
281 //===----------------------------------------------------------------------===//
284 /// MPPassManager manages ModulePasses and function pass managers.
285 /// It batches all Module passes and function pass managers together and
286 /// sequences them to process one module.
287 class MPPassManager : public Pass, public PMDataManager {
290 explicit MPPassManager() :
291 Pass(PT_PassManager, ID), PMDataManager() { }
293 // Delete on the fly managers.
294 virtual ~MPPassManager() {
295 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
296 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
298 FunctionPassManagerImpl *FPP = I->second;
303 /// createPrinterPass - Get a module printer pass.
304 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
305 return createPrintModulePass(&O, false, Banner);
308 /// run - Execute all of the passes scheduled for execution. Keep track of
309 /// whether any of the passes modifies the module, and if so, return true.
310 bool runOnModule(Module &M);
312 using llvm::Pass::doInitialization;
313 using llvm::Pass::doFinalization;
315 /// doInitialization - Run all of the initializers for the module passes.
317 bool doInitialization();
319 /// doFinalization - Run all of the finalizers for the module passes.
321 bool doFinalization();
323 /// Pass Manager itself does not invalidate any analysis info.
324 void getAnalysisUsage(AnalysisUsage &Info) const {
325 Info.setPreservesAll();
328 /// Add RequiredPass into list of lower level passes required by pass P.
329 /// RequiredPass is run on the fly by Pass Manager when P requests it
330 /// through getAnalysis interface.
331 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
333 /// Return function pass corresponding to PassInfo PI, that is
334 /// required by module pass MP. Instantiate analysis pass, by using
335 /// its runOnFunction() for function F.
336 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
338 virtual const char *getPassName() const {
339 return "Module Pass Manager";
342 virtual PMDataManager *getAsPMDataManager() { return this; }
343 virtual Pass *getAsPass() { return this; }
345 // Print passes managed by this manager
346 void dumpPassStructure(unsigned Offset) {
347 llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
348 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
349 ModulePass *MP = getContainedPass(Index);
350 MP->dumpPassStructure(Offset + 1);
351 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
352 OnTheFlyManagers.find(MP);
353 if (I != OnTheFlyManagers.end())
354 I->second->dumpPassStructure(Offset + 2);
355 dumpLastUses(MP, Offset+1);
359 ModulePass *getContainedPass(unsigned N) {
360 assert(N < PassVector.size() && "Pass number out of range!");
361 return static_cast<ModulePass *>(PassVector[N]);
364 virtual PassManagerType getPassManagerType() const {
365 return PMT_ModulePassManager;
369 /// Collection of on the fly FPPassManagers. These managers manage
370 /// function passes that are required by module passes.
371 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
374 char MPPassManager::ID = 0;
375 //===----------------------------------------------------------------------===//
379 /// PassManagerImpl manages MPPassManagers
380 class PassManagerImpl : public Pass,
381 public PMDataManager,
382 public PMTopLevelManager {
383 virtual void anchor();
387 explicit PassManagerImpl() :
388 Pass(PT_PassManager, ID), PMDataManager(),
389 PMTopLevelManager(new MPPassManager()) {}
391 /// add - Add a pass to the queue of passes to run. This passes ownership of
392 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
393 /// will be destroyed as well, so there is no need to delete the pass. This
394 /// implies that all passes MUST be allocated with 'new'.
399 /// createPrinterPass - Get a module printer pass.
400 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
401 return createPrintModulePass(&O, false, Banner);
404 /// run - Execute all of the passes scheduled for execution. Keep track of
405 /// whether any of the passes modifies the module, and if so, return true.
408 using llvm::Pass::doInitialization;
409 using llvm::Pass::doFinalization;
411 /// doInitialization - Run all of the initializers for the module passes.
413 bool doInitialization();
415 /// doFinalization - Run all of the finalizers for the module passes.
417 bool doFinalization();
419 /// Pass Manager itself does not invalidate any analysis info.
420 void getAnalysisUsage(AnalysisUsage &Info) const {
421 Info.setPreservesAll();
424 virtual PMDataManager *getAsPMDataManager() { return this; }
425 virtual Pass *getAsPass() { return this; }
426 virtual PassManagerType getTopLevelPassManagerType() {
427 return PMT_ModulePassManager;
430 MPPassManager *getContainedManager(unsigned N) {
431 assert(N < PassManagers.size() && "Pass number out of range!");
432 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
437 void PassManagerImpl::anchor() {}
439 char PassManagerImpl::ID = 0;
440 } // End of llvm namespace
444 //===----------------------------------------------------------------------===//
445 /// TimingInfo Class - This class is used to calculate information about the
446 /// amount of time each pass takes to execute. This only happens when
447 /// -time-passes is enabled on the command line.
450 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
453 DenseMap<Pass*, Timer*> TimingData;
456 // Use 'create' member to get this.
457 TimingInfo() : TG("... Pass execution timing report ...") {}
459 // TimingDtor - Print out information about timing information
461 // Delete all of the timers, which accumulate their info into the
463 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
464 E = TimingData.end(); I != E; ++I)
466 // TimerGroup is deleted next, printing the report.
469 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
470 // to a non null value (if the -time-passes option is enabled) or it leaves it
471 // null. It may be called multiple times.
472 static void createTheTimeInfo();
474 /// getPassTimer - Return the timer for the specified pass if it exists.
475 Timer *getPassTimer(Pass *P) {
476 if (P->getAsPMDataManager())
479 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
480 Timer *&T = TimingData[P];
482 T = new Timer(P->getPassName(), TG);
487 } // End of anon namespace
489 static TimingInfo *TheTimeInfo;
491 //===----------------------------------------------------------------------===//
492 // PMTopLevelManager implementation
494 /// Initialize top level manager. Create first pass manager.
495 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
496 PMDM->setTopLevelManager(this);
497 addPassManager(PMDM);
498 activeStack.push(PMDM);
501 /// Set pass P as the last user of the given analysis passes.
503 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
505 if (P->getResolver())
506 PDepth = P->getResolver()->getPMDataManager().getDepth();
508 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
509 E = AnalysisPasses.end(); I != E; ++I) {
516 // Update the last users of passes that are required transitive by AP.
517 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
518 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
519 SmallVector<Pass *, 12> LastUses;
520 SmallVector<Pass *, 12> LastPMUses;
521 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
522 E = IDs.end(); I != E; ++I) {
523 Pass *AnalysisPass = findAnalysisPass(*I);
524 assert(AnalysisPass && "Expected analysis pass to exist.");
525 AnalysisResolver *AR = AnalysisPass->getResolver();
526 assert(AR && "Expected analysis resolver to exist.");
527 unsigned APDepth = AR->getPMDataManager().getDepth();
529 if (PDepth == APDepth)
530 LastUses.push_back(AnalysisPass);
531 else if (PDepth > APDepth)
532 LastPMUses.push_back(AnalysisPass);
535 setLastUser(LastUses, P);
537 // If this pass has a corresponding pass manager, push higher level
538 // analysis to this pass manager.
539 if (P->getResolver())
540 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
543 // If AP is the last user of other passes then make P last user of
545 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
546 LUE = LastUser.end(); LUI != LUE; ++LUI) {
547 if (LUI->second == AP)
548 // DenseMap iterator is not invalidated here because
549 // this is just updating existing entries.
550 LastUser[LUI->first] = P;
555 /// Collect passes whose last user is P
556 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
558 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
559 InversedLastUser.find(P);
560 if (DMI == InversedLastUser.end())
563 SmallPtrSet<Pass *, 8> &LU = DMI->second;
564 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
565 E = LU.end(); I != E; ++I) {
566 LastUses.push_back(*I);
571 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
572 AnalysisUsage *AnUsage = NULL;
573 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
574 if (DMI != AnUsageMap.end())
575 AnUsage = DMI->second;
577 AnUsage = new AnalysisUsage();
578 P->getAnalysisUsage(*AnUsage);
579 AnUsageMap[P] = AnUsage;
584 /// Schedule pass P for execution. Make sure that passes required by
585 /// P are run before P is run. Update analysis info maintained by
586 /// the manager. Remove dead passes. This is a recursive function.
587 void PMTopLevelManager::schedulePass(Pass *P) {
589 // TODO : Allocate function manager for this pass, other wise required set
590 // may be inserted into previous function manager
592 // Give pass a chance to prepare the stage.
593 P->preparePassManager(activeStack);
595 // If P is an analysis pass and it is available then do not
596 // generate the analysis again. Stale analysis info should not be
597 // available at this point.
599 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
600 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
605 AnalysisUsage *AnUsage = findAnalysisUsage(P);
607 bool checkAnalysis = true;
608 while (checkAnalysis) {
609 checkAnalysis = false;
611 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
612 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
613 E = RequiredSet.end(); I != E; ++I) {
615 Pass *AnalysisPass = findAnalysisPass(*I);
617 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
620 // Pass P is not in the global PassRegistry
621 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
622 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
623 dbgs() << "Required Passes:" << "\n";
624 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
625 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
626 Pass *AnalysisPass2 = findAnalysisPass(*I2);
628 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
630 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
631 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
632 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
637 assert(PI && "Expected required passes to be initialized");
638 AnalysisPass = PI->createPass();
639 if (P->getPotentialPassManagerType () ==
640 AnalysisPass->getPotentialPassManagerType())
641 // Schedule analysis pass that is managed by the same pass manager.
642 schedulePass(AnalysisPass);
643 else if (P->getPotentialPassManagerType () >
644 AnalysisPass->getPotentialPassManagerType()) {
645 // Schedule analysis pass that is managed by a new manager.
646 schedulePass(AnalysisPass);
647 // Recheck analysis passes to ensure that required analyses that
648 // are already checked are still available.
649 checkAnalysis = true;
651 // Do not schedule this analysis. Lower level analsyis
652 // passes are run on the fly.
658 // Now all required passes are available.
659 if (ImmutablePass *IP = P->getAsImmutablePass()) {
660 // P is a immutable pass and it will be managed by this
661 // top level manager. Set up analysis resolver to connect them.
662 PMDataManager *DM = getAsPMDataManager();
663 AnalysisResolver *AR = new AnalysisResolver(*DM);
665 DM->initializeAnalysisImpl(P);
666 addImmutablePass(IP);
667 DM->recordAvailableAnalysis(IP);
671 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
672 Pass *PP = P->createPrinterPass(
673 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
674 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
677 // Add the requested pass to the best available pass manager.
678 P->assignPassManager(activeStack, getTopLevelPassManagerType());
680 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
681 Pass *PP = P->createPrinterPass(
682 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
683 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
687 /// Find the pass that implements Analysis AID. Search immutable
688 /// passes and all pass managers. If desired pass is not found
689 /// then return NULL.
690 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
692 // Check pass managers
693 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
694 E = PassManagers.end(); I != E; ++I)
695 if (Pass *P = (*I)->findAnalysisPass(AID, false))
698 // Check other pass managers
699 for (SmallVectorImpl<PMDataManager *>::iterator
700 I = IndirectPassManagers.begin(),
701 E = IndirectPassManagers.end(); I != E; ++I)
702 if (Pass *P = (*I)->findAnalysisPass(AID, false))
705 // Check the immutable passes. Iterate in reverse order so that we find
706 // the most recently registered passes first.
707 for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
708 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
709 AnalysisID PI = (*I)->getPassID();
713 // If Pass not found then check the interfaces implemented by Immutable Pass
714 const PassInfo *PassInf =
715 PassRegistry::getPassRegistry()->getPassInfo(PI);
716 assert(PassInf && "Expected all immutable passes to be initialized");
717 const std::vector<const PassInfo*> &ImmPI =
718 PassInf->getInterfacesImplemented();
719 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
720 EE = ImmPI.end(); II != EE; ++II) {
721 if ((*II)->getTypeInfo() == AID)
729 // Print passes managed by this top level manager.
730 void PMTopLevelManager::dumpPasses() const {
732 if (PassDebugging < Structure)
735 // Print out the immutable passes
736 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
737 ImmutablePasses[i]->dumpPassStructure(0);
740 // Every class that derives from PMDataManager also derives from Pass
741 // (sometimes indirectly), but there's no inheritance relationship
742 // between PMDataManager and Pass, so we have to getAsPass to get
743 // from a PMDataManager* to a Pass*.
744 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
745 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
746 (*I)->getAsPass()->dumpPassStructure(1);
749 void PMTopLevelManager::dumpArguments() const {
751 if (PassDebugging < Arguments)
754 dbgs() << "Pass Arguments: ";
755 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
756 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
757 if (const PassInfo *PI =
758 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
759 assert(PI && "Expected all immutable passes to be initialized");
760 if (!PI->isAnalysisGroup())
761 dbgs() << " -" << PI->getPassArgument();
763 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
764 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
765 (*I)->dumpPassArguments();
769 void PMTopLevelManager::initializeAllAnalysisInfo() {
770 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
771 E = PassManagers.end(); I != E; ++I)
772 (*I)->initializeAnalysisInfo();
774 // Initailize other pass managers
775 for (SmallVectorImpl<PMDataManager *>::iterator
776 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
778 (*I)->initializeAnalysisInfo();
780 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
781 DME = LastUser.end(); DMI != DME; ++DMI) {
782 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
783 InversedLastUser.find(DMI->second);
784 if (InvDMI != InversedLastUser.end()) {
785 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
786 L.insert(DMI->first);
788 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
789 InversedLastUser[DMI->second] = L;
795 PMTopLevelManager::~PMTopLevelManager() {
796 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
797 E = PassManagers.end(); I != E; ++I)
800 for (SmallVectorImpl<ImmutablePass *>::iterator
801 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
804 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
805 DME = AnUsageMap.end(); DMI != DME; ++DMI)
809 //===----------------------------------------------------------------------===//
810 // PMDataManager implementation
812 /// Augement AvailableAnalysis by adding analysis made available by pass P.
813 void PMDataManager::recordAvailableAnalysis(Pass *P) {
814 AnalysisID PI = P->getPassID();
816 AvailableAnalysis[PI] = P;
818 assert(!AvailableAnalysis.empty());
820 // This pass is the current implementation of all of the interfaces it
821 // implements as well.
822 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
823 if (PInf == 0) return;
824 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
825 for (unsigned i = 0, e = II.size(); i != e; ++i)
826 AvailableAnalysis[II[i]->getTypeInfo()] = P;
829 // Return true if P preserves high level analysis used by other
830 // passes managed by this manager
831 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
832 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
833 if (AnUsage->getPreservesAll())
836 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
837 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
838 E = HigherLevelAnalysis.end(); I != E; ++I) {
840 if (P1->getAsImmutablePass() == 0 &&
841 std::find(PreservedSet.begin(), PreservedSet.end(),
850 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
851 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
852 // Don't do this unless assertions are enabled.
856 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
857 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
859 // Verify preserved analysis
860 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
861 E = PreservedSet.end(); I != E; ++I) {
863 if (Pass *AP = findAnalysisPass(AID, true)) {
864 TimeRegion PassTimer(getPassTimer(AP));
865 AP->verifyAnalysis();
870 /// Remove Analysis not preserved by Pass P
871 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
872 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
873 if (AnUsage->getPreservesAll())
876 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
877 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
878 E = AvailableAnalysis.end(); I != E; ) {
879 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
880 if (Info->second->getAsImmutablePass() == 0 &&
881 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
882 PreservedSet.end()) {
883 // Remove this analysis
884 if (PassDebugging >= Details) {
885 Pass *S = Info->second;
886 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
887 dbgs() << S->getPassName() << "'\n";
889 AvailableAnalysis.erase(Info);
893 // Check inherited analysis also. If P is not preserving analysis
894 // provided by parent manager then remove it here.
895 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
897 if (!InheritedAnalysis[Index])
900 for (DenseMap<AnalysisID, Pass*>::iterator
901 I = InheritedAnalysis[Index]->begin(),
902 E = InheritedAnalysis[Index]->end(); I != E; ) {
903 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
904 if (Info->second->getAsImmutablePass() == 0 &&
905 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
906 PreservedSet.end()) {
907 // Remove this analysis
908 if (PassDebugging >= Details) {
909 Pass *S = Info->second;
910 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
911 dbgs() << S->getPassName() << "'\n";
913 InheritedAnalysis[Index]->erase(Info);
919 /// Remove analysis passes that are not used any longer
920 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
921 enum PassDebuggingString DBG_STR) {
923 SmallVector<Pass *, 12> DeadPasses;
925 // If this is a on the fly manager then it does not have TPM.
929 TPM->collectLastUses(DeadPasses, P);
931 if (PassDebugging >= Details && !DeadPasses.empty()) {
932 dbgs() << " -*- '" << P->getPassName();
933 dbgs() << "' is the last user of following pass instances.";
934 dbgs() << " Free these instances\n";
937 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
938 E = DeadPasses.end(); I != E; ++I)
939 freePass(*I, Msg, DBG_STR);
942 void PMDataManager::freePass(Pass *P, StringRef Msg,
943 enum PassDebuggingString DBG_STR) {
944 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
947 // If the pass crashes releasing memory, remember this.
948 PassManagerPrettyStackEntry X(P);
949 TimeRegion PassTimer(getPassTimer(P));
954 AnalysisID PI = P->getPassID();
955 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
956 // Remove the pass itself (if it is not already removed).
957 AvailableAnalysis.erase(PI);
959 // Remove all interfaces this pass implements, for which it is also
960 // listed as the available implementation.
961 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
962 for (unsigned i = 0, e = II.size(); i != e; ++i) {
963 DenseMap<AnalysisID, Pass*>::iterator Pos =
964 AvailableAnalysis.find(II[i]->getTypeInfo());
965 if (Pos != AvailableAnalysis.end() && Pos->second == P)
966 AvailableAnalysis.erase(Pos);
971 /// Add pass P into the PassVector. Update
972 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
973 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
974 // This manager is going to manage pass P. Set up analysis resolver
976 AnalysisResolver *AR = new AnalysisResolver(*this);
979 // If a FunctionPass F is the last user of ModulePass info M
980 // then the F's manager, not F, records itself as a last user of M.
981 SmallVector<Pass *, 12> TransferLastUses;
983 if (!ProcessAnalysis) {
985 PassVector.push_back(P);
989 // At the moment, this pass is the last user of all required passes.
990 SmallVector<Pass *, 12> LastUses;
991 SmallVector<Pass *, 8> RequiredPasses;
992 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
994 unsigned PDepth = this->getDepth();
996 collectRequiredAnalysis(RequiredPasses,
997 ReqAnalysisNotAvailable, P);
998 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
999 E = RequiredPasses.end(); I != E; ++I) {
1000 Pass *PRequired = *I;
1001 unsigned RDepth = 0;
1003 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1004 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1005 RDepth = DM.getDepth();
1007 if (PDepth == RDepth)
1008 LastUses.push_back(PRequired);
1009 else if (PDepth > RDepth) {
1010 // Let the parent claim responsibility of last use
1011 TransferLastUses.push_back(PRequired);
1012 // Keep track of higher level analysis used by this manager.
1013 HigherLevelAnalysis.push_back(PRequired);
1015 llvm_unreachable("Unable to accommodate Required Pass");
1018 // Set P as P's last user until someone starts using P.
1019 // However, if P is a Pass Manager then it does not need
1020 // to record its last user.
1021 if (P->getAsPMDataManager() == 0)
1022 LastUses.push_back(P);
1023 TPM->setLastUser(LastUses, P);
1025 if (!TransferLastUses.empty()) {
1026 Pass *My_PM = getAsPass();
1027 TPM->setLastUser(TransferLastUses, My_PM);
1028 TransferLastUses.clear();
1031 // Now, take care of required analyses that are not available.
1032 for (SmallVectorImpl<AnalysisID>::iterator
1033 I = ReqAnalysisNotAvailable.begin(),
1034 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1035 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1036 Pass *AnalysisPass = PI->createPass();
1037 this->addLowerLevelRequiredPass(P, AnalysisPass);
1040 // Take a note of analysis required and made available by this pass.
1041 // Remove the analysis not preserved by this pass
1042 removeNotPreservedAnalysis(P);
1043 recordAvailableAnalysis(P);
1046 PassVector.push_back(P);
1050 /// Populate RP with analysis pass that are required by
1051 /// pass P and are available. Populate RP_NotAvail with analysis
1052 /// pass that are required by pass P but are not available.
1053 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1054 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1056 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1057 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1058 for (AnalysisUsage::VectorType::const_iterator
1059 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1060 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1061 RP.push_back(AnalysisPass);
1063 RP_NotAvail.push_back(*I);
1066 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1067 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1068 E = IDs.end(); I != E; ++I) {
1069 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1070 RP.push_back(AnalysisPass);
1072 RP_NotAvail.push_back(*I);
1076 // All Required analyses should be available to the pass as it runs! Here
1077 // we fill in the AnalysisImpls member of the pass so that it can
1078 // successfully use the getAnalysis() method to retrieve the
1079 // implementations it needs.
1081 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1082 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1084 for (AnalysisUsage::VectorType::const_iterator
1085 I = AnUsage->getRequiredSet().begin(),
1086 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1087 Pass *Impl = findAnalysisPass(*I, true);
1089 // This may be analysis pass that is initialized on the fly.
1090 // If that is not the case then it will raise an assert when it is used.
1092 AnalysisResolver *AR = P->getResolver();
1093 assert(AR && "Analysis Resolver is not set");
1094 AR->addAnalysisImplsPair(*I, Impl);
1098 /// Find the pass that implements Analysis AID. If desired pass is not found
1099 /// then return NULL.
1100 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1102 // Check if AvailableAnalysis map has one entry.
1103 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1105 if (I != AvailableAnalysis.end())
1108 // Search Parents through TopLevelManager
1110 return TPM->findAnalysisPass(AID);
1115 // Print list of passes that are last used by P.
1116 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1118 SmallVector<Pass *, 12> LUses;
1120 // If this is a on the fly manager then it does not have TPM.
1124 TPM->collectLastUses(LUses, P);
1126 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1127 E = LUses.end(); I != E; ++I) {
1128 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1129 (*I)->dumpPassStructure(0);
1133 void PMDataManager::dumpPassArguments() const {
1134 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1135 E = PassVector.end(); I != E; ++I) {
1136 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1137 PMD->dumpPassArguments();
1139 if (const PassInfo *PI =
1140 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1141 if (!PI->isAnalysisGroup())
1142 dbgs() << " -" << PI->getPassArgument();
1146 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1147 enum PassDebuggingString S2,
1149 if (PassDebugging < Executions)
1151 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1154 dbgs() << "Executing Pass '" << P->getPassName();
1156 case MODIFICATION_MSG:
1157 dbgs() << "Made Modification '" << P->getPassName();
1160 dbgs() << " Freeing Pass '" << P->getPassName();
1166 case ON_BASICBLOCK_MSG:
1167 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1169 case ON_FUNCTION_MSG:
1170 dbgs() << "' on Function '" << Msg << "'...\n";
1173 dbgs() << "' on Module '" << Msg << "'...\n";
1176 dbgs() << "' on Region '" << Msg << "'...\n";
1179 dbgs() << "' on Loop '" << Msg << "'...\n";
1182 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1189 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1190 if (PassDebugging < Details)
1193 AnalysisUsage analysisUsage;
1194 P->getAnalysisUsage(analysisUsage);
1195 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1198 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1199 if (PassDebugging < Details)
1202 AnalysisUsage analysisUsage;
1203 P->getAnalysisUsage(analysisUsage);
1204 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1207 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1208 const AnalysisUsage::VectorType &Set) const {
1209 assert(PassDebugging >= Details);
1212 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1213 for (unsigned i = 0; i != Set.size(); ++i) {
1214 if (i) dbgs() << ',';
1215 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1217 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1219 dbgs() << " Uninitialized Pass";
1222 dbgs() << ' ' << PInf->getPassName();
1227 /// Add RequiredPass into list of lower level passes required by pass P.
1228 /// RequiredPass is run on the fly by Pass Manager when P requests it
1229 /// through getAnalysis interface.
1230 /// This should be handled by specific pass manager.
1231 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1233 TPM->dumpArguments();
1237 // Module Level pass may required Function Level analysis info
1238 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1239 // to provide this on demand. In that case, in Pass manager terminology,
1240 // module level pass is requiring lower level analysis info managed by
1241 // lower level pass manager.
1243 // When Pass manager is not able to order required analysis info, Pass manager
1244 // checks whether any lower level manager will be able to provide this
1245 // analysis info on demand or not.
1247 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1248 dbgs() << "' required by '" << P->getPassName() << "'\n";
1250 llvm_unreachable("Unable to schedule pass");
1253 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1254 llvm_unreachable("Unable to find on the fly pass");
1258 PMDataManager::~PMDataManager() {
1259 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1260 E = PassVector.end(); I != E; ++I)
1264 //===----------------------------------------------------------------------===//
1265 // NOTE: Is this the right place to define this method ?
1266 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1267 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1268 return PM.findAnalysisPass(ID, dir);
1271 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1273 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1276 //===----------------------------------------------------------------------===//
1277 // BBPassManager implementation
1279 /// Execute all of the passes scheduled for execution by invoking
1280 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1281 /// the function, and if so, return true.
1282 bool BBPassManager::runOnFunction(Function &F) {
1283 if (F.isDeclaration())
1286 bool Changed = doInitialization(F);
1288 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1289 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1290 BasicBlockPass *BP = getContainedPass(Index);
1291 bool LocalChanged = false;
1293 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1294 dumpRequiredSet(BP);
1296 initializeAnalysisImpl(BP);
1299 // If the pass crashes, remember this.
1300 PassManagerPrettyStackEntry X(BP, *I);
1301 TimeRegion PassTimer(getPassTimer(BP));
1303 LocalChanged |= BP->runOnBasicBlock(*I);
1306 Changed |= LocalChanged;
1308 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1310 dumpPreservedSet(BP);
1312 verifyPreservedAnalysis(BP);
1313 removeNotPreservedAnalysis(BP);
1314 recordAvailableAnalysis(BP);
1315 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1318 return doFinalization(F) || Changed;
1321 // Implement doInitialization and doFinalization
1322 bool BBPassManager::doInitialization(Module &M) {
1323 bool Changed = false;
1325 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1326 Changed |= getContainedPass(Index)->doInitialization(M);
1331 bool BBPassManager::doFinalization(Module &M) {
1332 bool Changed = false;
1334 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1335 Changed |= getContainedPass(Index)->doFinalization(M);
1340 bool BBPassManager::doInitialization(Function &F) {
1341 bool Changed = false;
1343 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1344 BasicBlockPass *BP = getContainedPass(Index);
1345 Changed |= BP->doInitialization(F);
1351 bool BBPassManager::doFinalization(Function &F) {
1352 bool Changed = false;
1354 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1355 BasicBlockPass *BP = getContainedPass(Index);
1356 Changed |= BP->doFinalization(F);
1363 //===----------------------------------------------------------------------===//
1364 // FunctionPassManager implementation
1366 /// Create new Function pass manager
1367 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1368 FPM = new FunctionPassManagerImpl();
1369 // FPM is the top level manager.
1370 FPM->setTopLevelManager(FPM);
1372 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1373 FPM->setResolver(AR);
1376 FunctionPassManager::~FunctionPassManager() {
1380 /// add - Add a pass to the queue of passes to run. This passes
1381 /// ownership of the Pass to the PassManager. When the
1382 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1383 /// there is no need to delete the pass. (TODO delete passes.)
1384 /// This implies that all passes MUST be allocated with 'new'.
1385 void FunctionPassManager::add(Pass *P) {
1389 /// run - Execute all of the passes scheduled for execution. Keep
1390 /// track of whether any of the passes modifies the function, and if
1391 /// so, return true.
1393 bool FunctionPassManager::run(Function &F) {
1394 if (F.isMaterializable()) {
1396 if (F.Materialize(&errstr))
1397 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1403 /// doInitialization - Run all of the initializers for the function passes.
1405 bool FunctionPassManager::doInitialization() {
1406 return FPM->doInitialization(*M);
1409 /// doFinalization - Run all of the finalizers for the function passes.
1411 bool FunctionPassManager::doFinalization() {
1412 return FPM->doFinalization(*M);
1415 //===----------------------------------------------------------------------===//
1416 // FunctionPassManagerImpl implementation
1418 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1419 bool Changed = false;
1424 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1425 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1426 E = IPV.end(); I != E; ++I) {
1427 Changed |= (*I)->doInitialization(M);
1430 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1431 Changed |= getContainedManager(Index)->doInitialization(M);
1436 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1437 bool Changed = false;
1439 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1440 Changed |= getContainedManager(Index)->doFinalization(M);
1442 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1443 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1444 E = IPV.end(); I != E; ++I) {
1445 Changed |= (*I)->doFinalization(M);
1451 /// cleanup - After running all passes, clean up pass manager cache.
1452 void FPPassManager::cleanup() {
1453 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1454 FunctionPass *FP = getContainedPass(Index);
1455 AnalysisResolver *AR = FP->getResolver();
1456 assert(AR && "Analysis Resolver is not set");
1457 AR->clearAnalysisImpls();
1461 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1464 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1465 FPPassManager *FPPM = getContainedManager(Index);
1466 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1467 FPPM->getContainedPass(Index)->releaseMemory();
1473 // Execute all the passes managed by this top level manager.
1474 // Return true if any function is modified by a pass.
1475 bool FunctionPassManagerImpl::run(Function &F) {
1476 bool Changed = false;
1477 TimingInfo::createTheTimeInfo();
1479 initializeAllAnalysisInfo();
1480 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1481 Changed |= getContainedManager(Index)->runOnFunction(F);
1483 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1484 getContainedManager(Index)->cleanup();
1490 //===----------------------------------------------------------------------===//
1491 // FPPassManager implementation
1493 char FPPassManager::ID = 0;
1494 /// Print passes managed by this manager
1495 void FPPassManager::dumpPassStructure(unsigned Offset) {
1496 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1497 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1498 FunctionPass *FP = getContainedPass(Index);
1499 FP->dumpPassStructure(Offset + 1);
1500 dumpLastUses(FP, Offset+1);
1505 /// Execute all of the passes scheduled for execution by invoking
1506 /// runOnFunction method. Keep track of whether any of the passes modifies
1507 /// the function, and if so, return true.
1508 bool FPPassManager::runOnFunction(Function &F) {
1509 if (F.isDeclaration())
1512 bool Changed = false;
1514 // Collect inherited analysis from Module level pass manager.
1515 populateInheritedAnalysis(TPM->activeStack);
1517 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1518 FunctionPass *FP = getContainedPass(Index);
1519 bool LocalChanged = false;
1521 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1522 dumpRequiredSet(FP);
1524 initializeAnalysisImpl(FP);
1527 PassManagerPrettyStackEntry X(FP, F);
1528 TimeRegion PassTimer(getPassTimer(FP));
1530 LocalChanged |= FP->runOnFunction(F);
1533 Changed |= LocalChanged;
1535 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1536 dumpPreservedSet(FP);
1538 verifyPreservedAnalysis(FP);
1539 removeNotPreservedAnalysis(FP);
1540 recordAvailableAnalysis(FP);
1541 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1546 bool FPPassManager::runOnModule(Module &M) {
1547 bool Changed = false;
1549 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1550 Changed |= runOnFunction(*I);
1555 bool FPPassManager::doInitialization(Module &M) {
1556 bool Changed = false;
1558 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1559 Changed |= getContainedPass(Index)->doInitialization(M);
1564 bool FPPassManager::doFinalization(Module &M) {
1565 bool Changed = false;
1567 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1568 Changed |= getContainedPass(Index)->doFinalization(M);
1573 //===----------------------------------------------------------------------===//
1574 // MPPassManager implementation
1576 /// Execute all of the passes scheduled for execution by invoking
1577 /// runOnModule method. Keep track of whether any of the passes modifies
1578 /// the module, and if so, return true.
1580 MPPassManager::runOnModule(Module &M) {
1581 bool Changed = false;
1583 // Initialize on-the-fly passes
1584 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1585 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1587 FunctionPassManagerImpl *FPP = I->second;
1588 Changed |= FPP->doInitialization(M);
1591 // Initialize module passes
1592 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1593 Changed |= getContainedPass(Index)->doInitialization(M);
1595 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1596 ModulePass *MP = getContainedPass(Index);
1597 bool LocalChanged = false;
1599 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1600 dumpRequiredSet(MP);
1602 initializeAnalysisImpl(MP);
1605 PassManagerPrettyStackEntry X(MP, M);
1606 TimeRegion PassTimer(getPassTimer(MP));
1608 LocalChanged |= MP->runOnModule(M);
1611 Changed |= LocalChanged;
1613 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1614 M.getModuleIdentifier());
1615 dumpPreservedSet(MP);
1617 verifyPreservedAnalysis(MP);
1618 removeNotPreservedAnalysis(MP);
1619 recordAvailableAnalysis(MP);
1620 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1623 // Finalize module passes
1624 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1625 Changed |= getContainedPass(Index)->doFinalization(M);
1627 // Finalize on-the-fly passes
1628 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1629 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1631 FunctionPassManagerImpl *FPP = I->second;
1632 // We don't know when is the last time an on-the-fly pass is run,
1633 // so we need to releaseMemory / finalize here
1634 FPP->releaseMemoryOnTheFly();
1635 Changed |= FPP->doFinalization(M);
1641 /// Add RequiredPass into list of lower level passes required by pass P.
1642 /// RequiredPass is run on the fly by Pass Manager when P requests it
1643 /// through getAnalysis interface.
1644 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1645 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1646 "Unable to handle Pass that requires lower level Analysis pass");
1647 assert((P->getPotentialPassManagerType() <
1648 RequiredPass->getPotentialPassManagerType()) &&
1649 "Unable to handle Pass that requires lower level Analysis pass");
1651 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1653 FPP = new FunctionPassManagerImpl();
1654 // FPP is the top level manager.
1655 FPP->setTopLevelManager(FPP);
1657 OnTheFlyManagers[P] = FPP;
1659 FPP->add(RequiredPass);
1661 // Register P as the last user of RequiredPass.
1663 SmallVector<Pass *, 1> LU;
1664 LU.push_back(RequiredPass);
1665 FPP->setLastUser(LU, P);
1669 /// Return function pass corresponding to PassInfo PI, that is
1670 /// required by module pass MP. Instantiate analysis pass, by using
1671 /// its runOnFunction() for function F.
1672 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1673 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1674 assert(FPP && "Unable to find on the fly pass");
1676 FPP->releaseMemoryOnTheFly();
1678 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1682 //===----------------------------------------------------------------------===//
1683 // PassManagerImpl implementation
1686 /// run - Execute all of the passes scheduled for execution. Keep track of
1687 /// whether any of the passes modifies the module, and if so, return true.
1688 bool PassManagerImpl::run(Module &M) {
1689 bool Changed = false;
1690 TimingInfo::createTheTimeInfo();
1695 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1696 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1697 E = IPV.end(); I != E; ++I) {
1698 Changed |= (*I)->doInitialization(M);
1701 initializeAllAnalysisInfo();
1702 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1703 Changed |= getContainedManager(Index)->runOnModule(M);
1705 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1706 E = IPV.end(); I != E; ++I) {
1707 Changed |= (*I)->doFinalization(M);
1713 //===----------------------------------------------------------------------===//
1714 // PassManager implementation
1716 /// Create new pass manager
1717 PassManager::PassManager() {
1718 PM = new PassManagerImpl();
1719 // PM is the top level manager
1720 PM->setTopLevelManager(PM);
1723 PassManager::~PassManager() {
1727 /// add - Add a pass to the queue of passes to run. This passes ownership of
1728 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1729 /// will be destroyed as well, so there is no need to delete the pass. This
1730 /// implies that all passes MUST be allocated with 'new'.
1731 void PassManager::add(Pass *P) {
1735 /// run - Execute all of the passes scheduled for execution. Keep track of
1736 /// whether any of the passes modifies the module, and if so, return true.
1737 bool PassManager::run(Module &M) {
1741 //===----------------------------------------------------------------------===//
1742 // TimingInfo implementation
1744 bool llvm::TimePassesIsEnabled = false;
1745 static cl::opt<bool,true>
1746 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1747 cl::desc("Time each pass, printing elapsed time for each on exit"));
1749 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1750 // a non null value (if the -time-passes option is enabled) or it leaves it
1751 // null. It may be called multiple times.
1752 void TimingInfo::createTheTimeInfo() {
1753 if (!TimePassesIsEnabled || TheTimeInfo) return;
1755 // Constructed the first time this is called, iff -time-passes is enabled.
1756 // This guarantees that the object will be constructed before static globals,
1757 // thus it will be destroyed before them.
1758 static ManagedStatic<TimingInfo> TTI;
1759 TheTimeInfo = &*TTI;
1762 /// If TimingInfo is enabled then start pass timer.
1763 Timer *llvm::getPassTimer(Pass *P) {
1765 return TheTimeInfo->getPassTimer(P);
1769 //===----------------------------------------------------------------------===//
1770 // PMStack implementation
1773 // Pop Pass Manager from the stack and clear its analysis info.
1774 void PMStack::pop() {
1776 PMDataManager *Top = this->top();
1777 Top->initializeAnalysisInfo();
1782 // Push PM on the stack and set its top level manager.
1783 void PMStack::push(PMDataManager *PM) {
1784 assert(PM && "Unable to push. Pass Manager expected");
1785 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1787 if (!this->empty()) {
1788 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1789 && "pushing bad pass manager to PMStack");
1790 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1792 assert(TPM && "Unable to find top level manager");
1793 TPM->addIndirectPassManager(PM);
1794 PM->setTopLevelManager(TPM);
1795 PM->setDepth(this->top()->getDepth()+1);
1797 assert((PM->getPassManagerType() == PMT_ModulePassManager
1798 || PM->getPassManagerType() == PMT_FunctionPassManager)
1799 && "pushing bad pass manager to PMStack");
1806 // Dump content of the pass manager stack.
1807 void PMStack::dump() const {
1808 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1809 E = S.end(); I != E; ++I)
1810 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1816 /// Find appropriate Module Pass Manager in the PM Stack and
1817 /// add self into that manager.
1818 void ModulePass::assignPassManager(PMStack &PMS,
1819 PassManagerType PreferredType) {
1820 // Find Module Pass Manager
1821 while (!PMS.empty()) {
1822 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1823 if (TopPMType == PreferredType)
1824 break; // We found desired pass manager
1825 else if (TopPMType > PMT_ModulePassManager)
1826 PMS.pop(); // Pop children pass managers
1830 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1831 PMS.top()->add(this);
1834 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1835 /// in the PM Stack and add self into that manager.
1836 void FunctionPass::assignPassManager(PMStack &PMS,
1837 PassManagerType PreferredType) {
1839 // Find Function Pass Manager
1840 while (!PMS.empty()) {
1841 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1847 // Create new Function Pass Manager if needed.
1849 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1850 FPP = (FPPassManager *)PMS.top();
1852 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1853 PMDataManager *PMD = PMS.top();
1855 // [1] Create new Function Pass Manager
1856 FPP = new FPPassManager();
1857 FPP->populateInheritedAnalysis(PMS);
1859 // [2] Set up new manager's top level manager
1860 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1861 TPM->addIndirectPassManager(FPP);
1863 // [3] Assign manager to manage this new manager. This may create
1864 // and push new managers into PMS
1865 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1867 // [4] Push new manager into PMS
1871 // Assign FPP as the manager of this pass.
1875 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1876 /// in the PM Stack and add self into that manager.
1877 void BasicBlockPass::assignPassManager(PMStack &PMS,
1878 PassManagerType PreferredType) {
1881 // Basic Pass Manager is a leaf pass manager. It does not handle
1882 // any other pass manager.
1884 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1885 BBP = (BBPassManager *)PMS.top();
1887 // If leaf manager is not Basic Block Pass manager then create new
1888 // basic Block Pass manager.
1889 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1890 PMDataManager *PMD = PMS.top();
1892 // [1] Create new Basic Block Manager
1893 BBP = new BBPassManager();
1895 // [2] Set up new manager's top level manager
1896 // Basic Block Pass Manager does not live by itself
1897 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1898 TPM->addIndirectPassManager(BBP);
1900 // [3] Assign manager to manage this new manager. This may create
1901 // and push new managers into PMS
1902 BBP->assignPassManager(PMS, PreferredType);
1904 // [4] Push new manager into PMS
1908 // Assign BBP as the manager of this pass.
1912 PassManagerBase::~PassManagerBase() {}