[AArch64] Crypto requires FP.
[llvm-core.git] / lib / IR / LegacyPassManager.cpp
blob628a67bd639ce29f9cf5e0e2be63628f49532a80
1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the legacy LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/LegacyPassManager.h"
15 #include "llvm/IR/IRPrintingPasses.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/LegacyPassManagers.h"
18 #include "llvm/IR/LegacyPassNameParser.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/Chrono.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/Mutex.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <map>
31 #include <unordered_set>
32 using namespace llvm;
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.
44 namespace {
45 // Different debug levels that can be enabled...
46 enum PassDebugLevel {
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"),
54 cl::values(
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")));
61 namespace {
62 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
63 PassOptionList;
66 // Print IR out before/after specified passes.
67 static PassOptionList
68 PrintBefore("print-before",
69 llvm::cl::desc("Print IR before specified passes"),
70 cl::Hidden);
72 static PassOptionList
73 PrintAfter("print-after",
74 llvm::cl::desc("Print IR after specified passes"),
75 cl::Hidden);
77 static cl::opt<bool>
78 PrintBeforeAll("print-before-all",
79 llvm::cl::desc("Print IR before each pass"),
80 cl::init(false));
81 static cl::opt<bool>
82 PrintAfterAll("print-after-all",
83 llvm::cl::desc("Print IR after each pass"),
84 cl::init(false));
86 static cl::list<std::string>
87 PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
88 cl::desc("Only print IR for functions whose name "
89 "match this for all print-[before|after][-all] "
90 "options"),
91 cl::CommaSeparated);
93 /// This is a helper to determine whether to print IR before or
94 /// after a pass.
96 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
97 PassOptionList &PassesToPrint) {
98 for (auto *PassInf : PassesToPrint) {
99 if (PassInf)
100 if (PassInf->getPassArgument() == PI->getPassArgument()) {
101 return true;
104 return false;
107 /// This is a utility to check whether a pass should have IR dumped
108 /// before it.
109 static bool ShouldPrintBeforePass(const PassInfo *PI) {
110 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
113 /// This is a utility to check whether a pass should have IR dumped
114 /// after it.
115 static bool ShouldPrintAfterPass(const PassInfo *PI) {
116 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
119 bool llvm::isFunctionInPrintList(StringRef FunctionName) {
120 static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
121 PrintFuncsList.end());
122 return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName);
124 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
125 /// or higher is specified.
126 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
127 return PassDebugging >= Executions;
133 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
134 if (!V && !M)
135 OS << "Releasing pass '";
136 else
137 OS << "Running pass '";
139 OS << P->getPassName() << "'";
141 if (M) {
142 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
143 return;
145 if (!V) {
146 OS << '\n';
147 return;
150 OS << " on ";
151 if (isa<Function>(V))
152 OS << "function";
153 else if (isa<BasicBlock>(V))
154 OS << "basic block";
155 else
156 OS << "value";
158 OS << " '";
159 V->printAsOperand(OS, /*PrintTy=*/false, M);
160 OS << "'\n";
164 namespace {
165 //===----------------------------------------------------------------------===//
166 // BBPassManager
168 /// BBPassManager manages BasicBlockPass. It batches all the
169 /// pass together and sequence them to process one basic block before
170 /// processing next basic block.
171 class BBPassManager : public PMDataManager, public FunctionPass {
173 public:
174 static char ID;
175 explicit BBPassManager()
176 : PMDataManager(), FunctionPass(ID) {}
178 /// Execute all of the passes scheduled for execution. Keep track of
179 /// whether any of the passes modifies the function, and if so, return true.
180 bool runOnFunction(Function &F) override;
182 /// Pass Manager itself does not invalidate any analysis info.
183 void getAnalysisUsage(AnalysisUsage &Info) const override {
184 Info.setPreservesAll();
187 bool doInitialization(Module &M) override;
188 bool doInitialization(Function &F);
189 bool doFinalization(Module &M) override;
190 bool doFinalization(Function &F);
192 PMDataManager *getAsPMDataManager() override { return this; }
193 Pass *getAsPass() override { return this; }
195 StringRef getPassName() const override { return "BasicBlock Pass Manager"; }
197 // Print passes managed by this manager
198 void dumpPassStructure(unsigned Offset) override {
199 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
200 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
201 BasicBlockPass *BP = getContainedPass(Index);
202 BP->dumpPassStructure(Offset + 1);
203 dumpLastUses(BP, Offset+1);
207 BasicBlockPass *getContainedPass(unsigned N) {
208 assert(N < PassVector.size() && "Pass number out of range!");
209 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
210 return BP;
213 PassManagerType getPassManagerType() const override {
214 return PMT_BasicBlockPassManager;
218 char BBPassManager::ID = 0;
219 } // End anonymous namespace
221 namespace llvm {
222 namespace legacy {
223 //===----------------------------------------------------------------------===//
224 // FunctionPassManagerImpl
226 /// FunctionPassManagerImpl manages FPPassManagers
227 class FunctionPassManagerImpl : public Pass,
228 public PMDataManager,
229 public PMTopLevelManager {
230 virtual void anchor();
231 private:
232 bool wasRun;
233 public:
234 static char ID;
235 explicit FunctionPassManagerImpl() :
236 Pass(PT_PassManager, ID), PMDataManager(),
237 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
239 /// \copydoc FunctionPassManager::add()
240 void add(Pass *P) {
241 schedulePass(P);
244 /// createPrinterPass - Get a function printer pass.
245 Pass *createPrinterPass(raw_ostream &O,
246 const std::string &Banner) const override {
247 return createPrintFunctionPass(O, Banner);
250 // Prepare for running an on the fly pass, freeing memory if needed
251 // from a previous run.
252 void releaseMemoryOnTheFly();
254 /// run - Execute all of the passes scheduled for execution. Keep track of
255 /// whether any of the passes modifies the module, and if so, return true.
256 bool run(Function &F);
258 /// doInitialization - Run all of the initializers for the function passes.
260 bool doInitialization(Module &M) override;
262 /// doFinalization - Run all of the finalizers for the function passes.
264 bool doFinalization(Module &M) override;
267 PMDataManager *getAsPMDataManager() override { return this; }
268 Pass *getAsPass() override { return this; }
269 PassManagerType getTopLevelPassManagerType() override {
270 return PMT_FunctionPassManager;
273 /// Pass Manager itself does not invalidate any analysis info.
274 void getAnalysisUsage(AnalysisUsage &Info) const override {
275 Info.setPreservesAll();
278 FPPassManager *getContainedManager(unsigned N) {
279 assert(N < PassManagers.size() && "Pass number out of range!");
280 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
281 return FP;
285 void FunctionPassManagerImpl::anchor() {}
287 char FunctionPassManagerImpl::ID = 0;
288 } // End of legacy namespace
289 } // End of llvm namespace
291 namespace {
292 //===----------------------------------------------------------------------===//
293 // MPPassManager
295 /// MPPassManager manages ModulePasses and function pass managers.
296 /// It batches all Module passes and function pass managers together and
297 /// sequences them to process one module.
298 class MPPassManager : public Pass, public PMDataManager {
299 public:
300 static char ID;
301 explicit MPPassManager() :
302 Pass(PT_PassManager, ID), PMDataManager() { }
304 // Delete on the fly managers.
305 ~MPPassManager() override {
306 for (auto &OnTheFlyManager : OnTheFlyManagers) {
307 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
308 delete FPP;
312 /// createPrinterPass - Get a module printer pass.
313 Pass *createPrinterPass(raw_ostream &O,
314 const std::string &Banner) const override {
315 return createPrintModulePass(O, Banner);
318 /// run - Execute all of the passes scheduled for execution. Keep track of
319 /// whether any of the passes modifies the module, and if so, return true.
320 bool runOnModule(Module &M);
322 using llvm::Pass::doInitialization;
323 using llvm::Pass::doFinalization;
325 /// Pass Manager itself does not invalidate any analysis info.
326 void getAnalysisUsage(AnalysisUsage &Info) const override {
327 Info.setPreservesAll();
330 /// Add RequiredPass into list of lower level passes required by pass P.
331 /// RequiredPass is run on the fly by Pass Manager when P requests it
332 /// through getAnalysis interface.
333 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
335 /// Return function pass corresponding to PassInfo PI, that is
336 /// required by module pass MP. Instantiate analysis pass, by using
337 /// its runOnFunction() for function F.
338 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
340 StringRef getPassName() const override { return "Module Pass Manager"; }
342 PMDataManager *getAsPMDataManager() override { return this; }
343 Pass *getAsPass() override { return this; }
345 // Print passes managed by this manager
346 void dumpPassStructure(unsigned Offset) override {
347 dbgs().indent(Offset*2) << "ModulePass Manager\n";
348 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
349 ModulePass *MP = getContainedPass(Index);
350 MP->dumpPassStructure(Offset + 1);
351 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
352 OnTheFlyManagers.find(MP);
353 if (I != OnTheFlyManagers.end())
354 I->second->dumpPassStructure(Offset + 2);
355 dumpLastUses(MP, Offset+1);
359 ModulePass *getContainedPass(unsigned N) {
360 assert(N < PassVector.size() && "Pass number out of range!");
361 return static_cast<ModulePass *>(PassVector[N]);
364 PassManagerType getPassManagerType() const override {
365 return PMT_ModulePassManager;
368 private:
369 /// Collection of on the fly FPPassManagers. These managers manage
370 /// function passes that are required by module passes.
371 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
374 char MPPassManager::ID = 0;
375 } // End anonymous namespace
377 namespace llvm {
378 namespace legacy {
379 //===----------------------------------------------------------------------===//
380 // PassManagerImpl
383 /// PassManagerImpl manages MPPassManagers
384 class PassManagerImpl : public Pass,
385 public PMDataManager,
386 public PMTopLevelManager {
387 virtual void anchor();
389 public:
390 static char ID;
391 explicit PassManagerImpl() :
392 Pass(PT_PassManager, ID), PMDataManager(),
393 PMTopLevelManager(new MPPassManager()) {}
395 /// \copydoc PassManager::add()
396 void add(Pass *P) {
397 schedulePass(P);
400 /// createPrinterPass - Get a module printer pass.
401 Pass *createPrinterPass(raw_ostream &O,
402 const std::string &Banner) const override {
403 return createPrintModulePass(O, Banner);
406 /// run - Execute all of the passes scheduled for execution. Keep track of
407 /// whether any of the passes modifies the module, and if so, return true.
408 bool run(Module &M);
410 using llvm::Pass::doInitialization;
411 using llvm::Pass::doFinalization;
413 /// Pass Manager itself does not invalidate any analysis info.
414 void getAnalysisUsage(AnalysisUsage &Info) const override {
415 Info.setPreservesAll();
418 PMDataManager *getAsPMDataManager() override { return this; }
419 Pass *getAsPass() override { return this; }
420 PassManagerType getTopLevelPassManagerType() override {
421 return PMT_ModulePassManager;
424 MPPassManager *getContainedManager(unsigned N) {
425 assert(N < PassManagers.size() && "Pass number out of range!");
426 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
427 return MP;
431 void PassManagerImpl::anchor() {}
433 char PassManagerImpl::ID = 0;
434 } // End of legacy namespace
435 } // End of llvm namespace
437 namespace {
439 //===----------------------------------------------------------------------===//
440 /// TimingInfo Class - This class is used to calculate information about the
441 /// amount of time each pass takes to execute. This only happens when
442 /// -time-passes is enabled on the command line.
445 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
447 class TimingInfo {
448 DenseMap<Pass*, Timer*> TimingData;
449 TimerGroup TG;
450 public:
451 // Use 'create' member to get this.
452 TimingInfo() : TG("pass", "... Pass execution timing report ...") {}
454 // TimingDtor - Print out information about timing information
455 ~TimingInfo() {
456 // Delete all of the timers, which accumulate their info into the
457 // TimerGroup.
458 for (auto &I : TimingData)
459 delete I.second;
460 // TimerGroup is deleted next, printing the report.
463 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
464 // to a non-null value (if the -time-passes option is enabled) or it leaves it
465 // null. It may be called multiple times.
466 static void createTheTimeInfo();
468 /// getPassTimer - Return the timer for the specified pass if it exists.
469 Timer *getPassTimer(Pass *P) {
470 if (P->getAsPMDataManager())
471 return nullptr;
473 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
474 Timer *&T = TimingData[P];
475 if (!T) {
476 StringRef PassName = P->getPassName();
477 T = new Timer(PassName, PassName, TG);
479 return T;
483 } // End of anon namespace
485 static TimingInfo *TheTimeInfo;
487 //===----------------------------------------------------------------------===//
488 // PMTopLevelManager implementation
490 /// Initialize top level manager. Create first pass manager.
491 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
492 PMDM->setTopLevelManager(this);
493 addPassManager(PMDM);
494 activeStack.push(PMDM);
497 /// Set pass P as the last user of the given analysis passes.
498 void
499 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
500 unsigned PDepth = 0;
501 if (P->getResolver())
502 PDepth = P->getResolver()->getPMDataManager().getDepth();
504 for (Pass *AP : AnalysisPasses) {
505 LastUser[AP] = P;
507 if (P == AP)
508 continue;
510 // Update the last users of passes that are required transitive by AP.
511 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
512 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
513 SmallVector<Pass *, 12> LastUses;
514 SmallVector<Pass *, 12> LastPMUses;
515 for (AnalysisID ID : IDs) {
516 Pass *AnalysisPass = findAnalysisPass(ID);
517 assert(AnalysisPass && "Expected analysis pass to exist.");
518 AnalysisResolver *AR = AnalysisPass->getResolver();
519 assert(AR && "Expected analysis resolver to exist.");
520 unsigned APDepth = AR->getPMDataManager().getDepth();
522 if (PDepth == APDepth)
523 LastUses.push_back(AnalysisPass);
524 else if (PDepth > APDepth)
525 LastPMUses.push_back(AnalysisPass);
528 setLastUser(LastUses, P);
530 // If this pass has a corresponding pass manager, push higher level
531 // analysis to this pass manager.
532 if (P->getResolver())
533 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
536 // If AP is the last user of other passes then make P last user of
537 // such passes.
538 for (auto LU : LastUser) {
539 if (LU.second == AP)
540 // DenseMap iterator is not invalidated here because
541 // this is just updating existing entries.
542 LastUser[LU.first] = P;
547 /// Collect passes whose last user is P
548 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
549 Pass *P) {
550 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
551 InversedLastUser.find(P);
552 if (DMI == InversedLastUser.end())
553 return;
555 SmallPtrSet<Pass *, 8> &LU = DMI->second;
556 for (Pass *LUP : LU) {
557 LastUses.push_back(LUP);
562 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
563 AnalysisUsage *AnUsage = nullptr;
564 auto DMI = AnUsageMap.find(P);
565 if (DMI != AnUsageMap.end())
566 AnUsage = DMI->second;
567 else {
568 // Look up the analysis usage from the pass instance (different instances
569 // of the same pass can produce different results), but unique the
570 // resulting object to reduce memory usage. This helps to greatly reduce
571 // memory usage when we have many instances of only a few pass types
572 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
573 // of dependencies.
574 AnalysisUsage AU;
575 P->getAnalysisUsage(AU);
577 AUFoldingSetNode* Node = nullptr;
578 FoldingSetNodeID ID;
579 AUFoldingSetNode::Profile(ID, AU);
580 void *IP = nullptr;
581 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
582 Node = N;
583 else {
584 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
585 UniqueAnalysisUsages.InsertNode(Node, IP);
587 assert(Node && "cached analysis usage must be non null");
589 AnUsageMap[P] = &Node->AU;
590 AnUsage = &Node->AU;;
592 return AnUsage;
595 /// Schedule pass P for execution. Make sure that passes required by
596 /// P are run before P is run. Update analysis info maintained by
597 /// the manager. Remove dead passes. This is a recursive function.
598 void PMTopLevelManager::schedulePass(Pass *P) {
600 // TODO : Allocate function manager for this pass, other wise required set
601 // may be inserted into previous function manager
603 // Give pass a chance to prepare the stage.
604 P->preparePassManager(activeStack);
606 // If P is an analysis pass and it is available then do not
607 // generate the analysis again. Stale analysis info should not be
608 // available at this point.
609 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
610 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
611 delete P;
612 return;
615 AnalysisUsage *AnUsage = findAnalysisUsage(P);
617 bool checkAnalysis = true;
618 while (checkAnalysis) {
619 checkAnalysis = false;
621 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
622 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
623 E = RequiredSet.end(); I != E; ++I) {
625 Pass *AnalysisPass = findAnalysisPass(*I);
626 if (!AnalysisPass) {
627 const PassInfo *PI = findAnalysisPassInfo(*I);
629 if (!PI) {
630 // Pass P is not in the global PassRegistry
631 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
632 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
633 dbgs() << "Required Passes:" << "\n";
634 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
635 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
636 Pass *AnalysisPass2 = findAnalysisPass(*I2);
637 if (AnalysisPass2) {
638 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
639 } else {
640 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
641 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
642 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
647 assert(PI && "Expected required passes to be initialized");
648 AnalysisPass = PI->createPass();
649 if (P->getPotentialPassManagerType () ==
650 AnalysisPass->getPotentialPassManagerType())
651 // Schedule analysis pass that is managed by the same pass manager.
652 schedulePass(AnalysisPass);
653 else if (P->getPotentialPassManagerType () >
654 AnalysisPass->getPotentialPassManagerType()) {
655 // Schedule analysis pass that is managed by a new manager.
656 schedulePass(AnalysisPass);
657 // Recheck analysis passes to ensure that required analyses that
658 // are already checked are still available.
659 checkAnalysis = true;
660 } else
661 // Do not schedule this analysis. Lower level analysis
662 // passes are run on the fly.
663 delete AnalysisPass;
668 // Now all required passes are available.
669 if (ImmutablePass *IP = P->getAsImmutablePass()) {
670 // P is a immutable pass and it will be managed by this
671 // top level manager. Set up analysis resolver to connect them.
672 PMDataManager *DM = getAsPMDataManager();
673 AnalysisResolver *AR = new AnalysisResolver(*DM);
674 P->setResolver(AR);
675 DM->initializeAnalysisImpl(P);
676 addImmutablePass(IP);
677 DM->recordAvailableAnalysis(IP);
678 return;
681 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
682 Pass *PP = P->createPrinterPass(
683 dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
684 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
687 // Add the requested pass to the best available pass manager.
688 P->assignPassManager(activeStack, getTopLevelPassManagerType());
690 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
691 Pass *PP = P->createPrinterPass(
692 dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
693 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
697 /// Find the pass that implements Analysis AID. Search immutable
698 /// passes and all pass managers. If desired pass is not found
699 /// then return NULL.
700 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
701 // For immutable passes we have a direct mapping from ID to pass, so check
702 // that first.
703 if (Pass *P = ImmutablePassMap.lookup(AID))
704 return P;
706 // Check pass managers
707 for (PMDataManager *PassManager : PassManagers)
708 if (Pass *P = PassManager->findAnalysisPass(AID, false))
709 return P;
711 // Check other pass managers
712 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
713 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
714 return P;
716 return nullptr;
719 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
720 const PassInfo *&PI = AnalysisPassInfos[AID];
721 if (!PI)
722 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
723 else
724 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
725 "The pass info pointer changed for an analysis ID!");
727 return PI;
730 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
731 P->initializePass();
732 ImmutablePasses.push_back(P);
734 // Add this pass to the map from its analysis ID. We clobber any prior runs
735 // of the pass in the map so that the last one added is the one found when
736 // doing lookups.
737 AnalysisID AID = P->getPassID();
738 ImmutablePassMap[AID] = P;
740 // Also add any interfaces implemented by the immutable pass to the map for
741 // fast lookup.
742 const PassInfo *PassInf = findAnalysisPassInfo(AID);
743 assert(PassInf && "Expected all immutable passes to be initialized");
744 for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
745 ImmutablePassMap[ImmPI->getTypeInfo()] = P;
748 // Print passes managed by this top level manager.
749 void PMTopLevelManager::dumpPasses() const {
751 if (PassDebugging < Structure)
752 return;
754 // Print out the immutable passes
755 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
756 ImmutablePasses[i]->dumpPassStructure(0);
759 // Every class that derives from PMDataManager also derives from Pass
760 // (sometimes indirectly), but there's no inheritance relationship
761 // between PMDataManager and Pass, so we have to getAsPass to get
762 // from a PMDataManager* to a Pass*.
763 for (PMDataManager *Manager : PassManagers)
764 Manager->getAsPass()->dumpPassStructure(1);
767 void PMTopLevelManager::dumpArguments() const {
769 if (PassDebugging < Arguments)
770 return;
772 dbgs() << "Pass Arguments: ";
773 for (ImmutablePass *P : ImmutablePasses)
774 if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
775 assert(PI && "Expected all immutable passes to be initialized");
776 if (!PI->isAnalysisGroup())
777 dbgs() << " -" << PI->getPassArgument();
779 for (PMDataManager *PM : PassManagers)
780 PM->dumpPassArguments();
781 dbgs() << "\n";
784 void PMTopLevelManager::initializeAllAnalysisInfo() {
785 for (PMDataManager *PM : PassManagers)
786 PM->initializeAnalysisInfo();
788 // Initailize other pass managers
789 for (PMDataManager *IPM : IndirectPassManagers)
790 IPM->initializeAnalysisInfo();
792 for (auto LU : LastUser) {
793 SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
794 L.insert(LU.first);
798 /// Destructor
799 PMTopLevelManager::~PMTopLevelManager() {
800 for (PMDataManager *PM : PassManagers)
801 delete PM;
803 for (ImmutablePass *P : ImmutablePasses)
804 delete P;
807 //===----------------------------------------------------------------------===//
808 // PMDataManager implementation
810 /// Augement AvailableAnalysis by adding analysis made available by pass P.
811 void PMDataManager::recordAvailableAnalysis(Pass *P) {
812 AnalysisID PI = P->getPassID();
814 AvailableAnalysis[PI] = P;
816 assert(!AvailableAnalysis.empty());
818 // This pass is the current implementation of all of the interfaces it
819 // implements as well.
820 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
821 if (!PInf) return;
822 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
823 for (unsigned i = 0, e = II.size(); i != e; ++i)
824 AvailableAnalysis[II[i]->getTypeInfo()] = P;
827 // Return true if P preserves high level analysis used by other
828 // passes managed by this manager
829 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
830 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
831 if (AnUsage->getPreservesAll())
832 return true;
834 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
835 for (Pass *P1 : HigherLevelAnalysis) {
836 if (P1->getAsImmutablePass() == nullptr &&
837 !is_contained(PreservedSet, P1->getPassID()))
838 return false;
841 return true;
844 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
845 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
846 // Don't do this unless assertions are enabled.
847 #ifdef NDEBUG
848 return;
849 #endif
850 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
851 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
853 // Verify preserved analysis
854 for (AnalysisID AID : PreservedSet) {
855 if (Pass *AP = findAnalysisPass(AID, true)) {
856 TimeRegion PassTimer(getPassTimer(AP));
857 AP->verifyAnalysis();
862 /// Remove Analysis not preserved by Pass P
863 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
864 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
865 if (AnUsage->getPreservesAll())
866 return;
868 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
869 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
870 E = AvailableAnalysis.end(); I != E; ) {
871 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
872 if (Info->second->getAsImmutablePass() == nullptr &&
873 !is_contained(PreservedSet, Info->first)) {
874 // Remove this analysis
875 if (PassDebugging >= Details) {
876 Pass *S = Info->second;
877 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
878 dbgs() << S->getPassName() << "'\n";
880 AvailableAnalysis.erase(Info);
884 // Check inherited analysis also. If P is not preserving analysis
885 // provided by parent manager then remove it here.
886 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
888 if (!InheritedAnalysis[Index])
889 continue;
891 for (DenseMap<AnalysisID, Pass*>::iterator
892 I = InheritedAnalysis[Index]->begin(),
893 E = InheritedAnalysis[Index]->end(); I != E; ) {
894 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
895 if (Info->second->getAsImmutablePass() == nullptr &&
896 !is_contained(PreservedSet, Info->first)) {
897 // Remove this analysis
898 if (PassDebugging >= Details) {
899 Pass *S = Info->second;
900 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
901 dbgs() << S->getPassName() << "'\n";
903 InheritedAnalysis[Index]->erase(Info);
909 /// Remove analysis passes that are not used any longer
910 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
911 enum PassDebuggingString DBG_STR) {
913 SmallVector<Pass *, 12> DeadPasses;
915 // If this is a on the fly manager then it does not have TPM.
916 if (!TPM)
917 return;
919 TPM->collectLastUses(DeadPasses, P);
921 if (PassDebugging >= Details && !DeadPasses.empty()) {
922 dbgs() << " -*- '" << P->getPassName();
923 dbgs() << "' is the last user of following pass instances.";
924 dbgs() << " Free these instances\n";
927 for (Pass *P : DeadPasses)
928 freePass(P, Msg, DBG_STR);
931 void PMDataManager::freePass(Pass *P, StringRef Msg,
932 enum PassDebuggingString DBG_STR) {
933 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
936 // If the pass crashes releasing memory, remember this.
937 PassManagerPrettyStackEntry X(P);
938 TimeRegion PassTimer(getPassTimer(P));
940 P->releaseMemory();
943 AnalysisID PI = P->getPassID();
944 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
945 // Remove the pass itself (if it is not already removed).
946 AvailableAnalysis.erase(PI);
948 // Remove all interfaces this pass implements, for which it is also
949 // listed as the available implementation.
950 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
951 for (unsigned i = 0, e = II.size(); i != e; ++i) {
952 DenseMap<AnalysisID, Pass*>::iterator Pos =
953 AvailableAnalysis.find(II[i]->getTypeInfo());
954 if (Pos != AvailableAnalysis.end() && Pos->second == P)
955 AvailableAnalysis.erase(Pos);
960 /// Add pass P into the PassVector. Update
961 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
962 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
963 // This manager is going to manage pass P. Set up analysis resolver
964 // to connect them.
965 AnalysisResolver *AR = new AnalysisResolver(*this);
966 P->setResolver(AR);
968 // If a FunctionPass F is the last user of ModulePass info M
969 // then the F's manager, not F, records itself as a last user of M.
970 SmallVector<Pass *, 12> TransferLastUses;
972 if (!ProcessAnalysis) {
973 // Add pass
974 PassVector.push_back(P);
975 return;
978 // At the moment, this pass is the last user of all required passes.
979 SmallVector<Pass *, 12> LastUses;
980 SmallVector<Pass *, 8> UsedPasses;
981 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
983 unsigned PDepth = this->getDepth();
985 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
986 for (Pass *PUsed : UsedPasses) {
987 unsigned RDepth = 0;
989 assert(PUsed->getResolver() && "Analysis Resolver is not set");
990 PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
991 RDepth = DM.getDepth();
993 if (PDepth == RDepth)
994 LastUses.push_back(PUsed);
995 else if (PDepth > RDepth) {
996 // Let the parent claim responsibility of last use
997 TransferLastUses.push_back(PUsed);
998 // Keep track of higher level analysis used by this manager.
999 HigherLevelAnalysis.push_back(PUsed);
1000 } else
1001 llvm_unreachable("Unable to accommodate Used Pass");
1004 // Set P as P's last user until someone starts using P.
1005 // However, if P is a Pass Manager then it does not need
1006 // to record its last user.
1007 if (!P->getAsPMDataManager())
1008 LastUses.push_back(P);
1009 TPM->setLastUser(LastUses, P);
1011 if (!TransferLastUses.empty()) {
1012 Pass *My_PM = getAsPass();
1013 TPM->setLastUser(TransferLastUses, My_PM);
1014 TransferLastUses.clear();
1017 // Now, take care of required analyses that are not available.
1018 for (AnalysisID ID : ReqAnalysisNotAvailable) {
1019 const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1020 Pass *AnalysisPass = PI->createPass();
1021 this->addLowerLevelRequiredPass(P, AnalysisPass);
1024 // Take a note of analysis required and made available by this pass.
1025 // Remove the analysis not preserved by this pass
1026 removeNotPreservedAnalysis(P);
1027 recordAvailableAnalysis(P);
1029 // Add pass
1030 PassVector.push_back(P);
1034 /// Populate UP with analysis pass that are used or required by
1035 /// pass P and are available. Populate RP_NotAvail with analysis
1036 /// pass that are required by pass P but are not available.
1037 void PMDataManager::collectRequiredAndUsedAnalyses(
1038 SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1039 Pass *P) {
1040 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1042 for (const auto &UsedID : AnUsage->getUsedSet())
1043 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1044 UP.push_back(AnalysisPass);
1046 for (const auto &RequiredID : AnUsage->getRequiredSet())
1047 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1048 UP.push_back(AnalysisPass);
1049 else
1050 RP_NotAvail.push_back(RequiredID);
1052 for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1053 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1054 UP.push_back(AnalysisPass);
1055 else
1056 RP_NotAvail.push_back(RequiredID);
1059 // All Required analyses should be available to the pass as it runs! Here
1060 // we fill in the AnalysisImpls member of the pass so that it can
1061 // successfully use the getAnalysis() method to retrieve the
1062 // implementations it needs.
1064 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1065 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1067 for (AnalysisUsage::VectorType::const_iterator
1068 I = AnUsage->getRequiredSet().begin(),
1069 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1070 Pass *Impl = findAnalysisPass(*I, true);
1071 if (!Impl)
1072 // This may be analysis pass that is initialized on the fly.
1073 // If that is not the case then it will raise an assert when it is used.
1074 continue;
1075 AnalysisResolver *AR = P->getResolver();
1076 assert(AR && "Analysis Resolver is not set");
1077 AR->addAnalysisImplsPair(*I, Impl);
1081 /// Find the pass that implements Analysis AID. If desired pass is not found
1082 /// then return NULL.
1083 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1085 // Check if AvailableAnalysis map has one entry.
1086 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1088 if (I != AvailableAnalysis.end())
1089 return I->second;
1091 // Search Parents through TopLevelManager
1092 if (SearchParent)
1093 return TPM->findAnalysisPass(AID);
1095 return nullptr;
1098 // Print list of passes that are last used by P.
1099 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1101 SmallVector<Pass *, 12> LUses;
1103 // If this is a on the fly manager then it does not have TPM.
1104 if (!TPM)
1105 return;
1107 TPM->collectLastUses(LUses, P);
1109 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1110 E = LUses.end(); I != E; ++I) {
1111 dbgs() << "--" << std::string(Offset*2, ' ');
1112 (*I)->dumpPassStructure(0);
1116 void PMDataManager::dumpPassArguments() const {
1117 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1118 E = PassVector.end(); I != E; ++I) {
1119 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1120 PMD->dumpPassArguments();
1121 else
1122 if (const PassInfo *PI =
1123 TPM->findAnalysisPassInfo((*I)->getPassID()))
1124 if (!PI->isAnalysisGroup())
1125 dbgs() << " -" << PI->getPassArgument();
1129 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1130 enum PassDebuggingString S2,
1131 StringRef Msg) {
1132 if (PassDebugging < Executions)
1133 return;
1134 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1135 << std::string(getDepth() * 2 + 1, ' ');
1136 switch (S1) {
1137 case EXECUTION_MSG:
1138 dbgs() << "Executing Pass '" << P->getPassName();
1139 break;
1140 case MODIFICATION_MSG:
1141 dbgs() << "Made Modification '" << P->getPassName();
1142 break;
1143 case FREEING_MSG:
1144 dbgs() << " Freeing Pass '" << P->getPassName();
1145 break;
1146 default:
1147 break;
1149 switch (S2) {
1150 case ON_BASICBLOCK_MSG:
1151 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1152 break;
1153 case ON_FUNCTION_MSG:
1154 dbgs() << "' on Function '" << Msg << "'...\n";
1155 break;
1156 case ON_MODULE_MSG:
1157 dbgs() << "' on Module '" << Msg << "'...\n";
1158 break;
1159 case ON_REGION_MSG:
1160 dbgs() << "' on Region '" << Msg << "'...\n";
1161 break;
1162 case ON_LOOP_MSG:
1163 dbgs() << "' on Loop '" << Msg << "'...\n";
1164 break;
1165 case ON_CG_MSG:
1166 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1167 break;
1168 default:
1169 break;
1173 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1174 if (PassDebugging < Details)
1175 return;
1177 AnalysisUsage analysisUsage;
1178 P->getAnalysisUsage(analysisUsage);
1179 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1182 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1183 if (PassDebugging < Details)
1184 return;
1186 AnalysisUsage analysisUsage;
1187 P->getAnalysisUsage(analysisUsage);
1188 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1191 void PMDataManager::dumpUsedSet(const Pass *P) const {
1192 if (PassDebugging < Details)
1193 return;
1195 AnalysisUsage analysisUsage;
1196 P->getAnalysisUsage(analysisUsage);
1197 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1200 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1201 const AnalysisUsage::VectorType &Set) const {
1202 assert(PassDebugging >= Details);
1203 if (Set.empty())
1204 return;
1205 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1206 for (unsigned i = 0; i != Set.size(); ++i) {
1207 if (i) dbgs() << ',';
1208 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1209 if (!PInf) {
1210 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1211 // all drivers.
1212 dbgs() << " Uninitialized Pass";
1213 continue;
1215 dbgs() << ' ' << PInf->getPassName();
1217 dbgs() << '\n';
1220 /// Add RequiredPass into list of lower level passes required by pass P.
1221 /// RequiredPass is run on the fly by Pass Manager when P requests it
1222 /// through getAnalysis interface.
1223 /// This should be handled by specific pass manager.
1224 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1225 if (TPM) {
1226 TPM->dumpArguments();
1227 TPM->dumpPasses();
1230 // Module Level pass may required Function Level analysis info
1231 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1232 // to provide this on demand. In that case, in Pass manager terminology,
1233 // module level pass is requiring lower level analysis info managed by
1234 // lower level pass manager.
1236 // When Pass manager is not able to order required analysis info, Pass manager
1237 // checks whether any lower level manager will be able to provide this
1238 // analysis info on demand or not.
1239 #ifndef NDEBUG
1240 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1241 dbgs() << "' required by '" << P->getPassName() << "'\n";
1242 #endif
1243 llvm_unreachable("Unable to schedule pass");
1246 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1247 llvm_unreachable("Unable to find on the fly pass");
1250 // Destructor
1251 PMDataManager::~PMDataManager() {
1252 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1253 E = PassVector.end(); I != E; ++I)
1254 delete *I;
1257 //===----------------------------------------------------------------------===//
1258 // NOTE: Is this the right place to define this method ?
1259 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1260 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1261 return PM.findAnalysisPass(ID, dir);
1264 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1265 Function &F) {
1266 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1269 //===----------------------------------------------------------------------===//
1270 // BBPassManager implementation
1272 /// Execute all of the passes scheduled for execution by invoking
1273 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1274 /// the function, and if so, return true.
1275 bool BBPassManager::runOnFunction(Function &F) {
1276 if (F.isDeclaration())
1277 return false;
1279 bool Changed = doInitialization(F);
1281 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1282 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1283 BasicBlockPass *BP = getContainedPass(Index);
1284 bool LocalChanged = false;
1286 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1287 dumpRequiredSet(BP);
1289 initializeAnalysisImpl(BP);
1292 // If the pass crashes, remember this.
1293 PassManagerPrettyStackEntry X(BP, *I);
1294 TimeRegion PassTimer(getPassTimer(BP));
1296 LocalChanged |= BP->runOnBasicBlock(*I);
1299 Changed |= LocalChanged;
1300 if (LocalChanged)
1301 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1302 I->getName());
1303 dumpPreservedSet(BP);
1304 dumpUsedSet(BP);
1306 verifyPreservedAnalysis(BP);
1307 removeNotPreservedAnalysis(BP);
1308 recordAvailableAnalysis(BP);
1309 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1312 return doFinalization(F) || Changed;
1315 // Implement doInitialization and doFinalization
1316 bool BBPassManager::doInitialization(Module &M) {
1317 bool Changed = false;
1319 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1320 Changed |= getContainedPass(Index)->doInitialization(M);
1322 return Changed;
1325 bool BBPassManager::doFinalization(Module &M) {
1326 bool Changed = false;
1328 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1329 Changed |= getContainedPass(Index)->doFinalization(M);
1331 return Changed;
1334 bool BBPassManager::doInitialization(Function &F) {
1335 bool Changed = false;
1337 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1338 BasicBlockPass *BP = getContainedPass(Index);
1339 Changed |= BP->doInitialization(F);
1342 return Changed;
1345 bool BBPassManager::doFinalization(Function &F) {
1346 bool Changed = false;
1348 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1349 BasicBlockPass *BP = getContainedPass(Index);
1350 Changed |= BP->doFinalization(F);
1353 return Changed;
1357 //===----------------------------------------------------------------------===//
1358 // FunctionPassManager implementation
1360 /// Create new Function pass manager
1361 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1362 FPM = new FunctionPassManagerImpl();
1363 // FPM is the top level manager.
1364 FPM->setTopLevelManager(FPM);
1366 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1367 FPM->setResolver(AR);
1370 FunctionPassManager::~FunctionPassManager() {
1371 delete FPM;
1374 void FunctionPassManager::add(Pass *P) {
1375 FPM->add(P);
1378 /// run - Execute all of the passes scheduled for execution. Keep
1379 /// track of whether any of the passes modifies the function, and if
1380 /// so, return true.
1382 bool FunctionPassManager::run(Function &F) {
1383 handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1384 report_fatal_error("Error reading bitcode file: " + EIB.message());
1386 return FPM->run(F);
1390 /// doInitialization - Run all of the initializers for the function passes.
1392 bool FunctionPassManager::doInitialization() {
1393 return FPM->doInitialization(*M);
1396 /// doFinalization - Run all of the finalizers for the function passes.
1398 bool FunctionPassManager::doFinalization() {
1399 return FPM->doFinalization(*M);
1402 //===----------------------------------------------------------------------===//
1403 // FunctionPassManagerImpl implementation
1405 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1406 bool Changed = false;
1408 dumpArguments();
1409 dumpPasses();
1411 for (ImmutablePass *ImPass : getImmutablePasses())
1412 Changed |= ImPass->doInitialization(M);
1414 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1415 Changed |= getContainedManager(Index)->doInitialization(M);
1417 return Changed;
1420 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1421 bool Changed = false;
1423 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1424 Changed |= getContainedManager(Index)->doFinalization(M);
1426 for (ImmutablePass *ImPass : getImmutablePasses())
1427 Changed |= ImPass->doFinalization(M);
1429 return Changed;
1432 /// cleanup - After running all passes, clean up pass manager cache.
1433 void FPPassManager::cleanup() {
1434 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1435 FunctionPass *FP = getContainedPass(Index);
1436 AnalysisResolver *AR = FP->getResolver();
1437 assert(AR && "Analysis Resolver is not set");
1438 AR->clearAnalysisImpls();
1442 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1443 if (!wasRun)
1444 return;
1445 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1446 FPPassManager *FPPM = getContainedManager(Index);
1447 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1448 FPPM->getContainedPass(Index)->releaseMemory();
1451 wasRun = false;
1454 // Execute all the passes managed by this top level manager.
1455 // Return true if any function is modified by a pass.
1456 bool FunctionPassManagerImpl::run(Function &F) {
1457 bool Changed = false;
1458 TimingInfo::createTheTimeInfo();
1460 initializeAllAnalysisInfo();
1461 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1462 Changed |= getContainedManager(Index)->runOnFunction(F);
1463 F.getContext().yield();
1466 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1467 getContainedManager(Index)->cleanup();
1469 wasRun = true;
1470 return Changed;
1473 //===----------------------------------------------------------------------===//
1474 // FPPassManager implementation
1476 char FPPassManager::ID = 0;
1477 /// Print passes managed by this manager
1478 void FPPassManager::dumpPassStructure(unsigned Offset) {
1479 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1480 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1481 FunctionPass *FP = getContainedPass(Index);
1482 FP->dumpPassStructure(Offset + 1);
1483 dumpLastUses(FP, Offset+1);
1488 /// Execute all of the passes scheduled for execution by invoking
1489 /// runOnFunction method. Keep track of whether any of the passes modifies
1490 /// the function, and if so, return true.
1491 bool FPPassManager::runOnFunction(Function &F) {
1492 if (F.isDeclaration())
1493 return false;
1495 bool Changed = false;
1497 // Collect inherited analysis from Module level pass manager.
1498 populateInheritedAnalysis(TPM->activeStack);
1500 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1501 FunctionPass *FP = getContainedPass(Index);
1502 bool LocalChanged = false;
1504 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1505 dumpRequiredSet(FP);
1507 initializeAnalysisImpl(FP);
1510 PassManagerPrettyStackEntry X(FP, F);
1511 TimeRegion PassTimer(getPassTimer(FP));
1513 LocalChanged |= FP->runOnFunction(F);
1516 Changed |= LocalChanged;
1517 if (LocalChanged)
1518 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1519 dumpPreservedSet(FP);
1520 dumpUsedSet(FP);
1522 verifyPreservedAnalysis(FP);
1523 removeNotPreservedAnalysis(FP);
1524 recordAvailableAnalysis(FP);
1525 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1527 return Changed;
1530 bool FPPassManager::runOnModule(Module &M) {
1531 bool Changed = false;
1533 for (Function &F : M)
1534 Changed |= runOnFunction(F);
1536 return Changed;
1539 bool FPPassManager::doInitialization(Module &M) {
1540 bool Changed = false;
1542 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1543 Changed |= getContainedPass(Index)->doInitialization(M);
1545 return Changed;
1548 bool FPPassManager::doFinalization(Module &M) {
1549 bool Changed = false;
1551 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1552 Changed |= getContainedPass(Index)->doFinalization(M);
1554 return Changed;
1557 //===----------------------------------------------------------------------===//
1558 // MPPassManager implementation
1560 /// Execute all of the passes scheduled for execution by invoking
1561 /// runOnModule method. Keep track of whether any of the passes modifies
1562 /// the module, and if so, return true.
1563 bool
1564 MPPassManager::runOnModule(Module &M) {
1565 bool Changed = false;
1567 // Initialize on-the-fly passes
1568 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1569 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1570 Changed |= FPP->doInitialization(M);
1573 // Initialize module passes
1574 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1575 Changed |= getContainedPass(Index)->doInitialization(M);
1577 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1578 ModulePass *MP = getContainedPass(Index);
1579 bool LocalChanged = false;
1581 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1582 dumpRequiredSet(MP);
1584 initializeAnalysisImpl(MP);
1587 PassManagerPrettyStackEntry X(MP, M);
1588 TimeRegion PassTimer(getPassTimer(MP));
1590 LocalChanged |= MP->runOnModule(M);
1593 Changed |= LocalChanged;
1594 if (LocalChanged)
1595 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1596 M.getModuleIdentifier());
1597 dumpPreservedSet(MP);
1598 dumpUsedSet(MP);
1600 verifyPreservedAnalysis(MP);
1601 removeNotPreservedAnalysis(MP);
1602 recordAvailableAnalysis(MP);
1603 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1606 // Finalize module passes
1607 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1608 Changed |= getContainedPass(Index)->doFinalization(M);
1610 // Finalize on-the-fly passes
1611 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1612 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1613 // We don't know when is the last time an on-the-fly pass is run,
1614 // so we need to releaseMemory / finalize here
1615 FPP->releaseMemoryOnTheFly();
1616 Changed |= FPP->doFinalization(M);
1619 return Changed;
1622 /// Add RequiredPass into list of lower level passes required by pass P.
1623 /// RequiredPass is run on the fly by Pass Manager when P requests it
1624 /// through getAnalysis interface.
1625 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1626 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1627 "Unable to handle Pass that requires lower level Analysis pass");
1628 assert((P->getPotentialPassManagerType() <
1629 RequiredPass->getPotentialPassManagerType()) &&
1630 "Unable to handle Pass that requires lower level Analysis pass");
1631 if (!RequiredPass)
1632 return;
1634 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1635 if (!FPP) {
1636 FPP = new FunctionPassManagerImpl();
1637 // FPP is the top level manager.
1638 FPP->setTopLevelManager(FPP);
1640 OnTheFlyManagers[P] = FPP;
1642 const PassInfo *RequiredPassPI =
1643 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1645 Pass *FoundPass = nullptr;
1646 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1647 FoundPass =
1648 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1650 if (!FoundPass) {
1651 FoundPass = RequiredPass;
1652 // This should be guaranteed to add RequiredPass to the passmanager given
1653 // that we checked for an available analysis above.
1654 FPP->add(RequiredPass);
1656 // Register P as the last user of FoundPass or RequiredPass.
1657 SmallVector<Pass *, 1> LU;
1658 LU.push_back(FoundPass);
1659 FPP->setLastUser(LU, P);
1662 /// Return function pass corresponding to PassInfo PI, that is
1663 /// required by module pass MP. Instantiate analysis pass, by using
1664 /// its runOnFunction() for function F.
1665 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1666 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1667 assert(FPP && "Unable to find on the fly pass");
1669 FPP->releaseMemoryOnTheFly();
1670 FPP->run(F);
1671 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1675 //===----------------------------------------------------------------------===//
1676 // PassManagerImpl implementation
1679 /// run - Execute all of the passes scheduled for execution. Keep track of
1680 /// whether any of the passes modifies the module, and if so, return true.
1681 bool PassManagerImpl::run(Module &M) {
1682 bool Changed = false;
1683 TimingInfo::createTheTimeInfo();
1685 dumpArguments();
1686 dumpPasses();
1688 for (ImmutablePass *ImPass : getImmutablePasses())
1689 Changed |= ImPass->doInitialization(M);
1691 initializeAllAnalysisInfo();
1692 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1693 Changed |= getContainedManager(Index)->runOnModule(M);
1694 M.getContext().yield();
1697 for (ImmutablePass *ImPass : getImmutablePasses())
1698 Changed |= ImPass->doFinalization(M);
1700 return Changed;
1703 //===----------------------------------------------------------------------===//
1704 // PassManager implementation
1706 /// Create new pass manager
1707 PassManager::PassManager() {
1708 PM = new PassManagerImpl();
1709 // PM is the top level manager
1710 PM->setTopLevelManager(PM);
1713 PassManager::~PassManager() {
1714 delete PM;
1717 void PassManager::add(Pass *P) {
1718 PM->add(P);
1721 /// run - Execute all of the passes scheduled for execution. Keep track of
1722 /// whether any of the passes modifies the module, and if so, return true.
1723 bool PassManager::run(Module &M) {
1724 return PM->run(M);
1727 //===----------------------------------------------------------------------===//
1728 // TimingInfo implementation
1730 bool llvm::TimePassesIsEnabled = false;
1731 static cl::opt<bool,true>
1732 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1733 cl::desc("Time each pass, printing elapsed time for each on exit"));
1735 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1736 // a non-null value (if the -time-passes option is enabled) or it leaves it
1737 // null. It may be called multiple times.
1738 void TimingInfo::createTheTimeInfo() {
1739 if (!TimePassesIsEnabled || TheTimeInfo) return;
1741 // Constructed the first time this is called, iff -time-passes is enabled.
1742 // This guarantees that the object will be constructed before static globals,
1743 // thus it will be destroyed before them.
1744 static ManagedStatic<TimingInfo> TTI;
1745 TheTimeInfo = &*TTI;
1748 /// If TimingInfo is enabled then start pass timer.
1749 Timer *llvm::getPassTimer(Pass *P) {
1750 if (TheTimeInfo)
1751 return TheTimeInfo->getPassTimer(P);
1752 return nullptr;
1755 //===----------------------------------------------------------------------===//
1756 // PMStack implementation
1759 // Pop Pass Manager from the stack and clear its analysis info.
1760 void PMStack::pop() {
1762 PMDataManager *Top = this->top();
1763 Top->initializeAnalysisInfo();
1765 S.pop_back();
1768 // Push PM on the stack and set its top level manager.
1769 void PMStack::push(PMDataManager *PM) {
1770 assert(PM && "Unable to push. Pass Manager expected");
1771 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1773 if (!this->empty()) {
1774 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1775 && "pushing bad pass manager to PMStack");
1776 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1778 assert(TPM && "Unable to find top level manager");
1779 TPM->addIndirectPassManager(PM);
1780 PM->setTopLevelManager(TPM);
1781 PM->setDepth(this->top()->getDepth()+1);
1782 } else {
1783 assert((PM->getPassManagerType() == PMT_ModulePassManager
1784 || PM->getPassManagerType() == PMT_FunctionPassManager)
1785 && "pushing bad pass manager to PMStack");
1786 PM->setDepth(1);
1789 S.push_back(PM);
1792 // Dump content of the pass manager stack.
1793 LLVM_DUMP_METHOD void PMStack::dump() const {
1794 for (PMDataManager *Manager : S)
1795 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1797 if (!S.empty())
1798 dbgs() << '\n';
1801 /// Find appropriate Module Pass Manager in the PM Stack and
1802 /// add self into that manager.
1803 void ModulePass::assignPassManager(PMStack &PMS,
1804 PassManagerType PreferredType) {
1805 // Find Module Pass Manager
1806 while (!PMS.empty()) {
1807 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1808 if (TopPMType == PreferredType)
1809 break; // We found desired pass manager
1810 else if (TopPMType > PMT_ModulePassManager)
1811 PMS.pop(); // Pop children pass managers
1812 else
1813 break;
1815 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1816 PMS.top()->add(this);
1819 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1820 /// in the PM Stack and add self into that manager.
1821 void FunctionPass::assignPassManager(PMStack &PMS,
1822 PassManagerType PreferredType) {
1824 // Find Function Pass Manager
1825 while (!PMS.empty()) {
1826 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1827 PMS.pop();
1828 else
1829 break;
1832 // Create new Function Pass Manager if needed.
1833 FPPassManager *FPP;
1834 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1835 FPP = (FPPassManager *)PMS.top();
1836 } else {
1837 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1838 PMDataManager *PMD = PMS.top();
1840 // [1] Create new Function Pass Manager
1841 FPP = new FPPassManager();
1842 FPP->populateInheritedAnalysis(PMS);
1844 // [2] Set up new manager's top level manager
1845 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1846 TPM->addIndirectPassManager(FPP);
1848 // [3] Assign manager to manage this new manager. This may create
1849 // and push new managers into PMS
1850 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1852 // [4] Push new manager into PMS
1853 PMS.push(FPP);
1856 // Assign FPP as the manager of this pass.
1857 FPP->add(this);
1860 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1861 /// in the PM Stack and add self into that manager.
1862 void BasicBlockPass::assignPassManager(PMStack &PMS,
1863 PassManagerType PreferredType) {
1864 BBPassManager *BBP;
1866 // Basic Pass Manager is a leaf pass manager. It does not handle
1867 // any other pass manager.
1868 if (!PMS.empty() &&
1869 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1870 BBP = (BBPassManager *)PMS.top();
1871 } else {
1872 // If leaf manager is not Basic Block Pass manager then create new
1873 // basic Block Pass manager.
1874 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1875 PMDataManager *PMD = PMS.top();
1877 // [1] Create new Basic Block Manager
1878 BBP = new BBPassManager();
1880 // [2] Set up new manager's top level manager
1881 // Basic Block Pass Manager does not live by itself
1882 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1883 TPM->addIndirectPassManager(BBP);
1885 // [3] Assign manager to manage this new manager. This may create
1886 // and push new managers into PMS
1887 BBP->assignPassManager(PMS, PreferredType);
1889 // [4] Push new manager into PMS
1890 PMS.push(BBP);
1893 // Assign BBP as the manager of this pass.
1894 BBP->add(this);
1897 PassManagerBase::~PassManagerBase() {}