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 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/LegacyPassManager.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/IR/IRPrintingPasses.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/IR/LegacyPassManagers.h"
19 #include "llvm/IR/LegacyPassNameParser.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/Chrono.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/Mutex.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
32 #include <unordered_set>
34 using namespace llvm::legacy;
36 // See PassManagers.h for Pass Manager infrastructure overview.
38 //===----------------------------------------------------------------------===//
39 // Pass debugging information. Often it is useful to find out what pass is
40 // running when a crash occurs in a utility. When this library is compiled with
41 // debugging on, a command line option (--debug-pass) is enabled that causes the
42 // pass name to be printed before it executes.
46 // Different debug levels that can be enabled...
48 Disabled, Arguments, Structure, Executions, Details
52 static cl::opt<enum PassDebugLevel>
53 PassDebugging("debug-pass", cl::Hidden,
54 cl::desc("Print PassManager debugging information"),
56 clEnumVal(Disabled , "disable debug output"),
57 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
58 clEnumVal(Structure , "print pass structure before run()"),
59 clEnumVal(Executions, "print pass name before it is executed"),
60 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 StringRef getPassName() const override { return "BasicBlock Pass Manager"; }
198 // Print passes managed by this manager
199 void dumpPassStructure(unsigned Offset) override {
200 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
201 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
202 BasicBlockPass *BP = getContainedPass(Index);
203 BP->dumpPassStructure(Offset + 1);
204 dumpLastUses(BP, Offset+1);
208 BasicBlockPass *getContainedPass(unsigned N) {
209 assert(N < PassVector.size() && "Pass number out of range!");
210 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
214 PassManagerType getPassManagerType() const override {
215 return PMT_BasicBlockPassManager;
219 char BBPassManager::ID = 0;
220 } // End anonymous namespace
224 //===----------------------------------------------------------------------===//
225 // FunctionPassManagerImpl
227 /// FunctionPassManagerImpl manages FPPassManagers
228 class FunctionPassManagerImpl : public Pass,
229 public PMDataManager,
230 public PMTopLevelManager {
231 virtual void anchor();
236 explicit FunctionPassManagerImpl() :
237 Pass(PT_PassManager, ID), PMDataManager(),
238 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
240 /// \copydoc FunctionPassManager::add()
245 /// createPrinterPass - Get a function printer pass.
246 Pass *createPrinterPass(raw_ostream &O,
247 const std::string &Banner) const override {
248 return createPrintFunctionPass(O, Banner);
251 // Prepare for running an on the fly pass, freeing memory if needed
252 // from a previous run.
253 void releaseMemoryOnTheFly();
255 /// run - Execute all of the passes scheduled for execution. Keep track of
256 /// whether any of the passes modifies the module, and if so, return true.
257 bool run(Function &F);
259 /// doInitialization - Run all of the initializers for the function passes.
261 bool doInitialization(Module &M) override;
263 /// doFinalization - Run all of the finalizers for the function passes.
265 bool doFinalization(Module &M) override;
268 PMDataManager *getAsPMDataManager() override { return this; }
269 Pass *getAsPass() override { return this; }
270 PassManagerType getTopLevelPassManagerType() override {
271 return PMT_FunctionPassManager;
274 /// Pass Manager itself does not invalidate any analysis info.
275 void getAnalysisUsage(AnalysisUsage &Info) const override {
276 Info.setPreservesAll();
279 FPPassManager *getContainedManager(unsigned N) {
280 assert(N < PassManagers.size() && "Pass number out of range!");
281 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
286 void FunctionPassManagerImpl::anchor() {}
288 char FunctionPassManagerImpl::ID = 0;
289 } // End of legacy namespace
290 } // End of llvm namespace
293 //===----------------------------------------------------------------------===//
296 /// MPPassManager manages ModulePasses and function pass managers.
297 /// It batches all Module passes and function pass managers together and
298 /// sequences them to process one module.
299 class MPPassManager : public Pass, public PMDataManager {
302 explicit MPPassManager() :
303 Pass(PT_PassManager, ID), PMDataManager() { }
305 // Delete on the fly managers.
306 ~MPPassManager() override {
307 for (auto &OnTheFlyManager : OnTheFlyManagers) {
308 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
313 /// createPrinterPass - Get a module printer pass.
314 Pass *createPrinterPass(raw_ostream &O,
315 const std::string &Banner) const override {
316 return createPrintModulePass(O, Banner);
319 /// run - Execute all of the passes scheduled for execution. Keep track of
320 /// whether any of the passes modifies the module, and if so, return true.
321 bool runOnModule(Module &M);
323 using llvm::Pass::doInitialization;
324 using llvm::Pass::doFinalization;
326 /// Pass Manager itself does not invalidate any analysis info.
327 void getAnalysisUsage(AnalysisUsage &Info) const override {
328 Info.setPreservesAll();
331 /// Add RequiredPass into list of lower level passes required by pass P.
332 /// RequiredPass is run on the fly by Pass Manager when P requests it
333 /// through getAnalysis interface.
334 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
336 /// Return function pass corresponding to PassInfo PI, that is
337 /// required by module pass MP. Instantiate analysis pass, by using
338 /// its runOnFunction() for function F.
339 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
341 StringRef getPassName() const override { return "Module Pass Manager"; }
343 PMDataManager *getAsPMDataManager() override { return this; }
344 Pass *getAsPass() override { return this; }
346 // Print passes managed by this manager
347 void dumpPassStructure(unsigned Offset) override {
348 dbgs().indent(Offset*2) << "ModulePass Manager\n";
349 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
350 ModulePass *MP = getContainedPass(Index);
351 MP->dumpPassStructure(Offset + 1);
352 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
353 OnTheFlyManagers.find(MP);
354 if (I != OnTheFlyManagers.end())
355 I->second->dumpPassStructure(Offset + 2);
356 dumpLastUses(MP, Offset+1);
360 ModulePass *getContainedPass(unsigned N) {
361 assert(N < PassVector.size() && "Pass number out of range!");
362 return static_cast<ModulePass *>(PassVector[N]);
365 PassManagerType getPassManagerType() const override {
366 return PMT_ModulePassManager;
370 /// Collection of on the fly FPPassManagers. These managers manage
371 /// function passes that are required by module passes.
372 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
375 char MPPassManager::ID = 0;
376 } // End anonymous namespace
380 //===----------------------------------------------------------------------===//
384 /// PassManagerImpl manages MPPassManagers
385 class PassManagerImpl : public Pass,
386 public PMDataManager,
387 public PMTopLevelManager {
388 virtual void anchor();
392 explicit PassManagerImpl() :
393 Pass(PT_PassManager, ID), PMDataManager(),
394 PMTopLevelManager(new MPPassManager()) {}
396 /// \copydoc PassManager::add()
401 /// createPrinterPass - Get a module printer pass.
402 Pass *createPrinterPass(raw_ostream &O,
403 const std::string &Banner) const override {
404 return createPrintModulePass(O, Banner);
407 /// run - Execute all of the passes scheduled for execution. Keep track of
408 /// whether any of the passes modifies the module, and if so, return true.
411 using llvm::Pass::doInitialization;
412 using llvm::Pass::doFinalization;
414 /// Pass Manager itself does not invalidate any analysis info.
415 void getAnalysisUsage(AnalysisUsage &Info) const override {
416 Info.setPreservesAll();
419 PMDataManager *getAsPMDataManager() override { return this; }
420 Pass *getAsPass() override { return this; }
421 PassManagerType getTopLevelPassManagerType() override {
422 return PMT_ModulePassManager;
425 MPPassManager *getContainedManager(unsigned N) {
426 assert(N < PassManagers.size() && "Pass number out of range!");
427 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
432 void PassManagerImpl::anchor() {}
434 char PassManagerImpl::ID = 0;
435 } // End of legacy namespace
436 } // End of llvm namespace
440 //===----------------------------------------------------------------------===//
441 /// TimingInfo Class - This class is used to calculate information about the
442 /// amount of time each pass takes to execute. This only happens when
443 /// -time-passes is enabled on the command line.
446 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
449 DenseMap<Pass*, Timer*> TimingData;
452 // Use 'create' member to get this.
453 TimingInfo() : TG("pass", "... Pass execution timing report ...") {}
455 // TimingDtor - Print out information about timing information
457 // Delete all of the timers, which accumulate their info into the
459 for (auto &I : TimingData)
461 // TimerGroup is deleted next, printing the report.
464 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
465 // to a non-null value (if the -time-passes option is enabled) or it leaves it
466 // null. It may be called multiple times.
467 static void createTheTimeInfo();
469 // print - Prints out timing information and then resets the timers.
471 TG.print(*CreateInfoOutputFile());
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 StringRef PassName = P->getPassName();
483 T = new Timer(PassName, PassName, TG);
489 } // End of anon namespace
491 static TimingInfo *TheTimeInfo;
493 //===----------------------------------------------------------------------===//
494 // PMTopLevelManager implementation
496 /// Initialize top level manager. Create first pass manager.
497 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
498 PMDM->setTopLevelManager(this);
499 addPassManager(PMDM);
500 activeStack.push(PMDM);
503 /// Set pass P as the last user of the given analysis passes.
505 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
507 if (P->getResolver())
508 PDepth = P->getResolver()->getPMDataManager().getDepth();
510 for (Pass *AP : AnalysisPasses) {
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 (AnalysisID ID : IDs) {
522 Pass *AnalysisPass = findAnalysisPass(ID);
523 assert(AnalysisPass && "Expected analysis pass to exist.");
524 AnalysisResolver *AR = AnalysisPass->getResolver();
525 assert(AR && "Expected analysis resolver to exist.");
526 unsigned APDepth = AR->getPMDataManager().getDepth();
528 if (PDepth == APDepth)
529 LastUses.push_back(AnalysisPass);
530 else if (PDepth > APDepth)
531 LastPMUses.push_back(AnalysisPass);
534 setLastUser(LastUses, P);
536 // If this pass has a corresponding pass manager, push higher level
537 // analysis to this pass manager.
538 if (P->getResolver())
539 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
542 // If AP is the last user of other passes then make P last user of
544 for (auto LU : LastUser) {
546 // DenseMap iterator is not invalidated here because
547 // this is just updating existing entries.
548 LastUser[LU.first] = P;
553 /// Collect passes whose last user is P
554 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
556 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
557 InversedLastUser.find(P);
558 if (DMI == InversedLastUser.end())
561 SmallPtrSet<Pass *, 8> &LU = DMI->second;
562 for (Pass *LUP : LU) {
563 LastUses.push_back(LUP);
568 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
569 AnalysisUsage *AnUsage = nullptr;
570 auto DMI = AnUsageMap.find(P);
571 if (DMI != AnUsageMap.end())
572 AnUsage = DMI->second;
574 // Look up the analysis usage from the pass instance (different instances
575 // of the same pass can produce different results), but unique the
576 // resulting object to reduce memory usage. This helps to greatly reduce
577 // memory usage when we have many instances of only a few pass types
578 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
581 P->getAnalysisUsage(AU);
583 AUFoldingSetNode* Node = nullptr;
585 AUFoldingSetNode::Profile(ID, AU);
587 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
590 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
591 UniqueAnalysisUsages.InsertNode(Node, IP);
593 assert(Node && "cached analysis usage must be non null");
595 AnUsageMap[P] = &Node->AU;
601 /// Schedule pass P for execution. Make sure that passes required by
602 /// P are run before P is run. Update analysis info maintained by
603 /// the manager. Remove dead passes. This is a recursive function.
604 void PMTopLevelManager::schedulePass(Pass *P) {
606 // TODO : Allocate function manager for this pass, other wise required set
607 // may be inserted into previous function manager
609 // Give pass a chance to prepare the stage.
610 P->preparePassManager(activeStack);
612 // If P is an analysis pass and it is available then do not
613 // generate the analysis again. Stale analysis info should not be
614 // available at this point.
615 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
616 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
621 AnalysisUsage *AnUsage = findAnalysisUsage(P);
623 bool checkAnalysis = true;
624 while (checkAnalysis) {
625 checkAnalysis = false;
627 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
628 for (const AnalysisID ID : RequiredSet) {
630 Pass *AnalysisPass = findAnalysisPass(ID);
632 const PassInfo *PI = findAnalysisPassInfo(ID);
635 // Pass P is not in the global PassRegistry
636 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
637 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
638 dbgs() << "Required Passes:" << "\n";
639 for (const AnalysisID ID2 : RequiredSet) {
642 Pass *AnalysisPass2 = findAnalysisPass(ID2);
644 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
646 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
647 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
648 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
653 assert(PI && "Expected required passes to be initialized");
654 AnalysisPass = PI->createPass();
655 if (P->getPotentialPassManagerType () ==
656 AnalysisPass->getPotentialPassManagerType())
657 // Schedule analysis pass that is managed by the same pass manager.
658 schedulePass(AnalysisPass);
659 else if (P->getPotentialPassManagerType () >
660 AnalysisPass->getPotentialPassManagerType()) {
661 // Schedule analysis pass that is managed by a new manager.
662 schedulePass(AnalysisPass);
663 // Recheck analysis passes to ensure that required analyses that
664 // are already checked are still available.
665 checkAnalysis = true;
667 // Do not schedule this analysis. Lower level analysis
668 // passes are run on the fly.
674 // Now all required passes are available.
675 if (ImmutablePass *IP = P->getAsImmutablePass()) {
676 // P is a immutable pass and it will be managed by this
677 // top level manager. Set up analysis resolver to connect them.
678 PMDataManager *DM = getAsPMDataManager();
679 AnalysisResolver *AR = new AnalysisResolver(*DM);
681 DM->initializeAnalysisImpl(P);
682 addImmutablePass(IP);
683 DM->recordAvailableAnalysis(IP);
687 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
688 Pass *PP = P->createPrinterPass(
689 dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
690 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
693 // Add the requested pass to the best available pass manager.
694 P->assignPassManager(activeStack, getTopLevelPassManagerType());
696 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
697 Pass *PP = P->createPrinterPass(
698 dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
699 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
703 /// Find the pass that implements Analysis AID. Search immutable
704 /// passes and all pass managers. If desired pass is not found
705 /// then return NULL.
706 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
707 // For immutable passes we have a direct mapping from ID to pass, so check
709 if (Pass *P = ImmutablePassMap.lookup(AID))
712 // Check pass managers
713 for (PMDataManager *PassManager : PassManagers)
714 if (Pass *P = PassManager->findAnalysisPass(AID, false))
717 // Check other pass managers
718 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
719 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
725 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
726 const PassInfo *&PI = AnalysisPassInfos[AID];
728 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
730 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
731 "The pass info pointer changed for an analysis ID!");
736 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
738 ImmutablePasses.push_back(P);
740 // Add this pass to the map from its analysis ID. We clobber any prior runs
741 // of the pass in the map so that the last one added is the one found when
743 AnalysisID AID = P->getPassID();
744 ImmutablePassMap[AID] = P;
746 // Also add any interfaces implemented by the immutable pass to the map for
748 const PassInfo *PassInf = findAnalysisPassInfo(AID);
749 assert(PassInf && "Expected all immutable passes to be initialized");
750 for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
751 ImmutablePassMap[ImmPI->getTypeInfo()] = P;
754 // Print passes managed by this top level manager.
755 void PMTopLevelManager::dumpPasses() const {
757 if (PassDebugging < Structure)
760 // Print out the immutable passes
761 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
762 ImmutablePasses[i]->dumpPassStructure(0);
765 // Every class that derives from PMDataManager also derives from Pass
766 // (sometimes indirectly), but there's no inheritance relationship
767 // between PMDataManager and Pass, so we have to getAsPass to get
768 // from a PMDataManager* to a Pass*.
769 for (PMDataManager *Manager : PassManagers)
770 Manager->getAsPass()->dumpPassStructure(1);
773 void PMTopLevelManager::dumpArguments() const {
775 if (PassDebugging < Arguments)
778 dbgs() << "Pass Arguments: ";
779 for (ImmutablePass *P : ImmutablePasses)
780 if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
781 assert(PI && "Expected all immutable passes to be initialized");
782 if (!PI->isAnalysisGroup())
783 dbgs() << " -" << PI->getPassArgument();
785 for (PMDataManager *PM : PassManagers)
786 PM->dumpPassArguments();
790 void PMTopLevelManager::initializeAllAnalysisInfo() {
791 for (PMDataManager *PM : PassManagers)
792 PM->initializeAnalysisInfo();
794 // Initailize other pass managers
795 for (PMDataManager *IPM : IndirectPassManagers)
796 IPM->initializeAnalysisInfo();
798 for (auto LU : LastUser) {
799 SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
805 PMTopLevelManager::~PMTopLevelManager() {
806 for (PMDataManager *PM : PassManagers)
809 for (ImmutablePass *P : ImmutablePasses)
813 //===----------------------------------------------------------------------===//
814 // PMDataManager implementation
816 /// Augement AvailableAnalysis by adding analysis made available by pass P.
817 void PMDataManager::recordAvailableAnalysis(Pass *P) {
818 AnalysisID PI = P->getPassID();
820 AvailableAnalysis[PI] = P;
822 assert(!AvailableAnalysis.empty());
824 // This pass is the current implementation of all of the interfaces it
825 // implements as well.
826 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
828 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
829 for (unsigned i = 0, e = II.size(); i != e; ++i)
830 AvailableAnalysis[II[i]->getTypeInfo()] = P;
833 // Return true if P preserves high level analysis used by other
834 // passes managed by this manager
835 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
836 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
837 if (AnUsage->getPreservesAll())
840 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
841 for (Pass *P1 : HigherLevelAnalysis) {
842 if (P1->getAsImmutablePass() == nullptr &&
843 !is_contained(PreservedSet, P1->getPassID()))
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 (AnalysisID AID : PreservedSet) {
861 if (Pass *AP = findAnalysisPass(AID, true)) {
862 TimeRegion PassTimer(getPassTimer(AP));
863 AP->verifyAnalysis();
868 /// Remove Analysis not preserved by Pass P
869 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
870 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
871 if (AnUsage->getPreservesAll())
874 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
875 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
876 E = AvailableAnalysis.end(); I != E; ) {
877 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
878 if (Info->second->getAsImmutablePass() == nullptr &&
879 !is_contained(PreservedSet, Info->first)) {
880 // Remove this analysis
881 if (PassDebugging >= Details) {
882 Pass *S = Info->second;
883 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
884 dbgs() << S->getPassName() << "'\n";
886 AvailableAnalysis.erase(Info);
890 // Check inherited analysis also. If P is not preserving analysis
891 // provided by parent manager then remove it here.
892 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
894 if (!InheritedAnalysis[Index])
897 for (DenseMap<AnalysisID, Pass*>::iterator
898 I = InheritedAnalysis[Index]->begin(),
899 E = InheritedAnalysis[Index]->end(); I != E; ) {
900 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
901 if (Info->second->getAsImmutablePass() == nullptr &&
902 !is_contained(PreservedSet, Info->first)) {
903 // Remove this analysis
904 if (PassDebugging >= Details) {
905 Pass *S = Info->second;
906 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
907 dbgs() << S->getPassName() << "'\n";
909 InheritedAnalysis[Index]->erase(Info);
915 /// Remove analysis passes that are not used any longer
916 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
917 enum PassDebuggingString DBG_STR) {
919 SmallVector<Pass *, 12> DeadPasses;
921 // If this is a on the fly manager then it does not have TPM.
925 TPM->collectLastUses(DeadPasses, P);
927 if (PassDebugging >= Details && !DeadPasses.empty()) {
928 dbgs() << " -*- '" << P->getPassName();
929 dbgs() << "' is the last user of following pass instances.";
930 dbgs() << " Free these instances\n";
933 for (Pass *P : DeadPasses)
934 freePass(P, Msg, DBG_STR);
937 void PMDataManager::freePass(Pass *P, StringRef Msg,
938 enum PassDebuggingString DBG_STR) {
939 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
942 // If the pass crashes releasing memory, remember this.
943 PassManagerPrettyStackEntry X(P);
944 TimeRegion PassTimer(getPassTimer(P));
949 AnalysisID PI = P->getPassID();
950 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
951 // Remove the pass itself (if it is not already removed).
952 AvailableAnalysis.erase(PI);
954 // Remove all interfaces this pass implements, for which it is also
955 // listed as the available implementation.
956 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
957 for (unsigned i = 0, e = II.size(); i != e; ++i) {
958 DenseMap<AnalysisID, Pass*>::iterator Pos =
959 AvailableAnalysis.find(II[i]->getTypeInfo());
960 if (Pos != AvailableAnalysis.end() && Pos->second == P)
961 AvailableAnalysis.erase(Pos);
966 /// Add pass P into the PassVector. Update
967 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
968 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
969 // This manager is going to manage pass P. Set up analysis resolver
971 AnalysisResolver *AR = new AnalysisResolver(*this);
974 // If a FunctionPass F is the last user of ModulePass info M
975 // then the F's manager, not F, records itself as a last user of M.
976 SmallVector<Pass *, 12> TransferLastUses;
978 if (!ProcessAnalysis) {
980 PassVector.push_back(P);
984 // At the moment, this pass is the last user of all required passes.
985 SmallVector<Pass *, 12> LastUses;
986 SmallVector<Pass *, 8> UsedPasses;
987 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
989 unsigned PDepth = this->getDepth();
991 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
992 for (Pass *PUsed : UsedPasses) {
995 assert(PUsed->getResolver() && "Analysis Resolver is not set");
996 PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
997 RDepth = DM.getDepth();
999 if (PDepth == RDepth)
1000 LastUses.push_back(PUsed);
1001 else if (PDepth > RDepth) {
1002 // Let the parent claim responsibility of last use
1003 TransferLastUses.push_back(PUsed);
1004 // Keep track of higher level analysis used by this manager.
1005 HigherLevelAnalysis.push_back(PUsed);
1007 llvm_unreachable("Unable to accommodate Used Pass");
1010 // Set P as P's last user until someone starts using P.
1011 // However, if P is a Pass Manager then it does not need
1012 // to record its last user.
1013 if (!P->getAsPMDataManager())
1014 LastUses.push_back(P);
1015 TPM->setLastUser(LastUses, P);
1017 if (!TransferLastUses.empty()) {
1018 Pass *My_PM = getAsPass();
1019 TPM->setLastUser(TransferLastUses, My_PM);
1020 TransferLastUses.clear();
1023 // Now, take care of required analyses that are not available.
1024 for (AnalysisID ID : ReqAnalysisNotAvailable) {
1025 const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1026 Pass *AnalysisPass = PI->createPass();
1027 this->addLowerLevelRequiredPass(P, AnalysisPass);
1030 // Take a note of analysis required and made available by this pass.
1031 // Remove the analysis not preserved by this pass
1032 removeNotPreservedAnalysis(P);
1033 recordAvailableAnalysis(P);
1036 PassVector.push_back(P);
1040 /// Populate UP with analysis pass that are used or required by
1041 /// pass P and are available. Populate RP_NotAvail with analysis
1042 /// pass that are required by pass P but are not available.
1043 void PMDataManager::collectRequiredAndUsedAnalyses(
1044 SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1046 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1048 for (const auto &UsedID : AnUsage->getUsedSet())
1049 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1050 UP.push_back(AnalysisPass);
1052 for (const auto &RequiredID : AnUsage->getRequiredSet())
1053 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1054 UP.push_back(AnalysisPass);
1056 RP_NotAvail.push_back(RequiredID);
1058 for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1059 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1060 UP.push_back(AnalysisPass);
1062 RP_NotAvail.push_back(RequiredID);
1065 // All Required analyses should be available to the pass as it runs! Here
1066 // we fill in the AnalysisImpls member of the pass so that it can
1067 // successfully use the getAnalysis() method to retrieve the
1068 // implementations it needs.
1070 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1071 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1073 for (const AnalysisID ID : AnUsage->getRequiredSet()) {
1074 Pass *Impl = findAnalysisPass(ID, true);
1076 // This may be analysis pass that is initialized on the fly.
1077 // If that is not the case then it will raise an assert when it is used.
1079 AnalysisResolver *AR = P->getResolver();
1080 assert(AR && "Analysis Resolver is not set");
1081 AR->addAnalysisImplsPair(ID, Impl);
1085 /// Find the pass that implements Analysis AID. If desired pass is not found
1086 /// then return NULL.
1087 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1089 // Check if AvailableAnalysis map has one entry.
1090 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1092 if (I != AvailableAnalysis.end())
1095 // Search Parents through TopLevelManager
1097 return TPM->findAnalysisPass(AID);
1102 // Print list of passes that are last used by P.
1103 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1105 SmallVector<Pass *, 12> LUses;
1107 // If this is a on the fly manager then it does not have TPM.
1111 TPM->collectLastUses(LUses, P);
1113 for (Pass *P : LUses) {
1114 dbgs() << "--" << std::string(Offset*2, ' ');
1115 P->dumpPassStructure(0);
1119 void PMDataManager::dumpPassArguments() const {
1120 for (Pass *P : PassVector) {
1121 if (PMDataManager *PMD = P->getAsPMDataManager())
1122 PMD->dumpPassArguments();
1124 if (const PassInfo *PI =
1125 TPM->findAnalysisPassInfo(P->getPassID()))
1126 if (!PI->isAnalysisGroup())
1127 dbgs() << " -" << PI->getPassArgument();
1131 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1132 enum PassDebuggingString S2,
1134 if (PassDebugging < Executions)
1136 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1137 << std::string(getDepth() * 2 + 1, ' ');
1140 dbgs() << "Executing Pass '" << P->getPassName();
1142 case MODIFICATION_MSG:
1143 dbgs() << "Made Modification '" << P->getPassName();
1146 dbgs() << " Freeing Pass '" << P->getPassName();
1152 case ON_BASICBLOCK_MSG:
1153 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1155 case ON_FUNCTION_MSG:
1156 dbgs() << "' on Function '" << Msg << "'...\n";
1159 dbgs() << "' on Module '" << Msg << "'...\n";
1162 dbgs() << "' on Region '" << Msg << "'...\n";
1165 dbgs() << "' on Loop '" << Msg << "'...\n";
1168 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1175 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1176 if (PassDebugging < Details)
1179 AnalysisUsage analysisUsage;
1180 P->getAnalysisUsage(analysisUsage);
1181 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1184 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1185 if (PassDebugging < Details)
1188 AnalysisUsage analysisUsage;
1189 P->getAnalysisUsage(analysisUsage);
1190 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1193 void PMDataManager::dumpUsedSet(const Pass *P) const {
1194 if (PassDebugging < Details)
1197 AnalysisUsage analysisUsage;
1198 P->getAnalysisUsage(analysisUsage);
1199 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1202 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1203 const AnalysisUsage::VectorType &Set) const {
1204 assert(PassDebugging >= Details);
1207 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1208 for (unsigned i = 0; i != Set.size(); ++i) {
1209 if (i) dbgs() << ',';
1210 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1212 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1214 dbgs() << " Uninitialized Pass";
1217 dbgs() << ' ' << PInf->getPassName();
1222 /// Add RequiredPass into list of lower level passes required by pass P.
1223 /// RequiredPass is run on the fly by Pass Manager when P requests it
1224 /// through getAnalysis interface.
1225 /// This should be handled by specific pass manager.
1226 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1228 TPM->dumpArguments();
1232 // Module Level pass may required Function Level analysis info
1233 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1234 // to provide this on demand. In that case, in Pass manager terminology,
1235 // module level pass is requiring lower level analysis info managed by
1236 // lower level pass manager.
1238 // When Pass manager is not able to order required analysis info, Pass manager
1239 // checks whether any lower level manager will be able to provide this
1240 // analysis info on demand or not.
1242 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1243 dbgs() << "' required by '" << P->getPassName() << "'\n";
1245 llvm_unreachable("Unable to schedule pass");
1248 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1249 llvm_unreachable("Unable to find on the fly pass");
1253 PMDataManager::~PMDataManager() {
1254 for (Pass *P : PassVector)
1258 //===----------------------------------------------------------------------===//
1259 // NOTE: Is this the right place to define this method ?
1260 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1261 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1262 return PM.findAnalysisPass(ID, dir);
1265 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1267 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1270 //===----------------------------------------------------------------------===//
1271 // BBPassManager implementation
1273 /// Execute all of the passes scheduled for execution by invoking
1274 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1275 /// the function, and if so, return true.
1276 bool BBPassManager::runOnFunction(Function &F) {
1277 if (F.isDeclaration())
1280 bool Changed = doInitialization(F);
1282 for (BasicBlock &BB : F)
1283 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1284 BasicBlockPass *BP = getContainedPass(Index);
1285 bool LocalChanged = false;
1287 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, BB.getName());
1288 dumpRequiredSet(BP);
1290 initializeAnalysisImpl(BP);
1293 // If the pass crashes, remember this.
1294 PassManagerPrettyStackEntry X(BP, BB);
1295 TimeRegion PassTimer(getPassTimer(BP));
1297 LocalChanged |= BP->runOnBasicBlock(BB);
1300 Changed |= LocalChanged;
1302 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1304 dumpPreservedSet(BP);
1307 verifyPreservedAnalysis(BP);
1308 removeNotPreservedAnalysis(BP);
1309 recordAvailableAnalysis(BP);
1310 removeDeadPasses(BP, BB.getName(), ON_BASICBLOCK_MSG);
1313 return doFinalization(F) || Changed;
1316 // Implement doInitialization and doFinalization
1317 bool BBPassManager::doInitialization(Module &M) {
1318 bool Changed = false;
1320 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1321 Changed |= getContainedPass(Index)->doInitialization(M);
1326 bool BBPassManager::doFinalization(Module &M) {
1327 bool Changed = false;
1329 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1330 Changed |= getContainedPass(Index)->doFinalization(M);
1335 bool BBPassManager::doInitialization(Function &F) {
1336 bool Changed = false;
1338 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1339 BasicBlockPass *BP = getContainedPass(Index);
1340 Changed |= BP->doInitialization(F);
1346 bool BBPassManager::doFinalization(Function &F) {
1347 bool Changed = false;
1349 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1350 BasicBlockPass *BP = getContainedPass(Index);
1351 Changed |= BP->doFinalization(F);
1358 //===----------------------------------------------------------------------===//
1359 // FunctionPassManager implementation
1361 /// Create new Function pass manager
1362 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1363 FPM = new FunctionPassManagerImpl();
1364 // FPM is the top level manager.
1365 FPM->setTopLevelManager(FPM);
1367 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1368 FPM->setResolver(AR);
1371 FunctionPassManager::~FunctionPassManager() {
1375 void FunctionPassManager::add(Pass *P) {
1379 /// run - Execute all of the passes scheduled for execution. Keep
1380 /// track of whether any of the passes modifies the function, and if
1381 /// so, return true.
1383 bool FunctionPassManager::run(Function &F) {
1384 handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1385 report_fatal_error("Error reading bitcode file: " + EIB.message());
1391 /// doInitialization - Run all of the initializers for the function passes.
1393 bool FunctionPassManager::doInitialization() {
1394 return FPM->doInitialization(*M);
1397 /// doFinalization - Run all of the finalizers for the function passes.
1399 bool FunctionPassManager::doFinalization() {
1400 return FPM->doFinalization(*M);
1403 //===----------------------------------------------------------------------===//
1404 // FunctionPassManagerImpl implementation
1406 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1407 bool Changed = false;
1412 for (ImmutablePass *ImPass : getImmutablePasses())
1413 Changed |= ImPass->doInitialization(M);
1415 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1416 Changed |= getContainedManager(Index)->doInitialization(M);
1421 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1422 bool Changed = false;
1424 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1425 Changed |= getContainedManager(Index)->doFinalization(M);
1427 for (ImmutablePass *ImPass : getImmutablePasses())
1428 Changed |= ImPass->doFinalization(M);
1433 /// cleanup - After running all passes, clean up pass manager cache.
1434 void FPPassManager::cleanup() {
1435 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1436 FunctionPass *FP = getContainedPass(Index);
1437 AnalysisResolver *AR = FP->getResolver();
1438 assert(AR && "Analysis Resolver is not set");
1439 AR->clearAnalysisImpls();
1443 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1446 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1447 FPPassManager *FPPM = getContainedManager(Index);
1448 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1449 FPPM->getContainedPass(Index)->releaseMemory();
1455 // Execute all the passes managed by this top level manager.
1456 // Return true if any function is modified by a pass.
1457 bool FunctionPassManagerImpl::run(Function &F) {
1458 bool Changed = false;
1459 TimingInfo::createTheTimeInfo();
1461 initializeAllAnalysisInfo();
1462 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1463 Changed |= getContainedManager(Index)->runOnFunction(F);
1464 F.getContext().yield();
1467 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1468 getContainedManager(Index)->cleanup();
1474 //===----------------------------------------------------------------------===//
1475 // FPPassManager implementation
1477 char FPPassManager::ID = 0;
1478 /// Print passes managed by this manager
1479 void FPPassManager::dumpPassStructure(unsigned Offset) {
1480 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1481 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1482 FunctionPass *FP = getContainedPass(Index);
1483 FP->dumpPassStructure(Offset + 1);
1484 dumpLastUses(FP, Offset+1);
1489 /// Execute all of the passes scheduled for execution by invoking
1490 /// runOnFunction method. Keep track of whether any of the passes modifies
1491 /// the function, and if so, return true.
1492 bool FPPassManager::runOnFunction(Function &F) {
1493 if (F.isDeclaration())
1496 bool Changed = false;
1498 // Collect inherited analysis from Module level pass manager.
1499 populateInheritedAnalysis(TPM->activeStack);
1501 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1502 FunctionPass *FP = getContainedPass(Index);
1503 bool LocalChanged = false;
1505 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1506 dumpRequiredSet(FP);
1508 initializeAnalysisImpl(FP);
1511 PassManagerPrettyStackEntry X(FP, F);
1512 TimeRegion PassTimer(getPassTimer(FP));
1514 LocalChanged |= FP->runOnFunction(F);
1517 Changed |= LocalChanged;
1519 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1520 dumpPreservedSet(FP);
1523 verifyPreservedAnalysis(FP);
1524 removeNotPreservedAnalysis(FP);
1525 recordAvailableAnalysis(FP);
1526 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1531 bool FPPassManager::runOnModule(Module &M) {
1532 bool Changed = false;
1534 for (Function &F : M)
1535 Changed |= runOnFunction(F);
1540 bool FPPassManager::doInitialization(Module &M) {
1541 bool Changed = false;
1543 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1544 Changed |= getContainedPass(Index)->doInitialization(M);
1549 bool FPPassManager::doFinalization(Module &M) {
1550 bool Changed = false;
1552 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1553 Changed |= getContainedPass(Index)->doFinalization(M);
1558 //===----------------------------------------------------------------------===//
1559 // MPPassManager implementation
1561 /// Execute all of the passes scheduled for execution by invoking
1562 /// runOnModule method. Keep track of whether any of the passes modifies
1563 /// the module, and if so, return true.
1565 MPPassManager::runOnModule(Module &M) {
1566 bool Changed = false;
1568 // Initialize on-the-fly passes
1569 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1570 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1571 Changed |= FPP->doInitialization(M);
1574 // Initialize module passes
1575 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1576 Changed |= getContainedPass(Index)->doInitialization(M);
1578 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1579 ModulePass *MP = getContainedPass(Index);
1580 bool LocalChanged = false;
1582 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1583 dumpRequiredSet(MP);
1585 initializeAnalysisImpl(MP);
1588 PassManagerPrettyStackEntry X(MP, M);
1589 TimeRegion PassTimer(getPassTimer(MP));
1591 LocalChanged |= MP->runOnModule(M);
1594 Changed |= LocalChanged;
1596 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1597 M.getModuleIdentifier());
1598 dumpPreservedSet(MP);
1601 verifyPreservedAnalysis(MP);
1602 removeNotPreservedAnalysis(MP);
1603 recordAvailableAnalysis(MP);
1604 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1607 // Finalize module passes
1608 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1609 Changed |= getContainedPass(Index)->doFinalization(M);
1611 // Finalize on-the-fly passes
1612 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1613 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1614 // We don't know when is the last time an on-the-fly pass is run,
1615 // so we need to releaseMemory / finalize here
1616 FPP->releaseMemoryOnTheFly();
1617 Changed |= FPP->doFinalization(M);
1623 /// Add RequiredPass into list of lower level passes required by pass P.
1624 /// RequiredPass is run on the fly by Pass Manager when P requests it
1625 /// through getAnalysis interface.
1626 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1627 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1628 "Unable to handle Pass that requires lower level Analysis pass");
1629 assert((P->getPotentialPassManagerType() <
1630 RequiredPass->getPotentialPassManagerType()) &&
1631 "Unable to handle Pass that requires lower level Analysis pass");
1635 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1637 FPP = new FunctionPassManagerImpl();
1638 // FPP is the top level manager.
1639 FPP->setTopLevelManager(FPP);
1641 OnTheFlyManagers[P] = FPP;
1643 const PassInfo *RequiredPassPI =
1644 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1646 Pass *FoundPass = nullptr;
1647 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1649 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1652 FoundPass = RequiredPass;
1653 // This should be guaranteed to add RequiredPass to the passmanager given
1654 // that we checked for an available analysis above.
1655 FPP->add(RequiredPass);
1657 // Register P as the last user of FoundPass or RequiredPass.
1658 SmallVector<Pass *, 1> LU;
1659 LU.push_back(FoundPass);
1660 FPP->setLastUser(LU, P);
1663 /// Return function pass corresponding to PassInfo PI, that is
1664 /// required by module pass MP. Instantiate analysis pass, by using
1665 /// its runOnFunction() for function F.
1666 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1667 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1668 assert(FPP && "Unable to find on the fly pass");
1670 FPP->releaseMemoryOnTheFly();
1672 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1676 //===----------------------------------------------------------------------===//
1677 // PassManagerImpl implementation
1680 /// run - Execute all of the passes scheduled for execution. Keep track of
1681 /// whether any of the passes modifies the module, and if so, return true.
1682 bool PassManagerImpl::run(Module &M) {
1683 bool Changed = false;
1684 TimingInfo::createTheTimeInfo();
1689 for (ImmutablePass *ImPass : getImmutablePasses())
1690 Changed |= ImPass->doInitialization(M);
1692 initializeAllAnalysisInfo();
1693 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1694 Changed |= getContainedManager(Index)->runOnModule(M);
1695 M.getContext().yield();
1698 for (ImmutablePass *ImPass : getImmutablePasses())
1699 Changed |= ImPass->doFinalization(M);
1704 //===----------------------------------------------------------------------===//
1705 // PassManager implementation
1707 /// Create new pass manager
1708 PassManager::PassManager() {
1709 PM = new PassManagerImpl();
1710 // PM is the top level manager
1711 PM->setTopLevelManager(PM);
1714 PassManager::~PassManager() {
1718 void PassManager::add(Pass *P) {
1722 /// run - Execute all of the passes scheduled for execution. Keep track of
1723 /// whether any of the passes modifies the module, and if so, return true.
1724 bool PassManager::run(Module &M) {
1728 //===----------------------------------------------------------------------===//
1729 // TimingInfo implementation
1731 bool llvm::TimePassesIsEnabled = false;
1732 static cl::opt<bool,true>
1733 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1734 cl::desc("Time each pass, printing elapsed time for each on exit"));
1736 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1737 // a non-null value (if the -time-passes option is enabled) or it leaves it
1738 // null. It may be called multiple times.
1739 void TimingInfo::createTheTimeInfo() {
1740 if (!TimePassesIsEnabled || TheTimeInfo) return;
1742 // Constructed the first time this is called, iff -time-passes is enabled.
1743 // This guarantees that the object will be constructed before static globals,
1744 // thus it will be destroyed before them.
1745 static ManagedStatic<TimingInfo> TTI;
1746 TheTimeInfo = &*TTI;
1749 /// If TimingInfo is enabled then start pass timer.
1750 Timer *llvm::getPassTimer(Pass *P) {
1752 return TheTimeInfo->getPassTimer(P);
1756 /// If timing is enabled, report the times collected up to now and then reset
1758 void llvm::reportAndResetTimings() {
1760 TheTimeInfo->print();
1763 //===----------------------------------------------------------------------===//
1764 // PMStack implementation
1767 // Pop Pass Manager from the stack and clear its analysis info.
1768 void PMStack::pop() {
1770 PMDataManager *Top = this->top();
1771 Top->initializeAnalysisInfo();
1776 // Push PM on the stack and set its top level manager.
1777 void PMStack::push(PMDataManager *PM) {
1778 assert(PM && "Unable to push. Pass Manager expected");
1779 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1781 if (!this->empty()) {
1782 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1783 && "pushing bad pass manager to PMStack");
1784 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1786 assert(TPM && "Unable to find top level manager");
1787 TPM->addIndirectPassManager(PM);
1788 PM->setTopLevelManager(TPM);
1789 PM->setDepth(this->top()->getDepth()+1);
1791 assert((PM->getPassManagerType() == PMT_ModulePassManager
1792 || PM->getPassManagerType() == PMT_FunctionPassManager)
1793 && "pushing bad pass manager to PMStack");
1800 // Dump content of the pass manager stack.
1801 LLVM_DUMP_METHOD void PMStack::dump() const {
1802 for (PMDataManager *Manager : S)
1803 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1809 /// Find appropriate Module Pass Manager in the PM Stack and
1810 /// add self into that manager.
1811 void ModulePass::assignPassManager(PMStack &PMS,
1812 PassManagerType PreferredType) {
1813 // Find Module Pass Manager
1814 while (!PMS.empty()) {
1815 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1816 if (TopPMType == PreferredType)
1817 break; // We found desired pass manager
1818 else if (TopPMType > PMT_ModulePassManager)
1819 PMS.pop(); // Pop children pass managers
1823 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1824 PMS.top()->add(this);
1827 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1828 /// in the PM Stack and add self into that manager.
1829 void FunctionPass::assignPassManager(PMStack &PMS,
1830 PassManagerType PreferredType) {
1832 // Find Function Pass Manager
1833 while (!PMS.empty()) {
1834 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1840 // Create new Function Pass Manager if needed.
1842 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1843 FPP = (FPPassManager *)PMS.top();
1845 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1846 PMDataManager *PMD = PMS.top();
1848 // [1] Create new Function Pass Manager
1849 FPP = new FPPassManager();
1850 FPP->populateInheritedAnalysis(PMS);
1852 // [2] Set up new manager's top level manager
1853 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1854 TPM->addIndirectPassManager(FPP);
1856 // [3] Assign manager to manage this new manager. This may create
1857 // and push new managers into PMS
1858 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1860 // [4] Push new manager into PMS
1864 // Assign FPP as the manager of this pass.
1868 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1869 /// in the PM Stack and add self into that manager.
1870 void BasicBlockPass::assignPassManager(PMStack &PMS,
1871 PassManagerType PreferredType) {
1874 // Basic Pass Manager is a leaf pass manager. It does not handle
1875 // any other pass manager.
1877 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1878 BBP = (BBPassManager *)PMS.top();
1880 // If leaf manager is not Basic Block Pass manager then create new
1881 // basic Block Pass manager.
1882 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1883 PMDataManager *PMD = PMS.top();
1885 // [1] Create new Basic Block Manager
1886 BBP = new BBPassManager();
1888 // [2] Set up new manager's top level manager
1889 // Basic Block Pass Manager does not live by itself
1890 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1891 TPM->addIndirectPassManager(BBP);
1893 // [3] Assign manager to manage this new manager. This may create
1894 // and push new managers into PMS
1895 BBP->assignPassManager(PMS, PreferredType);
1897 // [4] Push new manager into PMS
1901 // Assign BBP as the manager of this pass.
1905 PassManagerBase::~PassManagerBase() {}