1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the legacy LLVM Pass Manager infrastructure.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/LegacyPassManager.h"
14 #include "llvm/ADT/MapVector.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/IR/DiagnosticInfo.h"
17 #include "llvm/IR/IRPrintingPasses.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/LegacyPassManagers.h"
20 #include "llvm/IR/LegacyPassNameParser.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/PassTimingInfo.h"
23 #include "llvm/Support/Chrono.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/Mutex.h"
30 #include "llvm/Support/TimeProfiler.h"
31 #include "llvm/Support/Timer.h"
32 #include "llvm/Support/raw_ostream.h"
34 #include <unordered_set>
37 // See PassManagers.h for Pass Manager infrastructure overview.
39 //===----------------------------------------------------------------------===//
40 // Pass debugging information. Often it is useful to find out what pass is
41 // running when a crash occurs in a utility. When this library is compiled with
42 // debugging on, a command line option (--debug-pass) is enabled that causes the
43 // pass name to be printed before it executes.
47 // Different debug levels that can be enabled...
49 Disabled, Arguments, Structure, Executions, Details
53 static cl::opt<enum PassDebugLevel>
54 PassDebugging("debug-pass", cl::Hidden,
55 cl::desc("Print PassManager debugging information"),
57 clEnumVal(Disabled , "disable debug output"),
58 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
59 clEnumVal(Structure , "print pass structure before run()"),
60 clEnumVal(Executions, "print pass name before it is executed"),
61 clEnumVal(Details , "print pass details when it is executed")));
64 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
68 // Print IR out before/after specified passes.
70 PrintBefore("print-before",
71 llvm::cl::desc("Print IR before specified passes"),
75 PrintAfter("print-after",
76 llvm::cl::desc("Print IR after specified passes"),
79 static cl::opt<bool> PrintBeforeAll("print-before-all",
80 llvm::cl::desc("Print IR before each pass"),
81 cl::init(false), cl::Hidden);
82 static cl::opt<bool> PrintAfterAll("print-after-all",
83 llvm::cl::desc("Print IR after each pass"),
84 cl::init(false), cl::Hidden);
87 PrintModuleScope("print-module-scope",
88 cl::desc("When printing IR for print-[before|after]{-all} "
89 "always print a module IR"),
90 cl::init(false), cl::Hidden);
92 static cl::list<std::string>
93 PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
94 cl::desc("Only print IR for functions whose name "
95 "match this for all print-[before|after][-all] "
97 cl::CommaSeparated, cl::Hidden);
99 /// This is a helper to determine whether to print IR before or
102 bool llvm::shouldPrintBeforePass() {
103 return PrintBeforeAll || !PrintBefore.empty();
106 bool llvm::shouldPrintAfterPass() {
107 return PrintAfterAll || !PrintAfter.empty();
110 static bool ShouldPrintBeforeOrAfterPass(StringRef PassID,
111 PassOptionList &PassesToPrint) {
112 for (auto *PassInf : PassesToPrint) {
114 if (PassInf->getPassArgument() == PassID) {
121 bool llvm::shouldPrintBeforePass(StringRef PassID) {
122 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefore);
125 bool llvm::shouldPrintAfterPass(StringRef PassID) {
126 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
129 bool llvm::forcePrintModuleIR() { return PrintModuleScope; }
131 bool llvm::isFunctionInPrintList(StringRef FunctionName) {
132 static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
133 PrintFuncsList.end());
134 return PrintFuncNames.empty() ||
135 PrintFuncNames.count(std::string(FunctionName));
137 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
138 /// or higher is specified.
139 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
140 return PassDebugging >= Executions;
143 unsigned PMDataManager::initSizeRemarkInfo(
144 Module &M, StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount) {
145 // Only calculate getInstructionCount if the size-info remark is requested.
146 unsigned InstrCount = 0;
148 // Collect instruction counts for every function. We'll use this to emit
149 // per-function size remarks later.
150 for (Function &F : M) {
151 unsigned FCount = F.getInstructionCount();
153 // Insert a record into FunctionToInstrCount keeping track of the current
154 // size of the function as the first member of a pair. Set the second
155 // member to 0; if the function is deleted by the pass, then when we get
156 // here, we'll be able to let the user know that F no longer contributes to
158 FunctionToInstrCount[F.getName().str()] =
159 std::pair<unsigned, unsigned>(FCount, 0);
160 InstrCount += FCount;
165 void PMDataManager::emitInstrCountChangedRemark(
166 Pass *P, Module &M, int64_t Delta, unsigned CountBefore,
167 StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount,
169 // If it's a pass manager, don't emit a remark. (This hinges on the assumption
170 // that the only passes that return non-null with getAsPMDataManager are pass
171 // managers.) The reason we have to do this is to avoid emitting remarks for
173 if (P->getAsPMDataManager())
176 // Set to true if this isn't a module pass or CGSCC pass.
177 bool CouldOnlyImpactOneFunction = (F != nullptr);
179 // Helper lambda that updates the changes to the size of some function.
180 auto UpdateFunctionChanges =
181 [&FunctionToInstrCount](Function &MaybeChangedFn) {
182 // Update the total module count.
183 unsigned FnSize = MaybeChangedFn.getInstructionCount();
184 auto It = FunctionToInstrCount.find(MaybeChangedFn.getName());
186 // If we created a new function, then we need to add it to the map and
187 // say that it changed from 0 instructions to FnSize.
188 if (It == FunctionToInstrCount.end()) {
189 FunctionToInstrCount[MaybeChangedFn.getName()] =
190 std::pair<unsigned, unsigned>(0, FnSize);
193 // Insert the new function size into the second member of the pair. This
194 // tells us whether or not this function changed in size.
195 It->second.second = FnSize;
198 // We need to initially update all of the function sizes.
199 // If no function was passed in, then we're either a module pass or an
201 if (!CouldOnlyImpactOneFunction)
202 std::for_each(M.begin(), M.end(), UpdateFunctionChanges);
204 UpdateFunctionChanges(*F);
206 // Do we have a function we can use to emit a remark?
207 if (!CouldOnlyImpactOneFunction) {
208 // We need a function containing at least one basic block in order to output
209 // remarks. Since it's possible that the first function in the module
210 // doesn't actually contain a basic block, we have to go and find one that's
211 // suitable for emitting remarks.
212 auto It = std::find_if(M.begin(), M.end(),
213 [](const Function &Fn) { return !Fn.empty(); });
215 // Didn't find a function. Quit.
219 // We found a function containing at least one basic block.
222 int64_t CountAfter = static_cast<int64_t>(CountBefore) + Delta;
223 BasicBlock &BB = *F->begin();
224 OptimizationRemarkAnalysis R("size-info", "IRSizeChange",
225 DiagnosticLocation(), &BB);
226 // FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This
227 // would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.
228 R << DiagnosticInfoOptimizationBase::Argument("Pass", P->getPassName())
229 << ": IR instruction count changed from "
230 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore)
232 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter)
234 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta);
235 F->getContext().diagnose(R); // Not using ORE for layering reasons.
237 // Emit per-function size change remarks separately.
238 std::string PassName = P->getPassName().str();
240 // Helper lambda that emits a remark when the size of a function has changed.
241 auto EmitFunctionSizeChangedRemark = [&FunctionToInstrCount, &F, &BB,
242 &PassName](StringRef Fname) {
243 unsigned FnCountBefore, FnCountAfter;
244 std::pair<unsigned, unsigned> &Change = FunctionToInstrCount[Fname];
245 std::tie(FnCountBefore, FnCountAfter) = Change;
246 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
247 static_cast<int64_t>(FnCountBefore);
252 // FIXME: We shouldn't use BB for the location here. Unfortunately, because
253 // the function that we're looking at could have been deleted, we can't use
254 // it for the source location. We *want* remarks when a function is deleted
255 // though, so we're kind of stuck here as is. (This remark, along with the
256 // whole-module size change remarks really ought not to have source
257 // locations at all.)
258 OptimizationRemarkAnalysis FR("size-info", "FunctionIRSizeChange",
259 DiagnosticLocation(), &BB);
260 FR << DiagnosticInfoOptimizationBase::Argument("Pass", PassName)
262 << DiagnosticInfoOptimizationBase::Argument("Function", Fname)
263 << ": IR instruction count changed from "
264 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore",
267 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter",
270 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", FnDelta);
271 F->getContext().diagnose(FR);
273 // Update the function size.
274 Change.first = FnCountAfter;
277 // Are we looking at more than one function? If so, emit remarks for all of
278 // the functions in the module. Otherwise, only emit one remark.
279 if (!CouldOnlyImpactOneFunction)
280 std::for_each(FunctionToInstrCount.keys().begin(),
281 FunctionToInstrCount.keys().end(),
282 EmitFunctionSizeChangedRemark);
284 EmitFunctionSizeChangedRemark(F->getName().str());
287 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
289 OS << "Releasing pass '";
291 OS << "Running pass '";
293 OS << P->getPassName() << "'";
296 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
305 if (isa<Function>(V))
307 else if (isa<BasicBlock>(V))
313 V->printAsOperand(OS, /*PrintType=*/false, M);
319 //===----------------------------------------------------------------------===//
320 // FunctionPassManagerImpl
322 /// FunctionPassManagerImpl manages FPPassManagers
323 class FunctionPassManagerImpl : public Pass,
324 public PMDataManager,
325 public PMTopLevelManager {
326 virtual void anchor();
331 explicit FunctionPassManagerImpl() :
332 Pass(PT_PassManager, ID), PMDataManager(),
333 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
335 /// \copydoc FunctionPassManager::add()
340 /// createPrinterPass - Get a function printer pass.
341 Pass *createPrinterPass(raw_ostream &O,
342 const std::string &Banner) const override {
343 return createPrintFunctionPass(O, Banner);
346 // Prepare for running an on the fly pass, freeing memory if needed
347 // from a previous run.
348 void releaseMemoryOnTheFly();
350 /// run - Execute all of the passes scheduled for execution. Keep track of
351 /// whether any of the passes modifies the module, and if so, return true.
352 bool run(Function &F);
354 /// doInitialization - Run all of the initializers for the function passes.
356 bool doInitialization(Module &M) override;
358 /// doFinalization - Run all of the finalizers for the function passes.
360 bool doFinalization(Module &M) override;
363 PMDataManager *getAsPMDataManager() override { return this; }
364 Pass *getAsPass() override { return this; }
365 PassManagerType getTopLevelPassManagerType() override {
366 return PMT_FunctionPassManager;
369 /// Pass Manager itself does not invalidate any analysis info.
370 void getAnalysisUsage(AnalysisUsage &Info) const override {
371 Info.setPreservesAll();
374 FPPassManager *getContainedManager(unsigned N) {
375 assert(N < PassManagers.size() && "Pass number out of range!");
376 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
380 void dumpPassStructure(unsigned Offset) override {
381 for (unsigned I = 0; I < getNumContainedManagers(); ++I)
382 getContainedManager(I)->dumpPassStructure(Offset);
386 void FunctionPassManagerImpl::anchor() {}
388 char FunctionPassManagerImpl::ID = 0;
390 //===----------------------------------------------------------------------===//
391 // FunctionPassManagerImpl implementation
393 bool FunctionPassManagerImpl::doInitialization(Module &M) {
394 bool Changed = false;
399 for (ImmutablePass *ImPass : getImmutablePasses())
400 Changed |= ImPass->doInitialization(M);
402 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
403 Changed |= getContainedManager(Index)->doInitialization(M);
408 bool FunctionPassManagerImpl::doFinalization(Module &M) {
409 bool Changed = false;
411 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
412 Changed |= getContainedManager(Index)->doFinalization(M);
414 for (ImmutablePass *ImPass : getImmutablePasses())
415 Changed |= ImPass->doFinalization(M);
420 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
423 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
424 FPPassManager *FPPM = getContainedManager(Index);
425 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
426 FPPM->getContainedPass(Index)->releaseMemory();
432 // Execute all the passes managed by this top level manager.
433 // Return true if any function is modified by a pass.
434 bool FunctionPassManagerImpl::run(Function &F) {
435 bool Changed = false;
437 initializeAllAnalysisInfo();
438 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
439 Changed |= getContainedManager(Index)->runOnFunction(F);
440 F.getContext().yield();
443 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
444 getContainedManager(Index)->cleanup();
449 } // namespace legacy
453 //===----------------------------------------------------------------------===//
456 /// MPPassManager manages ModulePasses and function pass managers.
457 /// It batches all Module passes and function pass managers together and
458 /// sequences them to process one module.
459 class MPPassManager : public Pass, public PMDataManager {
462 explicit MPPassManager() :
463 Pass(PT_PassManager, ID), PMDataManager() { }
465 // Delete on the fly managers.
466 ~MPPassManager() override {
467 for (auto &OnTheFlyManager : OnTheFlyManagers) {
468 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
473 /// createPrinterPass - Get a module printer pass.
474 Pass *createPrinterPass(raw_ostream &O,
475 const std::string &Banner) const override {
476 return createPrintModulePass(O, Banner);
479 /// run - Execute all of the passes scheduled for execution. Keep track of
480 /// whether any of the passes modifies the module, and if so, return true.
481 bool runOnModule(Module &M);
483 using llvm::Pass::doInitialization;
484 using llvm::Pass::doFinalization;
486 /// Pass Manager itself does not invalidate any analysis info.
487 void getAnalysisUsage(AnalysisUsage &Info) const override {
488 Info.setPreservesAll();
491 /// Add RequiredPass into list of lower level passes required by pass P.
492 /// RequiredPass is run on the fly by Pass Manager when P requests it
493 /// through getAnalysis interface.
494 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
496 /// Return function pass corresponding to PassInfo PI, that is
497 /// required by module pass MP. Instantiate analysis pass, by using
498 /// its runOnFunction() for function F.
499 std::tuple<Pass *, bool> getOnTheFlyPass(Pass *MP, AnalysisID PI,
500 Function &F) override;
502 StringRef getPassName() const override { return "Module Pass Manager"; }
504 PMDataManager *getAsPMDataManager() override { return this; }
505 Pass *getAsPass() override { return this; }
507 // Print passes managed by this manager
508 void dumpPassStructure(unsigned Offset) override {
509 dbgs().indent(Offset*2) << "ModulePass Manager\n";
510 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
511 ModulePass *MP = getContainedPass(Index);
512 MP->dumpPassStructure(Offset + 1);
513 MapVector<Pass *, legacy::FunctionPassManagerImpl *>::const_iterator I =
514 OnTheFlyManagers.find(MP);
515 if (I != OnTheFlyManagers.end())
516 I->second->dumpPassStructure(Offset + 2);
517 dumpLastUses(MP, Offset+1);
521 ModulePass *getContainedPass(unsigned N) {
522 assert(N < PassVector.size() && "Pass number out of range!");
523 return static_cast<ModulePass *>(PassVector[N]);
526 PassManagerType getPassManagerType() const override {
527 return PMT_ModulePassManager;
531 /// Collection of on the fly FPPassManagers. These managers manage
532 /// function passes that are required by module passes.
533 MapVector<Pass *, legacy::FunctionPassManagerImpl *> OnTheFlyManagers;
536 char MPPassManager::ID = 0;
537 } // End anonymous namespace
541 //===----------------------------------------------------------------------===//
545 /// PassManagerImpl manages MPPassManagers
546 class PassManagerImpl : public Pass,
547 public PMDataManager,
548 public PMTopLevelManager {
549 virtual void anchor();
553 explicit PassManagerImpl() :
554 Pass(PT_PassManager, ID), PMDataManager(),
555 PMTopLevelManager(new MPPassManager()) {}
557 /// \copydoc PassManager::add()
562 /// createPrinterPass - Get a module printer pass.
563 Pass *createPrinterPass(raw_ostream &O,
564 const std::string &Banner) const override {
565 return createPrintModulePass(O, Banner);
568 /// run - Execute all of the passes scheduled for execution. Keep track of
569 /// whether any of the passes modifies the module, and if so, return true.
572 using llvm::Pass::doInitialization;
573 using llvm::Pass::doFinalization;
575 /// Pass Manager itself does not invalidate any analysis info.
576 void getAnalysisUsage(AnalysisUsage &Info) const override {
577 Info.setPreservesAll();
580 PMDataManager *getAsPMDataManager() override { return this; }
581 Pass *getAsPass() override { return this; }
582 PassManagerType getTopLevelPassManagerType() override {
583 return PMT_ModulePassManager;
586 MPPassManager *getContainedManager(unsigned N) {
587 assert(N < PassManagers.size() && "Pass number out of range!");
588 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
593 void PassManagerImpl::anchor() {}
595 char PassManagerImpl::ID = 0;
597 //===----------------------------------------------------------------------===//
598 // PassManagerImpl implementation
601 /// run - Execute all of the passes scheduled for execution. Keep track of
602 /// whether any of the passes modifies the module, and if so, return true.
603 bool PassManagerImpl::run(Module &M) {
604 bool Changed = false;
609 for (ImmutablePass *ImPass : getImmutablePasses())
610 Changed |= ImPass->doInitialization(M);
612 initializeAllAnalysisInfo();
613 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
614 Changed |= getContainedManager(Index)->runOnModule(M);
615 M.getContext().yield();
618 for (ImmutablePass *ImPass : getImmutablePasses())
619 Changed |= ImPass->doFinalization(M);
623 } // namespace legacy
626 //===----------------------------------------------------------------------===//
627 // PMTopLevelManager implementation
629 /// Initialize top level manager. Create first pass manager.
630 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
631 PMDM->setTopLevelManager(this);
632 addPassManager(PMDM);
633 activeStack.push(PMDM);
636 /// Set pass P as the last user of the given analysis passes.
638 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
640 if (P->getResolver())
641 PDepth = P->getResolver()->getPMDataManager().getDepth();
643 for (Pass *AP : AnalysisPasses) {
649 // Update the last users of passes that are required transitive by AP.
650 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
651 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
652 SmallVector<Pass *, 12> LastUses;
653 SmallVector<Pass *, 12> LastPMUses;
654 for (AnalysisID ID : IDs) {
655 Pass *AnalysisPass = findAnalysisPass(ID);
656 assert(AnalysisPass && "Expected analysis pass to exist.");
657 AnalysisResolver *AR = AnalysisPass->getResolver();
658 assert(AR && "Expected analysis resolver to exist.");
659 unsigned APDepth = AR->getPMDataManager().getDepth();
661 if (PDepth == APDepth)
662 LastUses.push_back(AnalysisPass);
663 else if (PDepth > APDepth)
664 LastPMUses.push_back(AnalysisPass);
667 setLastUser(LastUses, P);
669 // If this pass has a corresponding pass manager, push higher level
670 // analysis to this pass manager.
671 if (P->getResolver())
672 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
675 // If AP is the last user of other passes then make P last user of
677 for (auto LU : LastUser) {
679 // DenseMap iterator is not invalidated here because
680 // this is just updating existing entries.
681 LastUser[LU.first] = P;
686 /// Collect passes whose last user is P
687 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
689 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
690 InversedLastUser.find(P);
691 if (DMI == InversedLastUser.end())
694 SmallPtrSet<Pass *, 8> &LU = DMI->second;
695 for (Pass *LUP : LU) {
696 LastUses.push_back(LUP);
701 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
702 AnalysisUsage *AnUsage = nullptr;
703 auto DMI = AnUsageMap.find(P);
704 if (DMI != AnUsageMap.end())
705 AnUsage = DMI->second;
707 // Look up the analysis usage from the pass instance (different instances
708 // of the same pass can produce different results), but unique the
709 // resulting object to reduce memory usage. This helps to greatly reduce
710 // memory usage when we have many instances of only a few pass types
711 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
714 P->getAnalysisUsage(AU);
716 AUFoldingSetNode* Node = nullptr;
718 AUFoldingSetNode::Profile(ID, AU);
720 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
723 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
724 UniqueAnalysisUsages.InsertNode(Node, IP);
726 assert(Node && "cached analysis usage must be non null");
728 AnUsageMap[P] = &Node->AU;
734 /// Schedule pass P for execution. Make sure that passes required by
735 /// P are run before P is run. Update analysis info maintained by
736 /// the manager. Remove dead passes. This is a recursive function.
737 void PMTopLevelManager::schedulePass(Pass *P) {
739 // TODO : Allocate function manager for this pass, other wise required set
740 // may be inserted into previous function manager
742 // Give pass a chance to prepare the stage.
743 P->preparePassManager(activeStack);
745 // If P is an analysis pass and it is available then do not
746 // generate the analysis again. Stale analysis info should not be
747 // available at this point.
748 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
749 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
750 // Remove any cached AnalysisUsage information.
756 AnalysisUsage *AnUsage = findAnalysisUsage(P);
758 bool checkAnalysis = true;
759 while (checkAnalysis) {
760 checkAnalysis = false;
762 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
763 for (const AnalysisID ID : RequiredSet) {
765 Pass *AnalysisPass = findAnalysisPass(ID);
767 const PassInfo *PI = findAnalysisPassInfo(ID);
770 // Pass P is not in the global PassRegistry
771 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
772 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
773 dbgs() << "Required Passes:" << "\n";
774 for (const AnalysisID ID2 : RequiredSet) {
777 Pass *AnalysisPass2 = findAnalysisPass(ID2);
779 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
781 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
782 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
783 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
788 assert(PI && "Expected required passes to be initialized");
789 AnalysisPass = PI->createPass();
790 if (P->getPotentialPassManagerType () ==
791 AnalysisPass->getPotentialPassManagerType())
792 // Schedule analysis pass that is managed by the same pass manager.
793 schedulePass(AnalysisPass);
794 else if (P->getPotentialPassManagerType () >
795 AnalysisPass->getPotentialPassManagerType()) {
796 // Schedule analysis pass that is managed by a new manager.
797 schedulePass(AnalysisPass);
798 // Recheck analysis passes to ensure that required analyses that
799 // are already checked are still available.
800 checkAnalysis = true;
802 // Do not schedule this analysis. Lower level analysis
803 // passes are run on the fly.
809 // Now all required passes are available.
810 if (ImmutablePass *IP = P->getAsImmutablePass()) {
811 // P is a immutable pass and it will be managed by this
812 // top level manager. Set up analysis resolver to connect them.
813 PMDataManager *DM = getAsPMDataManager();
814 AnalysisResolver *AR = new AnalysisResolver(*DM);
816 DM->initializeAnalysisImpl(P);
817 addImmutablePass(IP);
818 DM->recordAvailableAnalysis(IP);
822 if (PI && !PI->isAnalysis() && shouldPrintBeforePass(PI->getPassArgument())) {
823 Pass *PP = P->createPrinterPass(
824 dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
825 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
828 // Add the requested pass to the best available pass manager.
829 P->assignPassManager(activeStack, getTopLevelPassManagerType());
831 if (PI && !PI->isAnalysis() && shouldPrintAfterPass(PI->getPassArgument())) {
832 Pass *PP = P->createPrinterPass(
833 dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
834 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
838 /// Find the pass that implements Analysis AID. Search immutable
839 /// passes and all pass managers. If desired pass is not found
840 /// then return NULL.
841 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
842 // For immutable passes we have a direct mapping from ID to pass, so check
844 if (Pass *P = ImmutablePassMap.lookup(AID))
847 // Check pass managers
848 for (PMDataManager *PassManager : PassManagers)
849 if (Pass *P = PassManager->findAnalysisPass(AID, false))
852 // Check other pass managers
853 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
854 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
860 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
861 const PassInfo *&PI = AnalysisPassInfos[AID];
863 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
865 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
866 "The pass info pointer changed for an analysis ID!");
871 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
873 ImmutablePasses.push_back(P);
875 // Add this pass to the map from its analysis ID. We clobber any prior runs
876 // of the pass in the map so that the last one added is the one found when
878 AnalysisID AID = P->getPassID();
879 ImmutablePassMap[AID] = P;
881 // Also add any interfaces implemented by the immutable pass to the map for
883 const PassInfo *PassInf = findAnalysisPassInfo(AID);
884 assert(PassInf && "Expected all immutable passes to be initialized");
885 for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
886 ImmutablePassMap[ImmPI->getTypeInfo()] = P;
889 // Print passes managed by this top level manager.
890 void PMTopLevelManager::dumpPasses() const {
892 if (PassDebugging < Structure)
895 // Print out the immutable passes
896 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
897 ImmutablePasses[i]->dumpPassStructure(0);
900 // Every class that derives from PMDataManager also derives from Pass
901 // (sometimes indirectly), but there's no inheritance relationship
902 // between PMDataManager and Pass, so we have to getAsPass to get
903 // from a PMDataManager* to a Pass*.
904 for (PMDataManager *Manager : PassManagers)
905 Manager->getAsPass()->dumpPassStructure(1);
908 void PMTopLevelManager::dumpArguments() const {
910 if (PassDebugging < Arguments)
913 dbgs() << "Pass Arguments: ";
914 for (ImmutablePass *P : ImmutablePasses)
915 if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
916 assert(PI && "Expected all immutable passes to be initialized");
917 if (!PI->isAnalysisGroup())
918 dbgs() << " -" << PI->getPassArgument();
920 for (PMDataManager *PM : PassManagers)
921 PM->dumpPassArguments();
925 void PMTopLevelManager::initializeAllAnalysisInfo() {
926 for (PMDataManager *PM : PassManagers)
927 PM->initializeAnalysisInfo();
929 // Initailize other pass managers
930 for (PMDataManager *IPM : IndirectPassManagers)
931 IPM->initializeAnalysisInfo();
933 for (auto LU : LastUser) {
934 SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
940 PMTopLevelManager::~PMTopLevelManager() {
941 for (PMDataManager *PM : PassManagers)
944 for (ImmutablePass *P : ImmutablePasses)
948 //===----------------------------------------------------------------------===//
949 // PMDataManager implementation
951 /// Augement AvailableAnalysis by adding analysis made available by pass P.
952 void PMDataManager::recordAvailableAnalysis(Pass *P) {
953 AnalysisID PI = P->getPassID();
955 AvailableAnalysis[PI] = P;
957 assert(!AvailableAnalysis.empty());
959 // This pass is the current implementation of all of the interfaces it
960 // implements as well.
961 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
963 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
964 for (unsigned i = 0, e = II.size(); i != e; ++i)
965 AvailableAnalysis[II[i]->getTypeInfo()] = P;
968 // Return true if P preserves high level analysis used by other
969 // passes managed by this manager
970 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
971 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
972 if (AnUsage->getPreservesAll())
975 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
976 for (Pass *P1 : HigherLevelAnalysis) {
977 if (P1->getAsImmutablePass() == nullptr &&
978 !is_contained(PreservedSet, P1->getPassID()))
985 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
986 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
987 // Don't do this unless assertions are enabled.
991 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
992 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
994 // Verify preserved analysis
995 for (AnalysisID AID : PreservedSet) {
996 if (Pass *AP = findAnalysisPass(AID, true)) {
997 TimeRegion PassTimer(getPassTimer(AP));
998 AP->verifyAnalysis();
1003 /// Remove Analysis not preserved by Pass P
1004 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
1005 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1006 if (AnUsage->getPreservesAll())
1009 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
1010 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
1011 E = AvailableAnalysis.end(); I != E; ) {
1012 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
1013 if (Info->second->getAsImmutablePass() == nullptr &&
1014 !is_contained(PreservedSet, Info->first)) {
1015 // Remove this analysis
1016 if (PassDebugging >= Details) {
1017 Pass *S = Info->second;
1018 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
1019 dbgs() << S->getPassName() << "'\n";
1021 AvailableAnalysis.erase(Info);
1025 // Check inherited analysis also. If P is not preserving analysis
1026 // provided by parent manager then remove it here.
1027 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
1029 if (!InheritedAnalysis[Index])
1032 for (DenseMap<AnalysisID, Pass*>::iterator
1033 I = InheritedAnalysis[Index]->begin(),
1034 E = InheritedAnalysis[Index]->end(); I != E; ) {
1035 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
1036 if (Info->second->getAsImmutablePass() == nullptr &&
1037 !is_contained(PreservedSet, Info->first)) {
1038 // Remove this analysis
1039 if (PassDebugging >= Details) {
1040 Pass *S = Info->second;
1041 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
1042 dbgs() << S->getPassName() << "'\n";
1044 InheritedAnalysis[Index]->erase(Info);
1050 /// Remove analysis passes that are not used any longer
1051 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
1052 enum PassDebuggingString DBG_STR) {
1054 SmallVector<Pass *, 12> DeadPasses;
1056 // If this is a on the fly manager then it does not have TPM.
1060 TPM->collectLastUses(DeadPasses, P);
1062 if (PassDebugging >= Details && !DeadPasses.empty()) {
1063 dbgs() << " -*- '" << P->getPassName();
1064 dbgs() << "' is the last user of following pass instances.";
1065 dbgs() << " Free these instances\n";
1068 for (Pass *P : DeadPasses)
1069 freePass(P, Msg, DBG_STR);
1072 void PMDataManager::freePass(Pass *P, StringRef Msg,
1073 enum PassDebuggingString DBG_STR) {
1074 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
1077 // If the pass crashes releasing memory, remember this.
1078 PassManagerPrettyStackEntry X(P);
1079 TimeRegion PassTimer(getPassTimer(P));
1084 AnalysisID PI = P->getPassID();
1085 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
1086 // Remove the pass itself (if it is not already removed).
1087 AvailableAnalysis.erase(PI);
1089 // Remove all interfaces this pass implements, for which it is also
1090 // listed as the available implementation.
1091 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
1092 for (unsigned i = 0, e = II.size(); i != e; ++i) {
1093 DenseMap<AnalysisID, Pass*>::iterator Pos =
1094 AvailableAnalysis.find(II[i]->getTypeInfo());
1095 if (Pos != AvailableAnalysis.end() && Pos->second == P)
1096 AvailableAnalysis.erase(Pos);
1101 /// Add pass P into the PassVector. Update
1102 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
1103 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
1104 // This manager is going to manage pass P. Set up analysis resolver
1106 AnalysisResolver *AR = new AnalysisResolver(*this);
1109 // If a FunctionPass F is the last user of ModulePass info M
1110 // then the F's manager, not F, records itself as a last user of M.
1111 SmallVector<Pass *, 12> TransferLastUses;
1113 if (!ProcessAnalysis) {
1115 PassVector.push_back(P);
1119 // At the moment, this pass is the last user of all required passes.
1120 SmallVector<Pass *, 12> LastUses;
1121 SmallVector<Pass *, 8> UsedPasses;
1122 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1124 unsigned PDepth = this->getDepth();
1126 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
1127 for (Pass *PUsed : UsedPasses) {
1128 unsigned RDepth = 0;
1130 assert(PUsed->getResolver() && "Analysis Resolver is not set");
1131 PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
1132 RDepth = DM.getDepth();
1134 if (PDepth == RDepth)
1135 LastUses.push_back(PUsed);
1136 else if (PDepth > RDepth) {
1137 // Let the parent claim responsibility of last use
1138 TransferLastUses.push_back(PUsed);
1139 // Keep track of higher level analysis used by this manager.
1140 HigherLevelAnalysis.push_back(PUsed);
1142 llvm_unreachable("Unable to accommodate Used Pass");
1145 // Set P as P's last user until someone starts using P.
1146 // However, if P is a Pass Manager then it does not need
1147 // to record its last user.
1148 if (!P->getAsPMDataManager())
1149 LastUses.push_back(P);
1150 TPM->setLastUser(LastUses, P);
1152 if (!TransferLastUses.empty()) {
1153 Pass *My_PM = getAsPass();
1154 TPM->setLastUser(TransferLastUses, My_PM);
1155 TransferLastUses.clear();
1158 // Now, take care of required analyses that are not available.
1159 for (AnalysisID ID : ReqAnalysisNotAvailable) {
1160 const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1161 Pass *AnalysisPass = PI->createPass();
1162 this->addLowerLevelRequiredPass(P, AnalysisPass);
1165 // Take a note of analysis required and made available by this pass.
1166 // Remove the analysis not preserved by this pass
1167 removeNotPreservedAnalysis(P);
1168 recordAvailableAnalysis(P);
1171 PassVector.push_back(P);
1175 /// Populate UP with analysis pass that are used or required by
1176 /// pass P and are available. Populate RP_NotAvail with analysis
1177 /// pass that are required by pass P but are not available.
1178 void PMDataManager::collectRequiredAndUsedAnalyses(
1179 SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1181 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1183 for (const auto &UsedID : AnUsage->getUsedSet())
1184 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1185 UP.push_back(AnalysisPass);
1187 for (const auto &RequiredID : AnUsage->getRequiredSet())
1188 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1189 UP.push_back(AnalysisPass);
1191 RP_NotAvail.push_back(RequiredID);
1193 for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1194 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1195 UP.push_back(AnalysisPass);
1197 RP_NotAvail.push_back(RequiredID);
1200 // All Required analyses should be available to the pass as it runs! Here
1201 // we fill in the AnalysisImpls member of the pass so that it can
1202 // successfully use the getAnalysis() method to retrieve the
1203 // implementations it needs.
1205 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1206 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1208 for (const AnalysisID ID : AnUsage->getRequiredSet()) {
1209 Pass *Impl = findAnalysisPass(ID, true);
1211 // This may be analysis pass that is initialized on the fly.
1212 // If that is not the case then it will raise an assert when it is used.
1214 AnalysisResolver *AR = P->getResolver();
1215 assert(AR && "Analysis Resolver is not set");
1216 AR->addAnalysisImplsPair(ID, Impl);
1220 /// Find the pass that implements Analysis AID. If desired pass is not found
1221 /// then return NULL.
1222 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1224 // Check if AvailableAnalysis map has one entry.
1225 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1227 if (I != AvailableAnalysis.end())
1230 // Search Parents through TopLevelManager
1232 return TPM->findAnalysisPass(AID);
1237 // Print list of passes that are last used by P.
1238 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1240 SmallVector<Pass *, 12> LUses;
1242 // If this is a on the fly manager then it does not have TPM.
1246 TPM->collectLastUses(LUses, P);
1248 for (Pass *P : LUses) {
1249 dbgs() << "--" << std::string(Offset*2, ' ');
1250 P->dumpPassStructure(0);
1254 void PMDataManager::dumpPassArguments() const {
1255 for (Pass *P : PassVector) {
1256 if (PMDataManager *PMD = P->getAsPMDataManager())
1257 PMD->dumpPassArguments();
1259 if (const PassInfo *PI =
1260 TPM->findAnalysisPassInfo(P->getPassID()))
1261 if (!PI->isAnalysisGroup())
1262 dbgs() << " -" << PI->getPassArgument();
1266 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1267 enum PassDebuggingString S2,
1269 if (PassDebugging < Executions)
1271 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1272 << std::string(getDepth() * 2 + 1, ' ');
1275 dbgs() << "Executing Pass '" << P->getPassName();
1277 case MODIFICATION_MSG:
1278 dbgs() << "Made Modification '" << P->getPassName();
1281 dbgs() << " Freeing Pass '" << P->getPassName();
1287 case ON_FUNCTION_MSG:
1288 dbgs() << "' on Function '" << Msg << "'...\n";
1291 dbgs() << "' on Module '" << Msg << "'...\n";
1294 dbgs() << "' on Region '" << Msg << "'...\n";
1297 dbgs() << "' on Loop '" << Msg << "'...\n";
1300 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1307 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1308 if (PassDebugging < Details)
1311 AnalysisUsage analysisUsage;
1312 P->getAnalysisUsage(analysisUsage);
1313 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1316 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1317 if (PassDebugging < Details)
1320 AnalysisUsage analysisUsage;
1321 P->getAnalysisUsage(analysisUsage);
1322 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1325 void PMDataManager::dumpUsedSet(const Pass *P) const {
1326 if (PassDebugging < Details)
1329 AnalysisUsage analysisUsage;
1330 P->getAnalysisUsage(analysisUsage);
1331 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1334 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1335 const AnalysisUsage::VectorType &Set) const {
1336 assert(PassDebugging >= Details);
1339 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1340 for (unsigned i = 0; i != Set.size(); ++i) {
1341 if (i) dbgs() << ',';
1342 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1344 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1346 dbgs() << " Uninitialized Pass";
1349 dbgs() << ' ' << PInf->getPassName();
1354 /// Add RequiredPass into list of lower level passes required by pass P.
1355 /// RequiredPass is run on the fly by Pass Manager when P requests it
1356 /// through getAnalysis interface.
1357 /// This should be handled by specific pass manager.
1358 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1360 TPM->dumpArguments();
1364 // Module Level pass may required Function Level analysis info
1365 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1366 // to provide this on demand. In that case, in Pass manager terminology,
1367 // module level pass is requiring lower level analysis info managed by
1368 // lower level pass manager.
1370 // When Pass manager is not able to order required analysis info, Pass manager
1371 // checks whether any lower level manager will be able to provide this
1372 // analysis info on demand or not.
1374 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1375 dbgs() << "' required by '" << P->getPassName() << "'\n";
1377 llvm_unreachable("Unable to schedule pass");
1380 std::tuple<Pass *, bool> PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI,
1382 llvm_unreachable("Unable to find on the fly pass");
1386 PMDataManager::~PMDataManager() {
1387 for (Pass *P : PassVector)
1391 //===----------------------------------------------------------------------===//
1392 // NOTE: Is this the right place to define this method ?
1393 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1394 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1395 return PM.findAnalysisPass(ID, dir);
1398 std::tuple<Pass *, bool>
1399 AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI, Function &F) {
1400 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1406 //===----------------------------------------------------------------------===//
1407 // FunctionPassManager implementation
1409 /// Create new Function pass manager
1410 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1411 FPM = new legacy::FunctionPassManagerImpl();
1412 // FPM is the top level manager.
1413 FPM->setTopLevelManager(FPM);
1415 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1416 FPM->setResolver(AR);
1419 FunctionPassManager::~FunctionPassManager() {
1423 void FunctionPassManager::add(Pass *P) {
1427 /// run - Execute all of the passes scheduled for execution. Keep
1428 /// track of whether any of the passes modifies the function, and if
1429 /// so, return true.
1431 bool FunctionPassManager::run(Function &F) {
1432 handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1433 report_fatal_error("Error reading bitcode file: " + EIB.message());
1439 /// doInitialization - Run all of the initializers for the function passes.
1441 bool FunctionPassManager::doInitialization() {
1442 return FPM->doInitialization(*M);
1445 /// doFinalization - Run all of the finalizers for the function passes.
1447 bool FunctionPassManager::doFinalization() {
1448 return FPM->doFinalization(*M);
1450 } // namespace legacy
1453 /// cleanup - After running all passes, clean up pass manager cache.
1454 void FPPassManager::cleanup() {
1455 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1456 FunctionPass *FP = getContainedPass(Index);
1457 AnalysisResolver *AR = FP->getResolver();
1458 assert(AR && "Analysis Resolver is not set");
1459 AR->clearAnalysisImpls();
1464 //===----------------------------------------------------------------------===//
1465 // FPPassManager implementation
1467 char FPPassManager::ID = 0;
1468 /// Print passes managed by this manager
1469 void FPPassManager::dumpPassStructure(unsigned Offset) {
1470 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1471 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1472 FunctionPass *FP = getContainedPass(Index);
1473 FP->dumpPassStructure(Offset + 1);
1474 dumpLastUses(FP, Offset+1);
1479 /// Execute all of the passes scheduled for execution by invoking
1480 /// runOnFunction method. Keep track of whether any of the passes modifies
1481 /// the function, and if so, return true.
1482 bool FPPassManager::runOnFunction(Function &F) {
1483 if (F.isDeclaration())
1486 bool Changed = false;
1487 Module &M = *F.getParent();
1488 // Collect inherited analysis from Module level pass manager.
1489 populateInheritedAnalysis(TPM->activeStack);
1491 unsigned InstrCount, FunctionSize = 0;
1492 StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1493 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1494 // Collect the initial size of the module.
1496 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1497 FunctionSize = F.getInstructionCount();
1500 llvm::TimeTraceScope FunctionScope("OptFunction", F.getName());
1502 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1503 FunctionPass *FP = getContainedPass(Index);
1504 bool LocalChanged = false;
1506 llvm::TimeTraceScope PassScope("RunPass", FP->getPassName());
1508 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1509 dumpRequiredSet(FP);
1511 initializeAnalysisImpl(FP);
1514 PassManagerPrettyStackEntry X(FP, F);
1515 TimeRegion PassTimer(getPassTimer(FP));
1516 LocalChanged |= FP->runOnFunction(F);
1518 unsigned NewSize = F.getInstructionCount();
1520 // Update the size of the function, emit a remark, and update the size
1522 if (NewSize != FunctionSize) {
1523 int64_t Delta = static_cast<int64_t>(NewSize) -
1524 static_cast<int64_t>(FunctionSize);
1525 emitInstrCountChangedRemark(FP, M, Delta, InstrCount,
1526 FunctionToInstrCount, &F);
1527 InstrCount = static_cast<int64_t>(InstrCount) + Delta;
1528 FunctionSize = NewSize;
1533 Changed |= LocalChanged;
1535 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1536 dumpPreservedSet(FP);
1539 verifyPreservedAnalysis(FP);
1540 removeNotPreservedAnalysis(FP);
1541 recordAvailableAnalysis(FP);
1542 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1548 bool FPPassManager::runOnModule(Module &M) {
1549 bool Changed = false;
1551 for (Function &F : M)
1552 Changed |= runOnFunction(F);
1557 bool FPPassManager::doInitialization(Module &M) {
1558 bool Changed = false;
1560 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1561 Changed |= getContainedPass(Index)->doInitialization(M);
1566 bool FPPassManager::doFinalization(Module &M) {
1567 bool Changed = false;
1569 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1570 Changed |= getContainedPass(Index)->doFinalization(M);
1575 //===----------------------------------------------------------------------===//
1576 // MPPassManager implementation
1578 /// Execute all of the passes scheduled for execution by invoking
1579 /// runOnModule method. Keep track of whether any of the passes modifies
1580 /// the module, and if so, return true.
1582 MPPassManager::runOnModule(Module &M) {
1583 llvm::TimeTraceScope TimeScope("OptModule", M.getName());
1585 bool Changed = false;
1587 // Initialize on-the-fly passes
1588 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1589 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1590 Changed |= FPP->doInitialization(M);
1593 // Initialize module passes
1594 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1595 Changed |= getContainedPass(Index)->doInitialization(M);
1597 unsigned InstrCount;
1598 StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1599 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1600 // Collect the initial size of the module.
1602 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1604 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1605 ModulePass *MP = getContainedPass(Index);
1606 bool LocalChanged = false;
1608 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1609 dumpRequiredSet(MP);
1611 initializeAnalysisImpl(MP);
1614 PassManagerPrettyStackEntry X(MP, M);
1615 TimeRegion PassTimer(getPassTimer(MP));
1617 LocalChanged |= MP->runOnModule(M);
1619 // Update the size of the module.
1620 unsigned ModuleCount = M.getInstructionCount();
1621 if (ModuleCount != InstrCount) {
1622 int64_t Delta = static_cast<int64_t>(ModuleCount) -
1623 static_cast<int64_t>(InstrCount);
1624 emitInstrCountChangedRemark(MP, M, Delta, InstrCount,
1625 FunctionToInstrCount);
1626 InstrCount = ModuleCount;
1631 Changed |= LocalChanged;
1633 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1634 M.getModuleIdentifier());
1635 dumpPreservedSet(MP);
1638 verifyPreservedAnalysis(MP);
1639 removeNotPreservedAnalysis(MP);
1640 recordAvailableAnalysis(MP);
1641 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1644 // Finalize module passes
1645 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1646 Changed |= getContainedPass(Index)->doFinalization(M);
1648 // Finalize on-the-fly passes
1649 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1650 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1651 // We don't know when is the last time an on-the-fly pass is run,
1652 // so we need to releaseMemory / finalize here
1653 FPP->releaseMemoryOnTheFly();
1654 Changed |= FPP->doFinalization(M);
1660 /// Add RequiredPass into list of lower level passes required by pass P.
1661 /// RequiredPass is run on the fly by Pass Manager when P requests it
1662 /// through getAnalysis interface.
1663 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1664 assert(RequiredPass && "No required pass?");
1665 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1666 "Unable to handle Pass that requires lower level Analysis pass");
1667 assert((P->getPotentialPassManagerType() <
1668 RequiredPass->getPotentialPassManagerType()) &&
1669 "Unable to handle Pass that requires lower level Analysis pass");
1671 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1673 FPP = new legacy::FunctionPassManagerImpl();
1674 // FPP is the top level manager.
1675 FPP->setTopLevelManager(FPP);
1677 OnTheFlyManagers[P] = FPP;
1679 const PassInfo *RequiredPassPI =
1680 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1682 Pass *FoundPass = nullptr;
1683 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1685 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1688 FoundPass = RequiredPass;
1689 // This should be guaranteed to add RequiredPass to the passmanager given
1690 // that we checked for an available analysis above.
1691 FPP->add(RequiredPass);
1693 // Register P as the last user of FoundPass or RequiredPass.
1694 SmallVector<Pass *, 1> LU;
1695 LU.push_back(FoundPass);
1696 FPP->setLastUser(LU, P);
1699 /// Return function pass corresponding to PassInfo PI, that is
1700 /// required by module pass MP. Instantiate analysis pass, by using
1701 /// its runOnFunction() for function F.
1702 std::tuple<Pass *, bool> MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI,
1704 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1705 assert(FPP && "Unable to find on the fly pass");
1707 FPP->releaseMemoryOnTheFly();
1708 bool Changed = FPP->run(F);
1709 return std::make_tuple(((PMTopLevelManager *)FPP)->findAnalysisPass(PI),
1716 //===----------------------------------------------------------------------===//
1717 // PassManager implementation
1719 /// Create new pass manager
1720 PassManager::PassManager() {
1721 PM = new PassManagerImpl();
1722 // PM is the top level manager
1723 PM->setTopLevelManager(PM);
1726 PassManager::~PassManager() {
1730 void PassManager::add(Pass *P) {
1734 /// run - Execute all of the passes scheduled for execution. Keep track of
1735 /// whether any of the passes modifies the module, and if so, return true.
1736 bool PassManager::run(Module &M) {
1739 } // namespace legacy
1742 //===----------------------------------------------------------------------===//
1743 // PMStack implementation
1746 // Pop Pass Manager from the stack and clear its analysis info.
1747 void PMStack::pop() {
1749 PMDataManager *Top = this->top();
1750 Top->initializeAnalysisInfo();
1755 // Push PM on the stack and set its top level manager.
1756 void PMStack::push(PMDataManager *PM) {
1757 assert(PM && "Unable to push. Pass Manager expected");
1758 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1760 if (!this->empty()) {
1761 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1762 && "pushing bad pass manager to PMStack");
1763 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1765 assert(TPM && "Unable to find top level manager");
1766 TPM->addIndirectPassManager(PM);
1767 PM->setTopLevelManager(TPM);
1768 PM->setDepth(this->top()->getDepth()+1);
1770 assert((PM->getPassManagerType() == PMT_ModulePassManager
1771 || PM->getPassManagerType() == PMT_FunctionPassManager)
1772 && "pushing bad pass manager to PMStack");
1779 // Dump content of the pass manager stack.
1780 LLVM_DUMP_METHOD void PMStack::dump() const {
1781 for (PMDataManager *Manager : S)
1782 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1788 /// Find appropriate Module Pass Manager in the PM Stack and
1789 /// add self into that manager.
1790 void ModulePass::assignPassManager(PMStack &PMS,
1791 PassManagerType PreferredType) {
1792 // Find Module Pass Manager
1794 while ((T = PMS.top()->getPassManagerType()) > PMT_ModulePassManager &&
1797 PMS.top()->add(this);
1800 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1801 /// in the PM Stack and add self into that manager.
1802 void FunctionPass::assignPassManager(PMStack &PMS,
1803 PassManagerType /*PreferredType*/) {
1804 // Find Function Pass Manager
1806 while (PM = PMS.top(), PM->getPassManagerType() > PMT_FunctionPassManager)
1809 // Create new Function Pass Manager if needed.
1810 if (PM->getPassManagerType() != PMT_FunctionPassManager) {
1811 // [1] Create new Function Pass Manager
1812 auto *FPP = new FPPassManager;
1813 FPP->populateInheritedAnalysis(PMS);
1815 // [2] Set up new manager's top level manager
1816 PM->getTopLevelManager()->addIndirectPassManager(FPP);
1818 // [3] Assign manager to manage this new manager. This may create
1819 // and push new managers into PMS
1820 FPP->assignPassManager(PMS, PM->getPassManagerType());
1822 // [4] Push new manager into PMS
1827 // Assign FPP as the manager of this pass.
1831 legacy::PassManagerBase::~PassManagerBase() {}