1 //===- LegacyPassManager.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 legacy LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/IRPrintingPasses.h"
17 #include "llvm/IR/LegacyPassManager.h"
18 #include "llvm/IR/LegacyPassManagers.h"
19 #include "llvm/IR/LegacyPassNameParser.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/TimeValue.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
31 #include <unordered_set>
33 using namespace llvm::legacy;
35 // See PassManagers.h for Pass Manager infrastructure overview.
37 //===----------------------------------------------------------------------===//
38 // Pass debugging information. Often it is useful to find out what pass is
39 // running when a crash occurs in a utility. When this library is compiled with
40 // debugging on, a command line option (--debug-pass) is enabled that causes the
41 // pass name to be printed before it executes.
45 // Different debug levels that can be enabled...
47 Disabled, Arguments, Structure, Executions, Details
51 static cl::opt<enum PassDebugLevel>
52 PassDebugging("debug-pass", cl::Hidden,
53 cl::desc("Print PassManager debugging information"),
55 clEnumVal(Disabled , "disable debug output"),
56 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
57 clEnumVal(Structure , "print pass structure before run()"),
58 clEnumVal(Executions, "print pass name before it is executed"),
59 clEnumVal(Details , "print pass details when it is executed"),
63 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
67 // Print IR out before/after specified passes.
69 PrintBefore("print-before",
70 llvm::cl::desc("Print IR before specified passes"),
74 PrintAfter("print-after",
75 llvm::cl::desc("Print IR after specified passes"),
79 PrintBeforeAll("print-before-all",
80 llvm::cl::desc("Print IR before each pass"),
83 PrintAfterAll("print-after-all",
84 llvm::cl::desc("Print IR after each pass"),
87 static cl::list<std::string>
88 PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
89 cl::desc("Only print IR for functions whose name "
90 "match this for all print-[before|after][-all] "
94 /// This is a helper to determine whether to print IR before or
97 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
98 PassOptionList &PassesToPrint) {
99 for (auto *PassInf : PassesToPrint) {
101 if (PassInf->getPassArgument() == PI->getPassArgument()) {
108 /// This is a utility to check whether a pass should have IR dumped
110 static bool ShouldPrintBeforePass(const PassInfo *PI) {
111 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
114 /// This is a utility to check whether a pass should have IR dumped
116 static bool ShouldPrintAfterPass(const PassInfo *PI) {
117 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
120 bool llvm::isFunctionInPrintList(StringRef FunctionName) {
121 static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
122 PrintFuncsList.end());
123 return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName);
125 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
126 /// or higher is specified.
127 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
128 return PassDebugging >= Executions;
134 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
136 OS << "Releasing pass '";
138 OS << "Running pass '";
140 OS << P->getPassName() << "'";
143 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
152 if (isa<Function>(V))
154 else if (isa<BasicBlock>(V))
160 V->printAsOperand(OS, /*PrintTy=*/false, M);
166 //===----------------------------------------------------------------------===//
169 /// BBPassManager manages BasicBlockPass. It batches all the
170 /// pass together and sequence them to process one basic block before
171 /// processing next basic block.
172 class BBPassManager : public PMDataManager, public FunctionPass {
176 explicit BBPassManager()
177 : PMDataManager(), FunctionPass(ID) {}
179 /// Execute all of the passes scheduled for execution. Keep track of
180 /// whether any of the passes modifies the function, and if so, return true.
181 bool runOnFunction(Function &F) override;
183 /// Pass Manager itself does not invalidate any analysis info.
184 void getAnalysisUsage(AnalysisUsage &Info) const override {
185 Info.setPreservesAll();
188 bool doInitialization(Module &M) override;
189 bool doInitialization(Function &F);
190 bool doFinalization(Module &M) override;
191 bool doFinalization(Function &F);
193 PMDataManager *getAsPMDataManager() override { return this; }
194 Pass *getAsPass() override { return this; }
196 const char *getPassName() const override {
197 return "BasicBlock Pass Manager";
200 // Print passes managed by this manager
201 void dumpPassStructure(unsigned Offset) override {
202 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
203 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
204 BasicBlockPass *BP = getContainedPass(Index);
205 BP->dumpPassStructure(Offset + 1);
206 dumpLastUses(BP, Offset+1);
210 BasicBlockPass *getContainedPass(unsigned N) {
211 assert(N < PassVector.size() && "Pass number out of range!");
212 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
216 PassManagerType getPassManagerType() const override {
217 return PMT_BasicBlockPassManager;
221 char BBPassManager::ID = 0;
222 } // End anonymous namespace
226 //===----------------------------------------------------------------------===//
227 // FunctionPassManagerImpl
229 /// FunctionPassManagerImpl manages FPPassManagers
230 class FunctionPassManagerImpl : public Pass,
231 public PMDataManager,
232 public PMTopLevelManager {
233 virtual void anchor();
238 explicit FunctionPassManagerImpl() :
239 Pass(PT_PassManager, ID), PMDataManager(),
240 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
242 /// \copydoc FunctionPassManager::add()
247 /// createPrinterPass - Get a function printer pass.
248 Pass *createPrinterPass(raw_ostream &O,
249 const std::string &Banner) const override {
250 return createPrintFunctionPass(O, Banner);
253 // Prepare for running an on the fly pass, freeing memory if needed
254 // from a previous run.
255 void releaseMemoryOnTheFly();
257 /// run - Execute all of the passes scheduled for execution. Keep track of
258 /// whether any of the passes modifies the module, and if so, return true.
259 bool run(Function &F);
261 /// doInitialization - Run all of the initializers for the function passes.
263 bool doInitialization(Module &M) override;
265 /// doFinalization - Run all of the finalizers for the function passes.
267 bool doFinalization(Module &M) override;
270 PMDataManager *getAsPMDataManager() override { return this; }
271 Pass *getAsPass() override { return this; }
272 PassManagerType getTopLevelPassManagerType() override {
273 return PMT_FunctionPassManager;
276 /// Pass Manager itself does not invalidate any analysis info.
277 void getAnalysisUsage(AnalysisUsage &Info) const override {
278 Info.setPreservesAll();
281 FPPassManager *getContainedManager(unsigned N) {
282 assert(N < PassManagers.size() && "Pass number out of range!");
283 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
288 void FunctionPassManagerImpl::anchor() {}
290 char FunctionPassManagerImpl::ID = 0;
291 } // End of legacy namespace
292 } // End of llvm namespace
295 //===----------------------------------------------------------------------===//
298 /// MPPassManager manages ModulePasses and function pass managers.
299 /// It batches all Module passes and function pass managers together and
300 /// sequences them to process one module.
301 class MPPassManager : public Pass, public PMDataManager {
304 explicit MPPassManager() :
305 Pass(PT_PassManager, ID), PMDataManager() { }
307 // Delete on the fly managers.
308 ~MPPassManager() override {
309 for (auto &OnTheFlyManager : OnTheFlyManagers) {
310 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
315 /// createPrinterPass - Get a module printer pass.
316 Pass *createPrinterPass(raw_ostream &O,
317 const std::string &Banner) const override {
318 return createPrintModulePass(O, Banner);
321 /// run - Execute all of the passes scheduled for execution. Keep track of
322 /// whether any of the passes modifies the module, and if so, return true.
323 bool runOnModule(Module &M);
325 using llvm::Pass::doInitialization;
326 using llvm::Pass::doFinalization;
328 /// doInitialization - Run all of the initializers for the module passes.
330 bool doInitialization();
332 /// doFinalization - Run all of the finalizers for the module passes.
334 bool doFinalization();
336 /// Pass Manager itself does not invalidate any analysis info.
337 void getAnalysisUsage(AnalysisUsage &Info) const override {
338 Info.setPreservesAll();
341 /// Add RequiredPass into list of lower level passes required by pass P.
342 /// RequiredPass is run on the fly by Pass Manager when P requests it
343 /// through getAnalysis interface.
344 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
346 /// Return function pass corresponding to PassInfo PI, that is
347 /// required by module pass MP. Instantiate analysis pass, by using
348 /// its runOnFunction() for function F.
349 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
351 const char *getPassName() const override {
352 return "Module Pass Manager";
355 PMDataManager *getAsPMDataManager() override { return this; }
356 Pass *getAsPass() override { return this; }
358 // Print passes managed by this manager
359 void dumpPassStructure(unsigned Offset) override {
360 dbgs().indent(Offset*2) << "ModulePass Manager\n";
361 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
362 ModulePass *MP = getContainedPass(Index);
363 MP->dumpPassStructure(Offset + 1);
364 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
365 OnTheFlyManagers.find(MP);
366 if (I != OnTheFlyManagers.end())
367 I->second->dumpPassStructure(Offset + 2);
368 dumpLastUses(MP, Offset+1);
372 ModulePass *getContainedPass(unsigned N) {
373 assert(N < PassVector.size() && "Pass number out of range!");
374 return static_cast<ModulePass *>(PassVector[N]);
377 PassManagerType getPassManagerType() const override {
378 return PMT_ModulePassManager;
382 /// Collection of on the fly FPPassManagers. These managers manage
383 /// function passes that are required by module passes.
384 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
387 char MPPassManager::ID = 0;
388 } // End anonymous namespace
392 //===----------------------------------------------------------------------===//
396 /// PassManagerImpl manages MPPassManagers
397 class PassManagerImpl : public Pass,
398 public PMDataManager,
399 public PMTopLevelManager {
400 virtual void anchor();
404 explicit PassManagerImpl() :
405 Pass(PT_PassManager, ID), PMDataManager(),
406 PMTopLevelManager(new MPPassManager()) {}
408 /// \copydoc PassManager::add()
413 /// createPrinterPass - Get a module printer pass.
414 Pass *createPrinterPass(raw_ostream &O,
415 const std::string &Banner) const override {
416 return createPrintModulePass(O, Banner);
419 /// run - Execute all of the passes scheduled for execution. Keep track of
420 /// whether any of the passes modifies the module, and if so, return true.
423 using llvm::Pass::doInitialization;
424 using llvm::Pass::doFinalization;
426 /// doInitialization - Run all of the initializers for the module passes.
428 bool doInitialization();
430 /// doFinalization - Run all of the finalizers for the module passes.
432 bool doFinalization();
434 /// Pass Manager itself does not invalidate any analysis info.
435 void getAnalysisUsage(AnalysisUsage &Info) const override {
436 Info.setPreservesAll();
439 PMDataManager *getAsPMDataManager() override { return this; }
440 Pass *getAsPass() override { return this; }
441 PassManagerType getTopLevelPassManagerType() override {
442 return PMT_ModulePassManager;
445 MPPassManager *getContainedManager(unsigned N) {
446 assert(N < PassManagers.size() && "Pass number out of range!");
447 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
452 void PassManagerImpl::anchor() {}
454 char PassManagerImpl::ID = 0;
455 } // End of legacy namespace
456 } // End of llvm namespace
460 //===----------------------------------------------------------------------===//
461 /// TimingInfo Class - This class is used to calculate information about the
462 /// amount of time each pass takes to execute. This only happens when
463 /// -time-passes is enabled on the command line.
466 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
469 DenseMap<Pass*, Timer*> TimingData;
472 // Use 'create' member to get this.
473 TimingInfo() : TG("... Pass execution timing report ...") {}
475 // TimingDtor - Print out information about timing information
477 // Delete all of the timers, which accumulate their info into the
479 for (auto &I : TimingData)
481 // TimerGroup is deleted next, printing the report.
484 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
485 // to a non-null value (if the -time-passes option is enabled) or it leaves it
486 // null. It may be called multiple times.
487 static void createTheTimeInfo();
489 /// getPassTimer - Return the timer for the specified pass if it exists.
490 Timer *getPassTimer(Pass *P) {
491 if (P->getAsPMDataManager())
494 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
495 Timer *&T = TimingData[P];
497 T = new Timer(P->getPassName(), TG);
502 } // End of anon namespace
504 static TimingInfo *TheTimeInfo;
506 //===----------------------------------------------------------------------===//
507 // PMTopLevelManager implementation
509 /// Initialize top level manager. Create first pass manager.
510 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
511 PMDM->setTopLevelManager(this);
512 addPassManager(PMDM);
513 activeStack.push(PMDM);
516 /// Set pass P as the last user of the given analysis passes.
518 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
520 if (P->getResolver())
521 PDepth = P->getResolver()->getPMDataManager().getDepth();
523 for (Pass *AP : AnalysisPasses) {
529 // Update the last users of passes that are required transitive by AP.
530 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
531 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
532 SmallVector<Pass *, 12> LastUses;
533 SmallVector<Pass *, 12> LastPMUses;
534 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
535 E = IDs.end(); I != E; ++I) {
536 Pass *AnalysisPass = findAnalysisPass(*I);
537 assert(AnalysisPass && "Expected analysis pass to exist.");
538 AnalysisResolver *AR = AnalysisPass->getResolver();
539 assert(AR && "Expected analysis resolver to exist.");
540 unsigned APDepth = AR->getPMDataManager().getDepth();
542 if (PDepth == APDepth)
543 LastUses.push_back(AnalysisPass);
544 else if (PDepth > APDepth)
545 LastPMUses.push_back(AnalysisPass);
548 setLastUser(LastUses, P);
550 // If this pass has a corresponding pass manager, push higher level
551 // analysis to this pass manager.
552 if (P->getResolver())
553 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
556 // If AP is the last user of other passes then make P last user of
558 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
559 LUE = LastUser.end(); LUI != LUE; ++LUI) {
560 if (LUI->second == AP)
561 // DenseMap iterator is not invalidated here because
562 // this is just updating existing entries.
563 LastUser[LUI->first] = P;
568 /// Collect passes whose last user is P
569 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
571 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
572 InversedLastUser.find(P);
573 if (DMI == InversedLastUser.end())
576 SmallPtrSet<Pass *, 8> &LU = DMI->second;
577 for (Pass *LUP : LU) {
578 LastUses.push_back(LUP);
583 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
584 AnalysisUsage *AnUsage = nullptr;
585 auto DMI = AnUsageMap.find(P);
586 if (DMI != AnUsageMap.end())
587 AnUsage = DMI->second;
589 // Look up the analysis usage from the pass instance (different instances
590 // of the same pass can produce different results), but unique the
591 // resulting object to reduce memory usage. This helps to greatly reduce
592 // memory usage when we have many instances of only a few pass types
593 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
596 P->getAnalysisUsage(AU);
598 AUFoldingSetNode* Node = nullptr;
600 AUFoldingSetNode::Profile(ID, AU);
602 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
605 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
606 UniqueAnalysisUsages.InsertNode(Node, IP);
608 assert(Node && "cached analysis usage must be non null");
610 AnUsageMap[P] = &Node->AU;
611 AnUsage = &Node->AU;;
616 /// Schedule pass P for execution. Make sure that passes required by
617 /// P are run before P is run. Update analysis info maintained by
618 /// the manager. Remove dead passes. This is a recursive function.
619 void PMTopLevelManager::schedulePass(Pass *P) {
621 // TODO : Allocate function manager for this pass, other wise required set
622 // may be inserted into previous function manager
624 // Give pass a chance to prepare the stage.
625 P->preparePassManager(activeStack);
627 // If P is an analysis pass and it is available then do not
628 // generate the analysis again. Stale analysis info should not be
629 // available at this point.
630 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
631 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
636 AnalysisUsage *AnUsage = findAnalysisUsage(P);
638 bool checkAnalysis = true;
639 while (checkAnalysis) {
640 checkAnalysis = false;
642 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
643 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
644 E = RequiredSet.end(); I != E; ++I) {
646 Pass *AnalysisPass = findAnalysisPass(*I);
648 const PassInfo *PI = findAnalysisPassInfo(*I);
651 // Pass P is not in the global PassRegistry
652 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
653 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
654 dbgs() << "Required Passes:" << "\n";
655 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
656 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
657 Pass *AnalysisPass2 = findAnalysisPass(*I2);
659 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
661 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
662 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
663 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
668 assert(PI && "Expected required passes to be initialized");
669 AnalysisPass = PI->createPass();
670 if (P->getPotentialPassManagerType () ==
671 AnalysisPass->getPotentialPassManagerType())
672 // Schedule analysis pass that is managed by the same pass manager.
673 schedulePass(AnalysisPass);
674 else if (P->getPotentialPassManagerType () >
675 AnalysisPass->getPotentialPassManagerType()) {
676 // Schedule analysis pass that is managed by a new manager.
677 schedulePass(AnalysisPass);
678 // Recheck analysis passes to ensure that required analyses that
679 // are already checked are still available.
680 checkAnalysis = true;
682 // Do not schedule this analysis. Lower level analysis
683 // passes are run on the fly.
689 // Now all required passes are available.
690 if (ImmutablePass *IP = P->getAsImmutablePass()) {
691 // P is a immutable pass and it will be managed by this
692 // top level manager. Set up analysis resolver to connect them.
693 PMDataManager *DM = getAsPMDataManager();
694 AnalysisResolver *AR = new AnalysisResolver(*DM);
696 DM->initializeAnalysisImpl(P);
697 addImmutablePass(IP);
698 DM->recordAvailableAnalysis(IP);
702 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
703 Pass *PP = P->createPrinterPass(
704 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
705 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
708 // Add the requested pass to the best available pass manager.
709 P->assignPassManager(activeStack, getTopLevelPassManagerType());
711 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
712 Pass *PP = P->createPrinterPass(
713 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
714 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
718 /// Find the pass that implements Analysis AID. Search immutable
719 /// passes and all pass managers. If desired pass is not found
720 /// then return NULL.
721 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
722 // For immutable passes we have a direct mapping from ID to pass, so check
724 if (Pass *P = ImmutablePassMap.lookup(AID))
727 // Check pass managers
728 for (PMDataManager *PassManager : PassManagers)
729 if (Pass *P = PassManager->findAnalysisPass(AID, false))
732 // Check other pass managers
733 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
734 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
740 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
741 const PassInfo *&PI = AnalysisPassInfos[AID];
743 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
745 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
746 "The pass info pointer changed for an analysis ID!");
751 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
753 ImmutablePasses.push_back(P);
755 // Add this pass to the map from its analysis ID. We clobber any prior runs
756 // of the pass in the map so that the last one added is the one found when
758 AnalysisID AID = P->getPassID();
759 ImmutablePassMap[AID] = P;
761 // Also add any interfaces implemented by the immutable pass to the map for
763 const PassInfo *PassInf = findAnalysisPassInfo(AID);
764 assert(PassInf && "Expected all immutable passes to be initialized");
765 for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
766 ImmutablePassMap[ImmPI->getTypeInfo()] = P;
769 // Print passes managed by this top level manager.
770 void PMTopLevelManager::dumpPasses() const {
772 if (PassDebugging < Structure)
775 // Print out the immutable passes
776 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
777 ImmutablePasses[i]->dumpPassStructure(0);
780 // Every class that derives from PMDataManager also derives from Pass
781 // (sometimes indirectly), but there's no inheritance relationship
782 // between PMDataManager and Pass, so we have to getAsPass to get
783 // from a PMDataManager* to a Pass*.
784 for (PMDataManager *Manager : PassManagers)
785 Manager->getAsPass()->dumpPassStructure(1);
788 void PMTopLevelManager::dumpArguments() const {
790 if (PassDebugging < Arguments)
793 dbgs() << "Pass Arguments: ";
794 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
795 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
796 if (const PassInfo *PI = findAnalysisPassInfo((*I)->getPassID())) {
797 assert(PI && "Expected all immutable passes to be initialized");
798 if (!PI->isAnalysisGroup())
799 dbgs() << " -" << PI->getPassArgument();
801 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
802 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
803 (*I)->dumpPassArguments();
807 void PMTopLevelManager::initializeAllAnalysisInfo() {
808 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
809 E = PassManagers.end(); I != E; ++I)
810 (*I)->initializeAnalysisInfo();
812 // Initailize other pass managers
813 for (SmallVectorImpl<PMDataManager *>::iterator
814 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
816 (*I)->initializeAnalysisInfo();
818 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
819 DME = LastUser.end(); DMI != DME; ++DMI) {
820 SmallPtrSet<Pass *, 8> &L = InversedLastUser[DMI->second];
821 L.insert(DMI->first);
826 PMTopLevelManager::~PMTopLevelManager() {
827 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
828 E = PassManagers.end(); I != E; ++I)
831 for (SmallVectorImpl<ImmutablePass *>::iterator
832 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
836 //===----------------------------------------------------------------------===//
837 // PMDataManager implementation
839 /// Augement AvailableAnalysis by adding analysis made available by pass P.
840 void PMDataManager::recordAvailableAnalysis(Pass *P) {
841 AnalysisID PI = P->getPassID();
843 AvailableAnalysis[PI] = P;
845 assert(!AvailableAnalysis.empty());
847 // This pass is the current implementation of all of the interfaces it
848 // implements as well.
849 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
851 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
852 for (unsigned i = 0, e = II.size(); i != e; ++i)
853 AvailableAnalysis[II[i]->getTypeInfo()] = P;
856 // Return true if P preserves high level analysis used by other
857 // passes managed by this manager
858 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
859 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
860 if (AnUsage->getPreservesAll())
863 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
864 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
865 E = HigherLevelAnalysis.end(); I != E; ++I) {
867 if (P1->getAsImmutablePass() == nullptr &&
868 std::find(PreservedSet.begin(), PreservedSet.end(),
877 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
878 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
879 // Don't do this unless assertions are enabled.
883 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
884 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
886 // Verify preserved analysis
887 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
888 E = PreservedSet.end(); I != E; ++I) {
890 if (Pass *AP = findAnalysisPass(AID, true)) {
891 TimeRegion PassTimer(getPassTimer(AP));
892 AP->verifyAnalysis();
897 /// Remove Analysis not preserved by Pass P
898 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
899 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
900 if (AnUsage->getPreservesAll())
903 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
904 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
905 E = AvailableAnalysis.end(); I != E; ) {
906 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
907 if (Info->second->getAsImmutablePass() == nullptr &&
908 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
909 PreservedSet.end()) {
910 // Remove this analysis
911 if (PassDebugging >= Details) {
912 Pass *S = Info->second;
913 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
914 dbgs() << S->getPassName() << "'\n";
916 AvailableAnalysis.erase(Info);
920 // Check inherited analysis also. If P is not preserving analysis
921 // provided by parent manager then remove it here.
922 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
924 if (!InheritedAnalysis[Index])
927 for (DenseMap<AnalysisID, Pass*>::iterator
928 I = InheritedAnalysis[Index]->begin(),
929 E = InheritedAnalysis[Index]->end(); I != E; ) {
930 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
931 if (Info->second->getAsImmutablePass() == nullptr &&
932 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
933 PreservedSet.end()) {
934 // Remove this analysis
935 if (PassDebugging >= Details) {
936 Pass *S = Info->second;
937 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
938 dbgs() << S->getPassName() << "'\n";
940 InheritedAnalysis[Index]->erase(Info);
946 /// Remove analysis passes that are not used any longer
947 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
948 enum PassDebuggingString DBG_STR) {
950 SmallVector<Pass *, 12> DeadPasses;
952 // If this is a on the fly manager then it does not have TPM.
956 TPM->collectLastUses(DeadPasses, P);
958 if (PassDebugging >= Details && !DeadPasses.empty()) {
959 dbgs() << " -*- '" << P->getPassName();
960 dbgs() << "' is the last user of following pass instances.";
961 dbgs() << " Free these instances\n";
964 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
965 E = DeadPasses.end(); I != E; ++I)
966 freePass(*I, Msg, DBG_STR);
969 void PMDataManager::freePass(Pass *P, StringRef Msg,
970 enum PassDebuggingString DBG_STR) {
971 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
974 // If the pass crashes releasing memory, remember this.
975 PassManagerPrettyStackEntry X(P);
976 TimeRegion PassTimer(getPassTimer(P));
981 AnalysisID PI = P->getPassID();
982 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
983 // Remove the pass itself (if it is not already removed).
984 AvailableAnalysis.erase(PI);
986 // Remove all interfaces this pass implements, for which it is also
987 // listed as the available implementation.
988 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
989 for (unsigned i = 0, e = II.size(); i != e; ++i) {
990 DenseMap<AnalysisID, Pass*>::iterator Pos =
991 AvailableAnalysis.find(II[i]->getTypeInfo());
992 if (Pos != AvailableAnalysis.end() && Pos->second == P)
993 AvailableAnalysis.erase(Pos);
998 /// Add pass P into the PassVector. Update
999 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
1000 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
1001 // This manager is going to manage pass P. Set up analysis resolver
1003 AnalysisResolver *AR = new AnalysisResolver(*this);
1006 // If a FunctionPass F is the last user of ModulePass info M
1007 // then the F's manager, not F, records itself as a last user of M.
1008 SmallVector<Pass *, 12> TransferLastUses;
1010 if (!ProcessAnalysis) {
1012 PassVector.push_back(P);
1016 // At the moment, this pass is the last user of all required passes.
1017 SmallVector<Pass *, 12> LastUses;
1018 SmallVector<Pass *, 8> UsedPasses;
1019 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1021 unsigned PDepth = this->getDepth();
1023 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
1024 for (Pass *PUsed : UsedPasses) {
1025 unsigned RDepth = 0;
1027 assert(PUsed->getResolver() && "Analysis Resolver is not set");
1028 PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
1029 RDepth = DM.getDepth();
1031 if (PDepth == RDepth)
1032 LastUses.push_back(PUsed);
1033 else if (PDepth > RDepth) {
1034 // Let the parent claim responsibility of last use
1035 TransferLastUses.push_back(PUsed);
1036 // Keep track of higher level analysis used by this manager.
1037 HigherLevelAnalysis.push_back(PUsed);
1039 llvm_unreachable("Unable to accommodate Used Pass");
1042 // Set P as P's last user until someone starts using P.
1043 // However, if P is a Pass Manager then it does not need
1044 // to record its last user.
1045 if (!P->getAsPMDataManager())
1046 LastUses.push_back(P);
1047 TPM->setLastUser(LastUses, P);
1049 if (!TransferLastUses.empty()) {
1050 Pass *My_PM = getAsPass();
1051 TPM->setLastUser(TransferLastUses, My_PM);
1052 TransferLastUses.clear();
1055 // Now, take care of required analyses that are not available.
1056 for (AnalysisID ID : ReqAnalysisNotAvailable) {
1057 const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1058 Pass *AnalysisPass = PI->createPass();
1059 this->addLowerLevelRequiredPass(P, AnalysisPass);
1062 // Take a note of analysis required and made available by this pass.
1063 // Remove the analysis not preserved by this pass
1064 removeNotPreservedAnalysis(P);
1065 recordAvailableAnalysis(P);
1068 PassVector.push_back(P);
1072 /// Populate UP with analysis pass that are used or required by
1073 /// pass P and are available. Populate RP_NotAvail with analysis
1074 /// pass that are required by pass P but are not available.
1075 void PMDataManager::collectRequiredAndUsedAnalyses(
1076 SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1078 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1080 for (const auto &UsedID : AnUsage->getUsedSet())
1081 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1082 UP.push_back(AnalysisPass);
1084 for (const auto &RequiredID : AnUsage->getRequiredSet())
1085 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1086 UP.push_back(AnalysisPass);
1088 RP_NotAvail.push_back(RequiredID);
1090 for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1091 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1092 UP.push_back(AnalysisPass);
1094 RP_NotAvail.push_back(RequiredID);
1097 // All Required analyses should be available to the pass as it runs! Here
1098 // we fill in the AnalysisImpls member of the pass so that it can
1099 // successfully use the getAnalysis() method to retrieve the
1100 // implementations it needs.
1102 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1103 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1105 for (AnalysisUsage::VectorType::const_iterator
1106 I = AnUsage->getRequiredSet().begin(),
1107 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1108 Pass *Impl = findAnalysisPass(*I, true);
1110 // This may be analysis pass that is initialized on the fly.
1111 // If that is not the case then it will raise an assert when it is used.
1113 AnalysisResolver *AR = P->getResolver();
1114 assert(AR && "Analysis Resolver is not set");
1115 AR->addAnalysisImplsPair(*I, Impl);
1119 /// Find the pass that implements Analysis AID. If desired pass is not found
1120 /// then return NULL.
1121 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1123 // Check if AvailableAnalysis map has one entry.
1124 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1126 if (I != AvailableAnalysis.end())
1129 // Search Parents through TopLevelManager
1131 return TPM->findAnalysisPass(AID);
1136 // Print list of passes that are last used by P.
1137 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1139 SmallVector<Pass *, 12> LUses;
1141 // If this is a on the fly manager then it does not have TPM.
1145 TPM->collectLastUses(LUses, P);
1147 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1148 E = LUses.end(); I != E; ++I) {
1149 dbgs() << "--" << std::string(Offset*2, ' ');
1150 (*I)->dumpPassStructure(0);
1154 void PMDataManager::dumpPassArguments() const {
1155 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1156 E = PassVector.end(); I != E; ++I) {
1157 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1158 PMD->dumpPassArguments();
1160 if (const PassInfo *PI =
1161 TPM->findAnalysisPassInfo((*I)->getPassID()))
1162 if (!PI->isAnalysisGroup())
1163 dbgs() << " -" << PI->getPassArgument();
1167 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1168 enum PassDebuggingString S2,
1170 if (PassDebugging < Executions)
1172 dbgs() << "[" << sys::TimeValue::now().str() << "] " << (void *)this
1173 << std::string(getDepth() * 2 + 1, ' ');
1176 dbgs() << "Executing Pass '" << P->getPassName();
1178 case MODIFICATION_MSG:
1179 dbgs() << "Made Modification '" << P->getPassName();
1182 dbgs() << " Freeing Pass '" << P->getPassName();
1188 case ON_BASICBLOCK_MSG:
1189 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1191 case ON_FUNCTION_MSG:
1192 dbgs() << "' on Function '" << Msg << "'...\n";
1195 dbgs() << "' on Module '" << Msg << "'...\n";
1198 dbgs() << "' on Region '" << Msg << "'...\n";
1201 dbgs() << "' on Loop '" << Msg << "'...\n";
1204 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1211 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1212 if (PassDebugging < Details)
1215 AnalysisUsage analysisUsage;
1216 P->getAnalysisUsage(analysisUsage);
1217 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1220 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1221 if (PassDebugging < Details)
1224 AnalysisUsage analysisUsage;
1225 P->getAnalysisUsage(analysisUsage);
1226 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1229 void PMDataManager::dumpUsedSet(const Pass *P) const {
1230 if (PassDebugging < Details)
1233 AnalysisUsage analysisUsage;
1234 P->getAnalysisUsage(analysisUsage);
1235 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1238 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1239 const AnalysisUsage::VectorType &Set) const {
1240 assert(PassDebugging >= Details);
1243 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1244 for (unsigned i = 0; i != Set.size(); ++i) {
1245 if (i) dbgs() << ',';
1246 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1248 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1250 dbgs() << " Uninitialized Pass";
1253 dbgs() << ' ' << PInf->getPassName();
1258 /// Add RequiredPass into list of lower level passes required by pass P.
1259 /// RequiredPass is run on the fly by Pass Manager when P requests it
1260 /// through getAnalysis interface.
1261 /// This should be handled by specific pass manager.
1262 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1264 TPM->dumpArguments();
1268 // Module Level pass may required Function Level analysis info
1269 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1270 // to provide this on demand. In that case, in Pass manager terminology,
1271 // module level pass is requiring lower level analysis info managed by
1272 // lower level pass manager.
1274 // When Pass manager is not able to order required analysis info, Pass manager
1275 // checks whether any lower level manager will be able to provide this
1276 // analysis info on demand or not.
1278 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1279 dbgs() << "' required by '" << P->getPassName() << "'\n";
1281 llvm_unreachable("Unable to schedule pass");
1284 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1285 llvm_unreachable("Unable to find on the fly pass");
1289 PMDataManager::~PMDataManager() {
1290 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1291 E = PassVector.end(); I != E; ++I)
1295 //===----------------------------------------------------------------------===//
1296 // NOTE: Is this the right place to define this method ?
1297 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1298 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1299 return PM.findAnalysisPass(ID, dir);
1302 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1304 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1307 //===----------------------------------------------------------------------===//
1308 // BBPassManager implementation
1310 /// Execute all of the passes scheduled for execution by invoking
1311 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1312 /// the function, and if so, return true.
1313 bool BBPassManager::runOnFunction(Function &F) {
1314 if (F.isDeclaration())
1317 bool Changed = doInitialization(F);
1319 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1320 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1321 BasicBlockPass *BP = getContainedPass(Index);
1322 bool LocalChanged = false;
1324 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1325 dumpRequiredSet(BP);
1327 initializeAnalysisImpl(BP);
1330 // If the pass crashes, remember this.
1331 PassManagerPrettyStackEntry X(BP, *I);
1332 TimeRegion PassTimer(getPassTimer(BP));
1334 LocalChanged |= BP->runOnBasicBlock(*I);
1337 Changed |= LocalChanged;
1339 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1341 dumpPreservedSet(BP);
1344 verifyPreservedAnalysis(BP);
1345 removeNotPreservedAnalysis(BP);
1346 recordAvailableAnalysis(BP);
1347 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1350 return doFinalization(F) || Changed;
1353 // Implement doInitialization and doFinalization
1354 bool BBPassManager::doInitialization(Module &M) {
1355 bool Changed = false;
1357 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1358 Changed |= getContainedPass(Index)->doInitialization(M);
1363 bool BBPassManager::doFinalization(Module &M) {
1364 bool Changed = false;
1366 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1367 Changed |= getContainedPass(Index)->doFinalization(M);
1372 bool BBPassManager::doInitialization(Function &F) {
1373 bool Changed = false;
1375 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1376 BasicBlockPass *BP = getContainedPass(Index);
1377 Changed |= BP->doInitialization(F);
1383 bool BBPassManager::doFinalization(Function &F) {
1384 bool Changed = false;
1386 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1387 BasicBlockPass *BP = getContainedPass(Index);
1388 Changed |= BP->doFinalization(F);
1395 //===----------------------------------------------------------------------===//
1396 // FunctionPassManager implementation
1398 /// Create new Function pass manager
1399 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1400 FPM = new FunctionPassManagerImpl();
1401 // FPM is the top level manager.
1402 FPM->setTopLevelManager(FPM);
1404 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1405 FPM->setResolver(AR);
1408 FunctionPassManager::~FunctionPassManager() {
1412 void FunctionPassManager::add(Pass *P) {
1416 /// run - Execute all of the passes scheduled for execution. Keep
1417 /// track of whether any of the passes modifies the function, and if
1418 /// so, return true.
1420 bool FunctionPassManager::run(Function &F) {
1421 if (std::error_code EC = F.materialize())
1422 report_fatal_error("Error reading bitcode file: " + EC.message());
1427 /// doInitialization - Run all of the initializers for the function passes.
1429 bool FunctionPassManager::doInitialization() {
1430 return FPM->doInitialization(*M);
1433 /// doFinalization - Run all of the finalizers for the function passes.
1435 bool FunctionPassManager::doFinalization() {
1436 return FPM->doFinalization(*M);
1439 //===----------------------------------------------------------------------===//
1440 // FunctionPassManagerImpl implementation
1442 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1443 bool Changed = false;
1448 for (ImmutablePass *ImPass : getImmutablePasses())
1449 Changed |= ImPass->doInitialization(M);
1451 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1452 Changed |= getContainedManager(Index)->doInitialization(M);
1457 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1458 bool Changed = false;
1460 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1461 Changed |= getContainedManager(Index)->doFinalization(M);
1463 for (ImmutablePass *ImPass : getImmutablePasses())
1464 Changed |= ImPass->doFinalization(M);
1469 /// cleanup - After running all passes, clean up pass manager cache.
1470 void FPPassManager::cleanup() {
1471 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1472 FunctionPass *FP = getContainedPass(Index);
1473 AnalysisResolver *AR = FP->getResolver();
1474 assert(AR && "Analysis Resolver is not set");
1475 AR->clearAnalysisImpls();
1479 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1482 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1483 FPPassManager *FPPM = getContainedManager(Index);
1484 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1485 FPPM->getContainedPass(Index)->releaseMemory();
1491 // Execute all the passes managed by this top level manager.
1492 // Return true if any function is modified by a pass.
1493 bool FunctionPassManagerImpl::run(Function &F) {
1494 bool Changed = false;
1495 TimingInfo::createTheTimeInfo();
1497 initializeAllAnalysisInfo();
1498 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1499 Changed |= getContainedManager(Index)->runOnFunction(F);
1500 F.getContext().yield();
1503 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1504 getContainedManager(Index)->cleanup();
1510 //===----------------------------------------------------------------------===//
1511 // FPPassManager implementation
1513 char FPPassManager::ID = 0;
1514 /// Print passes managed by this manager
1515 void FPPassManager::dumpPassStructure(unsigned Offset) {
1516 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1517 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1518 FunctionPass *FP = getContainedPass(Index);
1519 FP->dumpPassStructure(Offset + 1);
1520 dumpLastUses(FP, Offset+1);
1525 /// Execute all of the passes scheduled for execution by invoking
1526 /// runOnFunction method. Keep track of whether any of the passes modifies
1527 /// the function, and if so, return true.
1528 bool FPPassManager::runOnFunction(Function &F) {
1529 if (F.isDeclaration())
1532 bool Changed = false;
1534 // Collect inherited analysis from Module level pass manager.
1535 populateInheritedAnalysis(TPM->activeStack);
1537 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1538 FunctionPass *FP = getContainedPass(Index);
1539 bool LocalChanged = false;
1541 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1542 dumpRequiredSet(FP);
1544 initializeAnalysisImpl(FP);
1547 PassManagerPrettyStackEntry X(FP, F);
1548 TimeRegion PassTimer(getPassTimer(FP));
1550 LocalChanged |= FP->runOnFunction(F);
1553 Changed |= LocalChanged;
1555 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1556 dumpPreservedSet(FP);
1559 verifyPreservedAnalysis(FP);
1560 removeNotPreservedAnalysis(FP);
1561 recordAvailableAnalysis(FP);
1562 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1567 bool FPPassManager::runOnModule(Module &M) {
1568 bool Changed = false;
1570 for (Function &F : M)
1571 Changed |= runOnFunction(F);
1576 bool FPPassManager::doInitialization(Module &M) {
1577 bool Changed = false;
1579 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1580 Changed |= getContainedPass(Index)->doInitialization(M);
1585 bool FPPassManager::doFinalization(Module &M) {
1586 bool Changed = false;
1588 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1589 Changed |= getContainedPass(Index)->doFinalization(M);
1594 //===----------------------------------------------------------------------===//
1595 // MPPassManager implementation
1597 /// Execute all of the passes scheduled for execution by invoking
1598 /// runOnModule method. Keep track of whether any of the passes modifies
1599 /// the module, and if so, return true.
1601 MPPassManager::runOnModule(Module &M) {
1602 bool Changed = false;
1604 // Initialize on-the-fly passes
1605 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1606 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1607 Changed |= FPP->doInitialization(M);
1610 // Initialize module passes
1611 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1612 Changed |= getContainedPass(Index)->doInitialization(M);
1614 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1615 ModulePass *MP = getContainedPass(Index);
1616 bool LocalChanged = false;
1618 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1619 dumpRequiredSet(MP);
1621 initializeAnalysisImpl(MP);
1624 PassManagerPrettyStackEntry X(MP, M);
1625 TimeRegion PassTimer(getPassTimer(MP));
1627 LocalChanged |= MP->runOnModule(M);
1630 Changed |= LocalChanged;
1632 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1633 M.getModuleIdentifier());
1634 dumpPreservedSet(MP);
1637 verifyPreservedAnalysis(MP);
1638 removeNotPreservedAnalysis(MP);
1639 recordAvailableAnalysis(MP);
1640 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1643 // Finalize module passes
1644 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1645 Changed |= getContainedPass(Index)->doFinalization(M);
1647 // Finalize on-the-fly passes
1648 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1649 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1650 // We don't know when is the last time an on-the-fly pass is run,
1651 // so we need to releaseMemory / finalize here
1652 FPP->releaseMemoryOnTheFly();
1653 Changed |= FPP->doFinalization(M);
1659 /// Add RequiredPass into list of lower level passes required by pass P.
1660 /// RequiredPass is run on the fly by Pass Manager when P requests it
1661 /// through getAnalysis interface.
1662 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1663 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1664 "Unable to handle Pass that requires lower level Analysis pass");
1665 assert((P->getPotentialPassManagerType() <
1666 RequiredPass->getPotentialPassManagerType()) &&
1667 "Unable to handle Pass that requires lower level Analysis pass");
1671 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1673 FPP = new FunctionPassManagerImpl();
1674 // FPP is the top level manager.
1675 FPP->setTopLevelManager(FPP);
1677 OnTheFlyManagers[P] = FPP;
1679 const PassInfo *RequiredPassPI =
1680 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1682 Pass *FoundPass = nullptr;
1683 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1685 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1688 FoundPass = RequiredPass;
1689 // This should be guaranteed to add RequiredPass to the passmanager given
1690 // that we checked for an available analysis above.
1691 FPP->add(RequiredPass);
1693 // Register P as the last user of FoundPass or RequiredPass.
1694 SmallVector<Pass *, 1> LU;
1695 LU.push_back(FoundPass);
1696 FPP->setLastUser(LU, P);
1699 /// Return function pass corresponding to PassInfo PI, that is
1700 /// required by module pass MP. Instantiate analysis pass, by using
1701 /// its runOnFunction() for function F.
1702 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1703 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1704 assert(FPP && "Unable to find on the fly pass");
1706 FPP->releaseMemoryOnTheFly();
1708 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1712 //===----------------------------------------------------------------------===//
1713 // PassManagerImpl implementation
1716 /// run - Execute all of the passes scheduled for execution. Keep track of
1717 /// whether any of the passes modifies the module, and if so, return true.
1718 bool PassManagerImpl::run(Module &M) {
1719 bool Changed = false;
1720 TimingInfo::createTheTimeInfo();
1725 for (ImmutablePass *ImPass : getImmutablePasses())
1726 Changed |= ImPass->doInitialization(M);
1728 initializeAllAnalysisInfo();
1729 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1730 Changed |= getContainedManager(Index)->runOnModule(M);
1731 M.getContext().yield();
1734 for (ImmutablePass *ImPass : getImmutablePasses())
1735 Changed |= ImPass->doFinalization(M);
1740 //===----------------------------------------------------------------------===//
1741 // PassManager implementation
1743 /// Create new pass manager
1744 PassManager::PassManager() {
1745 PM = new PassManagerImpl();
1746 // PM is the top level manager
1747 PM->setTopLevelManager(PM);
1750 PassManager::~PassManager() {
1754 void PassManager::add(Pass *P) {
1758 /// run - Execute all of the passes scheduled for execution. Keep track of
1759 /// whether any of the passes modifies the module, and if so, return true.
1760 bool PassManager::run(Module &M) {
1764 //===----------------------------------------------------------------------===//
1765 // TimingInfo implementation
1767 bool llvm::TimePassesIsEnabled = false;
1768 static cl::opt<bool,true>
1769 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1770 cl::desc("Time each pass, printing elapsed time for each on exit"));
1772 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1773 // a non-null value (if the -time-passes option is enabled) or it leaves it
1774 // null. It may be called multiple times.
1775 void TimingInfo::createTheTimeInfo() {
1776 if (!TimePassesIsEnabled || TheTimeInfo) return;
1778 // Constructed the first time this is called, iff -time-passes is enabled.
1779 // This guarantees that the object will be constructed before static globals,
1780 // thus it will be destroyed before them.
1781 static ManagedStatic<TimingInfo> TTI;
1782 TheTimeInfo = &*TTI;
1785 /// If TimingInfo is enabled then start pass timer.
1786 Timer *llvm::getPassTimer(Pass *P) {
1788 return TheTimeInfo->getPassTimer(P);
1792 //===----------------------------------------------------------------------===//
1793 // PMStack implementation
1796 // Pop Pass Manager from the stack and clear its analysis info.
1797 void PMStack::pop() {
1799 PMDataManager *Top = this->top();
1800 Top->initializeAnalysisInfo();
1805 // Push PM on the stack and set its top level manager.
1806 void PMStack::push(PMDataManager *PM) {
1807 assert(PM && "Unable to push. Pass Manager expected");
1808 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1810 if (!this->empty()) {
1811 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1812 && "pushing bad pass manager to PMStack");
1813 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1815 assert(TPM && "Unable to find top level manager");
1816 TPM->addIndirectPassManager(PM);
1817 PM->setTopLevelManager(TPM);
1818 PM->setDepth(this->top()->getDepth()+1);
1820 assert((PM->getPassManagerType() == PMT_ModulePassManager
1821 || PM->getPassManagerType() == PMT_FunctionPassManager)
1822 && "pushing bad pass manager to PMStack");
1829 // Dump content of the pass manager stack.
1830 void PMStack::dump() const {
1831 for (PMDataManager *Manager : S)
1832 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1838 /// Find appropriate Module Pass Manager in the PM Stack and
1839 /// add self into that manager.
1840 void ModulePass::assignPassManager(PMStack &PMS,
1841 PassManagerType PreferredType) {
1842 // Find Module Pass Manager
1843 while (!PMS.empty()) {
1844 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1845 if (TopPMType == PreferredType)
1846 break; // We found desired pass manager
1847 else if (TopPMType > PMT_ModulePassManager)
1848 PMS.pop(); // Pop children pass managers
1852 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1853 PMS.top()->add(this);
1856 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1857 /// in the PM Stack and add self into that manager.
1858 void FunctionPass::assignPassManager(PMStack &PMS,
1859 PassManagerType PreferredType) {
1861 // Find Function Pass Manager
1862 while (!PMS.empty()) {
1863 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1869 // Create new Function Pass Manager if needed.
1871 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1872 FPP = (FPPassManager *)PMS.top();
1874 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1875 PMDataManager *PMD = PMS.top();
1877 // [1] Create new Function Pass Manager
1878 FPP = new FPPassManager();
1879 FPP->populateInheritedAnalysis(PMS);
1881 // [2] Set up new manager's top level manager
1882 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1883 TPM->addIndirectPassManager(FPP);
1885 // [3] Assign manager to manage this new manager. This may create
1886 // and push new managers into PMS
1887 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1889 // [4] Push new manager into PMS
1893 // Assign FPP as the manager of this pass.
1897 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1898 /// in the PM Stack and add self into that manager.
1899 void BasicBlockPass::assignPassManager(PMStack &PMS,
1900 PassManagerType PreferredType) {
1903 // Basic Pass Manager is a leaf pass manager. It does not handle
1904 // any other pass manager.
1906 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1907 BBP = (BBPassManager *)PMS.top();
1909 // If leaf manager is not Basic Block Pass manager then create new
1910 // basic Block Pass manager.
1911 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1912 PMDataManager *PMD = PMS.top();
1914 // [1] Create new Basic Block Manager
1915 BBP = new BBPassManager();
1917 // [2] Set up new manager's top level manager
1918 // Basic Block Pass Manager does not live by itself
1919 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1920 TPM->addIndirectPassManager(BBP);
1922 // [3] Assign manager to manage this new manager. This may create
1923 // and push new managers into PMS
1924 BBP->assignPassManager(PMS, PreferredType);
1926 // [4] Push new manager into PMS
1930 // Assign BBP as the manager of this pass.
1934 PassManagerBase::~PassManagerBase() {}