1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the legacy LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/IRPrintingPasses.h"
17 #include "llvm/IR/LegacyPassManager.h"
18 #include "llvm/IR/LegacyPassManagers.h"
19 #include "llvm/IR/LegacyPassNameParser.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/TimeValue.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm::legacy;
34 // See PassManagers.h for Pass Manager infrastructure overview.
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information. Often it is useful to find out what pass is
38 // running when a crash occurs in a utility. When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
44 // Different debug levels that can be enabled...
46 Disabled, Arguments, Structure, Executions, Details
50 static cl::opt<enum PassDebugLevel>
51 PassDebugging("debug-pass", cl::Hidden,
52 cl::desc("Print PassManager debugging information"),
54 clEnumVal(Disabled , "disable debug output"),
55 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
56 clEnumVal(Structure , "print pass structure before run()"),
57 clEnumVal(Executions, "print pass name before it is executed"),
58 clEnumVal(Details , "print pass details when it is executed"),
62 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
66 // Print IR out before/after specified passes.
68 PrintBefore("print-before",
69 llvm::cl::desc("Print IR before specified passes"),
73 PrintAfter("print-after",
74 llvm::cl::desc("Print IR after specified passes"),
78 PrintBeforeAll("print-before-all",
79 llvm::cl::desc("Print IR before each pass"),
82 PrintAfterAll("print-after-all",
83 llvm::cl::desc("Print IR after each pass"),
86 /// This is a helper to determine whether to print IR before or
89 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
90 PassOptionList &PassesToPrint) {
91 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
92 const llvm::PassInfo *PassInf = PassesToPrint[i];
94 if (PassInf->getPassArgument() == PI->getPassArgument()) {
101 /// This is a utility to check whether a pass should have IR dumped
103 static bool ShouldPrintBeforePass(const PassInfo *PI) {
104 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
107 /// This is a utility to check whether a pass should have IR dumped
109 static bool ShouldPrintAfterPass(const PassInfo *PI) {
110 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
113 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
114 /// or higher is specified.
115 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
116 return PassDebugging >= Executions;
122 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
124 OS << "Releasing pass '";
126 OS << "Running pass '";
128 OS << P->getPassName() << "'";
131 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
140 if (isa<Function>(V))
142 else if (isa<BasicBlock>(V))
148 V->printAsOperand(OS, /*PrintTy=*/false, M);
154 //===----------------------------------------------------------------------===//
157 /// BBPassManager manages BasicBlockPass. It batches all the
158 /// pass together and sequence them to process one basic block before
159 /// processing next basic block.
160 class BBPassManager : public PMDataManager, public FunctionPass {
164 explicit BBPassManager()
165 : PMDataManager(), FunctionPass(ID) {}
167 /// Execute all of the passes scheduled for execution. Keep track of
168 /// whether any of the passes modifies the function, and if so, return true.
169 bool runOnFunction(Function &F) override;
171 /// Pass Manager itself does not invalidate any analysis info.
172 void getAnalysisUsage(AnalysisUsage &Info) const override {
173 Info.setPreservesAll();
176 bool doInitialization(Module &M) override;
177 bool doInitialization(Function &F);
178 bool doFinalization(Module &M) override;
179 bool doFinalization(Function &F);
181 PMDataManager *getAsPMDataManager() override { return this; }
182 Pass *getAsPass() override { return this; }
184 const char *getPassName() const override {
185 return "BasicBlock Pass Manager";
188 // Print passes managed by this manager
189 void dumpPassStructure(unsigned Offset) override {
190 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
191 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
192 BasicBlockPass *BP = getContainedPass(Index);
193 BP->dumpPassStructure(Offset + 1);
194 dumpLastUses(BP, Offset+1);
198 BasicBlockPass *getContainedPass(unsigned N) {
199 assert(N < PassVector.size() && "Pass number out of range!");
200 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
204 PassManagerType getPassManagerType() const override {
205 return PMT_BasicBlockPassManager;
209 char BBPassManager::ID = 0;
210 } // End anonymous namespace
214 //===----------------------------------------------------------------------===//
215 // FunctionPassManagerImpl
217 /// FunctionPassManagerImpl manages FPPassManagers
218 class FunctionPassManagerImpl : public Pass,
219 public PMDataManager,
220 public PMTopLevelManager {
221 virtual void anchor();
226 explicit FunctionPassManagerImpl() :
227 Pass(PT_PassManager, ID), PMDataManager(),
228 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
230 /// \copydoc FunctionPassManager::add()
235 /// createPrinterPass - Get a function printer pass.
236 Pass *createPrinterPass(raw_ostream &O,
237 const std::string &Banner) const override {
238 return createPrintFunctionPass(O, Banner);
241 // Prepare for running an on the fly pass, freeing memory if needed
242 // from a previous run.
243 void releaseMemoryOnTheFly();
245 /// run - Execute all of the passes scheduled for execution. Keep track of
246 /// whether any of the passes modifies the module, and if so, return true.
247 bool run(Function &F);
249 /// doInitialization - Run all of the initializers for the function passes.
251 bool doInitialization(Module &M) override;
253 /// doFinalization - Run all of the finalizers for the function passes.
255 bool doFinalization(Module &M) override;
258 PMDataManager *getAsPMDataManager() override { return this; }
259 Pass *getAsPass() override { return this; }
260 PassManagerType getTopLevelPassManagerType() override {
261 return PMT_FunctionPassManager;
264 /// Pass Manager itself does not invalidate any analysis info.
265 void getAnalysisUsage(AnalysisUsage &Info) const override {
266 Info.setPreservesAll();
269 FPPassManager *getContainedManager(unsigned N) {
270 assert(N < PassManagers.size() && "Pass number out of range!");
271 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
276 void FunctionPassManagerImpl::anchor() {}
278 char FunctionPassManagerImpl::ID = 0;
279 } // End of legacy namespace
280 } // End of llvm namespace
283 //===----------------------------------------------------------------------===//
286 /// MPPassManager manages ModulePasses and function pass managers.
287 /// It batches all Module passes and function pass managers together and
288 /// sequences them to process one module.
289 class MPPassManager : public Pass, public PMDataManager {
292 explicit MPPassManager() :
293 Pass(PT_PassManager, ID), PMDataManager() { }
295 // Delete on the fly managers.
296 virtual ~MPPassManager() {
297 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
298 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
300 FunctionPassManagerImpl *FPP = I->second;
305 /// createPrinterPass - Get a module printer pass.
306 Pass *createPrinterPass(raw_ostream &O,
307 const std::string &Banner) const override {
308 return createPrintModulePass(O, Banner);
311 /// run - Execute all of the passes scheduled for execution. Keep track of
312 /// whether any of the passes modifies the module, and if so, return true.
313 bool runOnModule(Module &M);
315 using llvm::Pass::doInitialization;
316 using llvm::Pass::doFinalization;
318 /// doInitialization - Run all of the initializers for the module passes.
320 bool doInitialization();
322 /// doFinalization - Run all of the finalizers for the module passes.
324 bool doFinalization();
326 /// Pass Manager itself does not invalidate any analysis info.
327 void getAnalysisUsage(AnalysisUsage &Info) const override {
328 Info.setPreservesAll();
331 /// Add RequiredPass into list of lower level passes required by pass P.
332 /// RequiredPass is run on the fly by Pass Manager when P requests it
333 /// through getAnalysis interface.
334 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
336 /// Return function pass corresponding to PassInfo PI, that is
337 /// required by module pass MP. Instantiate analysis pass, by using
338 /// its runOnFunction() for function F.
339 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
341 const char *getPassName() const override {
342 return "Module Pass Manager";
345 PMDataManager *getAsPMDataManager() override { return this; }
346 Pass *getAsPass() override { return this; }
348 // Print passes managed by this manager
349 void dumpPassStructure(unsigned Offset) override {
350 dbgs().indent(Offset*2) << "ModulePass Manager\n";
351 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
352 ModulePass *MP = getContainedPass(Index);
353 MP->dumpPassStructure(Offset + 1);
354 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
355 OnTheFlyManagers.find(MP);
356 if (I != OnTheFlyManagers.end())
357 I->second->dumpPassStructure(Offset + 2);
358 dumpLastUses(MP, Offset+1);
362 ModulePass *getContainedPass(unsigned N) {
363 assert(N < PassVector.size() && "Pass number out of range!");
364 return static_cast<ModulePass *>(PassVector[N]);
367 PassManagerType getPassManagerType() const override {
368 return PMT_ModulePassManager;
372 /// Collection of on the fly FPPassManagers. These managers manage
373 /// function passes that are required by module passes.
374 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
377 char MPPassManager::ID = 0;
378 } // End anonymous namespace
382 //===----------------------------------------------------------------------===//
386 /// PassManagerImpl manages MPPassManagers
387 class PassManagerImpl : public Pass,
388 public PMDataManager,
389 public PMTopLevelManager {
390 virtual void anchor();
394 explicit PassManagerImpl() :
395 Pass(PT_PassManager, ID), PMDataManager(),
396 PMTopLevelManager(new MPPassManager()) {}
398 /// \copydoc PassManager::add()
403 /// createPrinterPass - Get a module printer pass.
404 Pass *createPrinterPass(raw_ostream &O,
405 const std::string &Banner) const override {
406 return createPrintModulePass(O, Banner);
409 /// run - Execute all of the passes scheduled for execution. Keep track of
410 /// whether any of the passes modifies the module, and if so, return true.
413 using llvm::Pass::doInitialization;
414 using llvm::Pass::doFinalization;
416 /// doInitialization - Run all of the initializers for the module passes.
418 bool doInitialization();
420 /// doFinalization - Run all of the finalizers for the module passes.
422 bool doFinalization();
424 /// Pass Manager itself does not invalidate any analysis info.
425 void getAnalysisUsage(AnalysisUsage &Info) const override {
426 Info.setPreservesAll();
429 PMDataManager *getAsPMDataManager() override { return this; }
430 Pass *getAsPass() override { return this; }
431 PassManagerType getTopLevelPassManagerType() override {
432 return PMT_ModulePassManager;
435 MPPassManager *getContainedManager(unsigned N) {
436 assert(N < PassManagers.size() && "Pass number out of range!");
437 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
442 void PassManagerImpl::anchor() {}
444 char PassManagerImpl::ID = 0;
445 } // End of legacy namespace
446 } // End of llvm namespace
450 //===----------------------------------------------------------------------===//
451 /// TimingInfo Class - This class is used to calculate information about the
452 /// amount of time each pass takes to execute. This only happens when
453 /// -time-passes is enabled on the command line.
456 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
459 DenseMap<Pass*, Timer*> TimingData;
462 // Use 'create' member to get this.
463 TimingInfo() : TG("... Pass execution timing report ...") {}
465 // TimingDtor - Print out information about timing information
467 // Delete all of the timers, which accumulate their info into the
469 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
470 E = TimingData.end(); I != E; ++I)
472 // TimerGroup is deleted next, printing the report.
475 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
476 // to a non-null value (if the -time-passes option is enabled) or it leaves it
477 // null. It may be called multiple times.
478 static void createTheTimeInfo();
480 /// getPassTimer - Return the timer for the specified pass if it exists.
481 Timer *getPassTimer(Pass *P) {
482 if (P->getAsPMDataManager())
485 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
486 Timer *&T = TimingData[P];
488 T = new Timer(P->getPassName(), TG);
493 } // End of anon namespace
495 static TimingInfo *TheTimeInfo;
497 //===----------------------------------------------------------------------===//
498 // PMTopLevelManager implementation
500 /// Initialize top level manager. Create first pass manager.
501 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
502 PMDM->setTopLevelManager(this);
503 addPassManager(PMDM);
504 activeStack.push(PMDM);
507 /// Set pass P as the last user of the given analysis passes.
509 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
511 if (P->getResolver())
512 PDepth = P->getResolver()->getPMDataManager().getDepth();
514 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
515 E = AnalysisPasses.end(); I != E; ++I) {
522 // Update the last users of passes that are required transitive by AP.
523 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
524 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
525 SmallVector<Pass *, 12> LastUses;
526 SmallVector<Pass *, 12> LastPMUses;
527 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
528 E = IDs.end(); I != E; ++I) {
529 Pass *AnalysisPass = findAnalysisPass(*I);
530 assert(AnalysisPass && "Expected analysis pass to exist.");
531 AnalysisResolver *AR = AnalysisPass->getResolver();
532 assert(AR && "Expected analysis resolver to exist.");
533 unsigned APDepth = AR->getPMDataManager().getDepth();
535 if (PDepth == APDepth)
536 LastUses.push_back(AnalysisPass);
537 else if (PDepth > APDepth)
538 LastPMUses.push_back(AnalysisPass);
541 setLastUser(LastUses, P);
543 // If this pass has a corresponding pass manager, push higher level
544 // analysis to this pass manager.
545 if (P->getResolver())
546 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
549 // If AP is the last user of other passes then make P last user of
551 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
552 LUE = LastUser.end(); LUI != LUE; ++LUI) {
553 if (LUI->second == AP)
554 // DenseMap iterator is not invalidated here because
555 // this is just updating existing entries.
556 LastUser[LUI->first] = P;
561 /// Collect passes whose last user is P
562 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
564 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
565 InversedLastUser.find(P);
566 if (DMI == InversedLastUser.end())
569 SmallPtrSet<Pass *, 8> &LU = DMI->second;
570 for (Pass *LUP : LU) {
571 LastUses.push_back(LUP);
576 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
577 AnalysisUsage *AnUsage = nullptr;
578 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
579 if (DMI != AnUsageMap.end())
580 AnUsage = DMI->second;
582 AnUsage = new AnalysisUsage();
583 P->getAnalysisUsage(*AnUsage);
584 AnUsageMap[P] = AnUsage;
589 /// Schedule pass P for execution. Make sure that passes required by
590 /// P are run before P is run. Update analysis info maintained by
591 /// the manager. Remove dead passes. This is a recursive function.
592 void PMTopLevelManager::schedulePass(Pass *P) {
594 // TODO : Allocate function manager for this pass, other wise required set
595 // may be inserted into previous function manager
597 // Give pass a chance to prepare the stage.
598 P->preparePassManager(activeStack);
600 // If P is an analysis pass and it is available then do not
601 // generate the analysis again. Stale analysis info should not be
602 // available at this point.
604 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
605 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
610 AnalysisUsage *AnUsage = findAnalysisUsage(P);
612 bool checkAnalysis = true;
613 while (checkAnalysis) {
614 checkAnalysis = false;
616 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
617 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
618 E = RequiredSet.end(); I != E; ++I) {
620 Pass *AnalysisPass = findAnalysisPass(*I);
622 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
625 // Pass P is not in the global PassRegistry
626 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
627 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
628 dbgs() << "Required Passes:" << "\n";
629 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
630 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
631 Pass *AnalysisPass2 = findAnalysisPass(*I2);
633 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
635 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
636 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
637 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
642 assert(PI && "Expected required passes to be initialized");
643 AnalysisPass = PI->createPass();
644 if (P->getPotentialPassManagerType () ==
645 AnalysisPass->getPotentialPassManagerType())
646 // Schedule analysis pass that is managed by the same pass manager.
647 schedulePass(AnalysisPass);
648 else if (P->getPotentialPassManagerType () >
649 AnalysisPass->getPotentialPassManagerType()) {
650 // Schedule analysis pass that is managed by a new manager.
651 schedulePass(AnalysisPass);
652 // Recheck analysis passes to ensure that required analyses that
653 // are already checked are still available.
654 checkAnalysis = true;
656 // Do not schedule this analysis. Lower level analsyis
657 // passes are run on the fly.
663 // Now all required passes are available.
664 if (ImmutablePass *IP = P->getAsImmutablePass()) {
665 // P is a immutable pass and it will be managed by this
666 // top level manager. Set up analysis resolver to connect them.
667 PMDataManager *DM = getAsPMDataManager();
668 AnalysisResolver *AR = new AnalysisResolver(*DM);
670 DM->initializeAnalysisImpl(P);
671 addImmutablePass(IP);
672 DM->recordAvailableAnalysis(IP);
676 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
677 Pass *PP = P->createPrinterPass(
678 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
679 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
682 // Add the requested pass to the best available pass manager.
683 P->assignPassManager(activeStack, getTopLevelPassManagerType());
685 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
686 Pass *PP = P->createPrinterPass(
687 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
688 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
692 /// Find the pass that implements Analysis AID. Search immutable
693 /// passes and all pass managers. If desired pass is not found
694 /// then return NULL.
695 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
697 // Check pass managers
698 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
699 E = PassManagers.end(); I != E; ++I)
700 if (Pass *P = (*I)->findAnalysisPass(AID, false))
703 // Check other pass managers
704 for (SmallVectorImpl<PMDataManager *>::iterator
705 I = IndirectPassManagers.begin(),
706 E = IndirectPassManagers.end(); I != E; ++I)
707 if (Pass *P = (*I)->findAnalysisPass(AID, false))
710 // Check the immutable passes. Iterate in reverse order so that we find
711 // the most recently registered passes first.
712 for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
713 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
714 AnalysisID PI = (*I)->getPassID();
718 // If Pass not found then check the interfaces implemented by Immutable Pass
719 const PassInfo *PassInf =
720 PassRegistry::getPassRegistry()->getPassInfo(PI);
721 assert(PassInf && "Expected all immutable passes to be initialized");
722 const std::vector<const PassInfo*> &ImmPI =
723 PassInf->getInterfacesImplemented();
724 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
725 EE = ImmPI.end(); II != EE; ++II) {
726 if ((*II)->getTypeInfo() == AID)
734 // Print passes managed by this top level manager.
735 void PMTopLevelManager::dumpPasses() const {
737 if (PassDebugging < Structure)
740 // Print out the immutable passes
741 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
742 ImmutablePasses[i]->dumpPassStructure(0);
745 // Every class that derives from PMDataManager also derives from Pass
746 // (sometimes indirectly), but there's no inheritance relationship
747 // between PMDataManager and Pass, so we have to getAsPass to get
748 // from a PMDataManager* to a Pass*.
749 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
750 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
751 (*I)->getAsPass()->dumpPassStructure(1);
754 void PMTopLevelManager::dumpArguments() const {
756 if (PassDebugging < Arguments)
759 dbgs() << "Pass Arguments: ";
760 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
761 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
762 if (const PassInfo *PI =
763 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
764 assert(PI && "Expected all immutable passes to be initialized");
765 if (!PI->isAnalysisGroup())
766 dbgs() << " -" << PI->getPassArgument();
768 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
769 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
770 (*I)->dumpPassArguments();
774 void PMTopLevelManager::initializeAllAnalysisInfo() {
775 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
776 E = PassManagers.end(); I != E; ++I)
777 (*I)->initializeAnalysisInfo();
779 // Initailize other pass managers
780 for (SmallVectorImpl<PMDataManager *>::iterator
781 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
783 (*I)->initializeAnalysisInfo();
785 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
786 DME = LastUser.end(); DMI != DME; ++DMI) {
787 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
788 InversedLastUser.find(DMI->second);
789 if (InvDMI != InversedLastUser.end()) {
790 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
791 L.insert(DMI->first);
793 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
794 InversedLastUser[DMI->second] = L;
800 PMTopLevelManager::~PMTopLevelManager() {
801 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
802 E = PassManagers.end(); I != E; ++I)
805 for (SmallVectorImpl<ImmutablePass *>::iterator
806 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
809 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
810 DME = AnUsageMap.end(); DMI != DME; ++DMI)
814 //===----------------------------------------------------------------------===//
815 // PMDataManager implementation
817 /// Augement AvailableAnalysis by adding analysis made available by pass P.
818 void PMDataManager::recordAvailableAnalysis(Pass *P) {
819 AnalysisID PI = P->getPassID();
821 AvailableAnalysis[PI] = P;
823 assert(!AvailableAnalysis.empty());
825 // This pass is the current implementation of all of the interfaces it
826 // implements as well.
827 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
829 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
830 for (unsigned i = 0, e = II.size(); i != e; ++i)
831 AvailableAnalysis[II[i]->getTypeInfo()] = P;
834 // Return true if P preserves high level analysis used by other
835 // passes managed by this manager
836 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
837 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
838 if (AnUsage->getPreservesAll())
841 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
842 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
843 E = HigherLevelAnalysis.end(); I != E; ++I) {
845 if (P1->getAsImmutablePass() == nullptr &&
846 std::find(PreservedSet.begin(), PreservedSet.end(),
855 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
856 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
857 // Don't do this unless assertions are enabled.
861 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
862 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
864 // Verify preserved analysis
865 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
866 E = PreservedSet.end(); I != E; ++I) {
868 if (Pass *AP = findAnalysisPass(AID, true)) {
869 TimeRegion PassTimer(getPassTimer(AP));
870 AP->verifyAnalysis();
875 /// Remove Analysis not preserved by Pass P
876 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
877 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
878 if (AnUsage->getPreservesAll())
881 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
882 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
883 E = AvailableAnalysis.end(); I != E; ) {
884 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
885 if (Info->second->getAsImmutablePass() == nullptr &&
886 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
887 PreservedSet.end()) {
888 // Remove this analysis
889 if (PassDebugging >= Details) {
890 Pass *S = Info->second;
891 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
892 dbgs() << S->getPassName() << "'\n";
894 AvailableAnalysis.erase(Info);
898 // Check inherited analysis also. If P is not preserving analysis
899 // provided by parent manager then remove it here.
900 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
902 if (!InheritedAnalysis[Index])
905 for (DenseMap<AnalysisID, Pass*>::iterator
906 I = InheritedAnalysis[Index]->begin(),
907 E = InheritedAnalysis[Index]->end(); I != E; ) {
908 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
909 if (Info->second->getAsImmutablePass() == nullptr &&
910 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
911 PreservedSet.end()) {
912 // Remove this analysis
913 if (PassDebugging >= Details) {
914 Pass *S = Info->second;
915 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
916 dbgs() << S->getPassName() << "'\n";
918 InheritedAnalysis[Index]->erase(Info);
924 /// Remove analysis passes that are not used any longer
925 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
926 enum PassDebuggingString DBG_STR) {
928 SmallVector<Pass *, 12> DeadPasses;
930 // If this is a on the fly manager then it does not have TPM.
934 TPM->collectLastUses(DeadPasses, P);
936 if (PassDebugging >= Details && !DeadPasses.empty()) {
937 dbgs() << " -*- '" << P->getPassName();
938 dbgs() << "' is the last user of following pass instances.";
939 dbgs() << " Free these instances\n";
942 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
943 E = DeadPasses.end(); I != E; ++I)
944 freePass(*I, Msg, DBG_STR);
947 void PMDataManager::freePass(Pass *P, StringRef Msg,
948 enum PassDebuggingString DBG_STR) {
949 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
952 // If the pass crashes releasing memory, remember this.
953 PassManagerPrettyStackEntry X(P);
954 TimeRegion PassTimer(getPassTimer(P));
959 AnalysisID PI = P->getPassID();
960 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
961 // Remove the pass itself (if it is not already removed).
962 AvailableAnalysis.erase(PI);
964 // Remove all interfaces this pass implements, for which it is also
965 // listed as the available implementation.
966 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
967 for (unsigned i = 0, e = II.size(); i != e; ++i) {
968 DenseMap<AnalysisID, Pass*>::iterator Pos =
969 AvailableAnalysis.find(II[i]->getTypeInfo());
970 if (Pos != AvailableAnalysis.end() && Pos->second == P)
971 AvailableAnalysis.erase(Pos);
976 /// Add pass P into the PassVector. Update
977 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
978 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
979 // This manager is going to manage pass P. Set up analysis resolver
981 AnalysisResolver *AR = new AnalysisResolver(*this);
984 // If a FunctionPass F is the last user of ModulePass info M
985 // then the F's manager, not F, records itself as a last user of M.
986 SmallVector<Pass *, 12> TransferLastUses;
988 if (!ProcessAnalysis) {
990 PassVector.push_back(P);
994 // At the moment, this pass is the last user of all required passes.
995 SmallVector<Pass *, 12> LastUses;
996 SmallVector<Pass *, 8> RequiredPasses;
997 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
999 unsigned PDepth = this->getDepth();
1001 collectRequiredAnalysis(RequiredPasses,
1002 ReqAnalysisNotAvailable, P);
1003 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1004 E = RequiredPasses.end(); I != E; ++I) {
1005 Pass *PRequired = *I;
1006 unsigned RDepth = 0;
1008 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1009 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1010 RDepth = DM.getDepth();
1012 if (PDepth == RDepth)
1013 LastUses.push_back(PRequired);
1014 else if (PDepth > RDepth) {
1015 // Let the parent claim responsibility of last use
1016 TransferLastUses.push_back(PRequired);
1017 // Keep track of higher level analysis used by this manager.
1018 HigherLevelAnalysis.push_back(PRequired);
1020 llvm_unreachable("Unable to accommodate Required Pass");
1023 // Set P as P's last user until someone starts using P.
1024 // However, if P is a Pass Manager then it does not need
1025 // to record its last user.
1026 if (!P->getAsPMDataManager())
1027 LastUses.push_back(P);
1028 TPM->setLastUser(LastUses, P);
1030 if (!TransferLastUses.empty()) {
1031 Pass *My_PM = getAsPass();
1032 TPM->setLastUser(TransferLastUses, My_PM);
1033 TransferLastUses.clear();
1036 // Now, take care of required analyses that are not available.
1037 for (SmallVectorImpl<AnalysisID>::iterator
1038 I = ReqAnalysisNotAvailable.begin(),
1039 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1040 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1041 Pass *AnalysisPass = PI->createPass();
1042 this->addLowerLevelRequiredPass(P, AnalysisPass);
1045 // Take a note of analysis required and made available by this pass.
1046 // Remove the analysis not preserved by this pass
1047 removeNotPreservedAnalysis(P);
1048 recordAvailableAnalysis(P);
1051 PassVector.push_back(P);
1055 /// Populate RP with analysis pass that are required by
1056 /// pass P and are available. Populate RP_NotAvail with analysis
1057 /// pass that are required by pass P but are not available.
1058 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1059 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1061 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1062 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1063 for (AnalysisUsage::VectorType::const_iterator
1064 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1065 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1066 RP.push_back(AnalysisPass);
1068 RP_NotAvail.push_back(*I);
1071 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1072 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1073 E = IDs.end(); I != E; ++I) {
1074 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1075 RP.push_back(AnalysisPass);
1077 RP_NotAvail.push_back(*I);
1081 // All Required analyses should be available to the pass as it runs! Here
1082 // we fill in the AnalysisImpls member of the pass so that it can
1083 // successfully use the getAnalysis() method to retrieve the
1084 // implementations it needs.
1086 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1087 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1089 for (AnalysisUsage::VectorType::const_iterator
1090 I = AnUsage->getRequiredSet().begin(),
1091 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1092 Pass *Impl = findAnalysisPass(*I, true);
1094 // This may be analysis pass that is initialized on the fly.
1095 // If that is not the case then it will raise an assert when it is used.
1097 AnalysisResolver *AR = P->getResolver();
1098 assert(AR && "Analysis Resolver is not set");
1099 AR->addAnalysisImplsPair(*I, Impl);
1103 /// Find the pass that implements Analysis AID. If desired pass is not found
1104 /// then return NULL.
1105 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1107 // Check if AvailableAnalysis map has one entry.
1108 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1110 if (I != AvailableAnalysis.end())
1113 // Search Parents through TopLevelManager
1115 return TPM->findAnalysisPass(AID);
1120 // Print list of passes that are last used by P.
1121 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1123 SmallVector<Pass *, 12> LUses;
1125 // If this is a on the fly manager then it does not have TPM.
1129 TPM->collectLastUses(LUses, P);
1131 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1132 E = LUses.end(); I != E; ++I) {
1133 dbgs() << "--" << std::string(Offset*2, ' ');
1134 (*I)->dumpPassStructure(0);
1138 void PMDataManager::dumpPassArguments() const {
1139 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1140 E = PassVector.end(); I != E; ++I) {
1141 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1142 PMD->dumpPassArguments();
1144 if (const PassInfo *PI =
1145 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1146 if (!PI->isAnalysisGroup())
1147 dbgs() << " -" << PI->getPassArgument();
1151 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1152 enum PassDebuggingString S2,
1154 if (PassDebugging < Executions)
1156 dbgs() << "[" << sys::TimeValue::now().str() << "] " << (void *)this
1157 << std::string(getDepth() * 2 + 1, ' ');
1160 dbgs() << "Executing Pass '" << P->getPassName();
1162 case MODIFICATION_MSG:
1163 dbgs() << "Made Modification '" << P->getPassName();
1166 dbgs() << " Freeing Pass '" << P->getPassName();
1172 case ON_BASICBLOCK_MSG:
1173 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1175 case ON_FUNCTION_MSG:
1176 dbgs() << "' on Function '" << Msg << "'...\n";
1179 dbgs() << "' on Module '" << Msg << "'...\n";
1182 dbgs() << "' on Region '" << Msg << "'...\n";
1185 dbgs() << "' on Loop '" << Msg << "'...\n";
1188 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1195 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1196 if (PassDebugging < Details)
1199 AnalysisUsage analysisUsage;
1200 P->getAnalysisUsage(analysisUsage);
1201 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1204 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1205 if (PassDebugging < Details)
1208 AnalysisUsage analysisUsage;
1209 P->getAnalysisUsage(analysisUsage);
1210 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1213 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1214 const AnalysisUsage::VectorType &Set) const {
1215 assert(PassDebugging >= Details);
1218 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1219 for (unsigned i = 0; i != Set.size(); ++i) {
1220 if (i) dbgs() << ',';
1221 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1223 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1225 dbgs() << " Uninitialized Pass";
1228 dbgs() << ' ' << PInf->getPassName();
1233 /// Add RequiredPass into list of lower level passes required by pass P.
1234 /// RequiredPass is run on the fly by Pass Manager when P requests it
1235 /// through getAnalysis interface.
1236 /// This should be handled by specific pass manager.
1237 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1239 TPM->dumpArguments();
1243 // Module Level pass may required Function Level analysis info
1244 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1245 // to provide this on demand. In that case, in Pass manager terminology,
1246 // module level pass is requiring lower level analysis info managed by
1247 // lower level pass manager.
1249 // When Pass manager is not able to order required analysis info, Pass manager
1250 // checks whether any lower level manager will be able to provide this
1251 // analysis info on demand or not.
1253 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1254 dbgs() << "' required by '" << P->getPassName() << "'\n";
1256 llvm_unreachable("Unable to schedule pass");
1259 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1260 llvm_unreachable("Unable to find on the fly pass");
1264 PMDataManager::~PMDataManager() {
1265 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1266 E = PassVector.end(); I != E; ++I)
1270 //===----------------------------------------------------------------------===//
1271 // NOTE: Is this the right place to define this method ?
1272 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1273 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1274 return PM.findAnalysisPass(ID, dir);
1277 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1279 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1282 //===----------------------------------------------------------------------===//
1283 // BBPassManager implementation
1285 /// Execute all of the passes scheduled for execution by invoking
1286 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1287 /// the function, and if so, return true.
1288 bool BBPassManager::runOnFunction(Function &F) {
1289 if (F.isDeclaration())
1292 bool Changed = doInitialization(F);
1294 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1295 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1296 BasicBlockPass *BP = getContainedPass(Index);
1297 bool LocalChanged = false;
1299 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1300 dumpRequiredSet(BP);
1302 initializeAnalysisImpl(BP);
1305 // If the pass crashes, remember this.
1306 PassManagerPrettyStackEntry X(BP, *I);
1307 TimeRegion PassTimer(getPassTimer(BP));
1309 LocalChanged |= BP->runOnBasicBlock(*I);
1312 Changed |= LocalChanged;
1314 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1316 dumpPreservedSet(BP);
1318 verifyPreservedAnalysis(BP);
1319 removeNotPreservedAnalysis(BP);
1320 recordAvailableAnalysis(BP);
1321 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1324 return doFinalization(F) || Changed;
1327 // Implement doInitialization and doFinalization
1328 bool BBPassManager::doInitialization(Module &M) {
1329 bool Changed = false;
1331 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1332 Changed |= getContainedPass(Index)->doInitialization(M);
1337 bool BBPassManager::doFinalization(Module &M) {
1338 bool Changed = false;
1340 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1341 Changed |= getContainedPass(Index)->doFinalization(M);
1346 bool BBPassManager::doInitialization(Function &F) {
1347 bool Changed = false;
1349 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1350 BasicBlockPass *BP = getContainedPass(Index);
1351 Changed |= BP->doInitialization(F);
1357 bool BBPassManager::doFinalization(Function &F) {
1358 bool Changed = false;
1360 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1361 BasicBlockPass *BP = getContainedPass(Index);
1362 Changed |= BP->doFinalization(F);
1369 //===----------------------------------------------------------------------===//
1370 // FunctionPassManager implementation
1372 /// Create new Function pass manager
1373 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1374 FPM = new FunctionPassManagerImpl();
1375 // FPM is the top level manager.
1376 FPM->setTopLevelManager(FPM);
1378 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1379 FPM->setResolver(AR);
1382 FunctionPassManager::~FunctionPassManager() {
1386 void FunctionPassManager::add(Pass *P) {
1390 /// run - Execute all of the passes scheduled for execution. Keep
1391 /// track of whether any of the passes modifies the function, and if
1392 /// so, return true.
1394 bool FunctionPassManager::run(Function &F) {
1395 if (std::error_code EC = F.materialize())
1396 report_fatal_error("Error reading bitcode file: " + EC.message());
1401 /// doInitialization - Run all of the initializers for the function passes.
1403 bool FunctionPassManager::doInitialization() {
1404 return FPM->doInitialization(*M);
1407 /// doFinalization - Run all of the finalizers for the function passes.
1409 bool FunctionPassManager::doFinalization() {
1410 return FPM->doFinalization(*M);
1413 //===----------------------------------------------------------------------===//
1414 // FunctionPassManagerImpl implementation
1416 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1417 bool Changed = false;
1422 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1423 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1424 E = IPV.end(); I != E; ++I) {
1425 Changed |= (*I)->doInitialization(M);
1428 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1429 Changed |= getContainedManager(Index)->doInitialization(M);
1434 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1435 bool Changed = false;
1437 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1438 Changed |= getContainedManager(Index)->doFinalization(M);
1440 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1441 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1442 E = IPV.end(); I != E; ++I) {
1443 Changed |= (*I)->doFinalization(M);
1449 /// cleanup - After running all passes, clean up pass manager cache.
1450 void FPPassManager::cleanup() {
1451 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1452 FunctionPass *FP = getContainedPass(Index);
1453 AnalysisResolver *AR = FP->getResolver();
1454 assert(AR && "Analysis Resolver is not set");
1455 AR->clearAnalysisImpls();
1459 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1462 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1463 FPPassManager *FPPM = getContainedManager(Index);
1464 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1465 FPPM->getContainedPass(Index)->releaseMemory();
1471 // Execute all the passes managed by this top level manager.
1472 // Return true if any function is modified by a pass.
1473 bool FunctionPassManagerImpl::run(Function &F) {
1474 bool Changed = false;
1475 TimingInfo::createTheTimeInfo();
1477 initializeAllAnalysisInfo();
1478 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1479 Changed |= getContainedManager(Index)->runOnFunction(F);
1480 F.getContext().yield();
1483 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1484 getContainedManager(Index)->cleanup();
1490 //===----------------------------------------------------------------------===//
1491 // FPPassManager implementation
1493 char FPPassManager::ID = 0;
1494 /// Print passes managed by this manager
1495 void FPPassManager::dumpPassStructure(unsigned Offset) {
1496 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1497 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1498 FunctionPass *FP = getContainedPass(Index);
1499 FP->dumpPassStructure(Offset + 1);
1500 dumpLastUses(FP, Offset+1);
1505 /// Execute all of the passes scheduled for execution by invoking
1506 /// runOnFunction method. Keep track of whether any of the passes modifies
1507 /// the function, and if so, return true.
1508 bool FPPassManager::runOnFunction(Function &F) {
1509 if (F.isDeclaration())
1512 bool Changed = false;
1514 // Collect inherited analysis from Module level pass manager.
1515 populateInheritedAnalysis(TPM->activeStack);
1517 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1518 FunctionPass *FP = getContainedPass(Index);
1519 bool LocalChanged = false;
1521 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1522 dumpRequiredSet(FP);
1524 initializeAnalysisImpl(FP);
1527 PassManagerPrettyStackEntry X(FP, F);
1528 TimeRegion PassTimer(getPassTimer(FP));
1530 LocalChanged |= FP->runOnFunction(F);
1533 Changed |= LocalChanged;
1535 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1536 dumpPreservedSet(FP);
1538 verifyPreservedAnalysis(FP);
1539 removeNotPreservedAnalysis(FP);
1540 recordAvailableAnalysis(FP);
1541 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1546 bool FPPassManager::runOnModule(Module &M) {
1547 bool Changed = false;
1549 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1550 Changed |= runOnFunction(*I);
1555 bool FPPassManager::doInitialization(Module &M) {
1556 bool Changed = false;
1558 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1559 Changed |= getContainedPass(Index)->doInitialization(M);
1564 bool FPPassManager::doFinalization(Module &M) {
1565 bool Changed = false;
1567 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1568 Changed |= getContainedPass(Index)->doFinalization(M);
1573 //===----------------------------------------------------------------------===//
1574 // MPPassManager implementation
1576 /// Execute all of the passes scheduled for execution by invoking
1577 /// runOnModule method. Keep track of whether any of the passes modifies
1578 /// the module, and if so, return true.
1580 MPPassManager::runOnModule(Module &M) {
1581 bool Changed = false;
1583 // Initialize on-the-fly passes
1584 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1585 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1587 FunctionPassManagerImpl *FPP = I->second;
1588 Changed |= FPP->doInitialization(M);
1591 // Initialize module passes
1592 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1593 Changed |= getContainedPass(Index)->doInitialization(M);
1595 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1596 ModulePass *MP = getContainedPass(Index);
1597 bool LocalChanged = false;
1599 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1600 dumpRequiredSet(MP);
1602 initializeAnalysisImpl(MP);
1605 PassManagerPrettyStackEntry X(MP, M);
1606 TimeRegion PassTimer(getPassTimer(MP));
1608 LocalChanged |= MP->runOnModule(M);
1611 Changed |= LocalChanged;
1613 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1614 M.getModuleIdentifier());
1615 dumpPreservedSet(MP);
1617 verifyPreservedAnalysis(MP);
1618 removeNotPreservedAnalysis(MP);
1619 recordAvailableAnalysis(MP);
1620 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1623 // Finalize module passes
1624 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1625 Changed |= getContainedPass(Index)->doFinalization(M);
1627 // Finalize on-the-fly passes
1628 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1629 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1631 FunctionPassManagerImpl *FPP = I->second;
1632 // We don't know when is the last time an on-the-fly pass is run,
1633 // so we need to releaseMemory / finalize here
1634 FPP->releaseMemoryOnTheFly();
1635 Changed |= FPP->doFinalization(M);
1641 /// Add RequiredPass into list of lower level passes required by pass P.
1642 /// RequiredPass is run on the fly by Pass Manager when P requests it
1643 /// through getAnalysis interface.
1644 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1645 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1646 "Unable to handle Pass that requires lower level Analysis pass");
1647 assert((P->getPotentialPassManagerType() <
1648 RequiredPass->getPotentialPassManagerType()) &&
1649 "Unable to handle Pass that requires lower level Analysis pass");
1653 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1655 FPP = new FunctionPassManagerImpl();
1656 // FPP is the top level manager.
1657 FPP->setTopLevelManager(FPP);
1659 OnTheFlyManagers[P] = FPP;
1661 const PassInfo * RequiredPassPI =
1662 PassRegistry::getPassRegistry()->getPassInfo(RequiredPass->getPassID());
1664 Pass *FoundPass = nullptr;
1665 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1667 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1670 FoundPass = RequiredPass;
1671 // This should be guaranteed to add RequiredPass to the passmanager given
1672 // that we checked for an available analysis above.
1673 FPP->add(RequiredPass);
1675 // Register P as the last user of FoundPass or RequiredPass.
1676 SmallVector<Pass *, 1> LU;
1677 LU.push_back(FoundPass);
1678 FPP->setLastUser(LU, P);
1681 /// Return function pass corresponding to PassInfo PI, that is
1682 /// required by module pass MP. Instantiate analysis pass, by using
1683 /// its runOnFunction() for function F.
1684 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1685 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1686 assert(FPP && "Unable to find on the fly pass");
1688 FPP->releaseMemoryOnTheFly();
1690 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1694 //===----------------------------------------------------------------------===//
1695 // PassManagerImpl implementation
1698 /// run - Execute all of the passes scheduled for execution. Keep track of
1699 /// whether any of the passes modifies the module, and if so, return true.
1700 bool PassManagerImpl::run(Module &M) {
1701 bool Changed = false;
1702 TimingInfo::createTheTimeInfo();
1707 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1708 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1709 E = IPV.end(); I != E; ++I) {
1710 Changed |= (*I)->doInitialization(M);
1713 initializeAllAnalysisInfo();
1714 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1715 Changed |= getContainedManager(Index)->runOnModule(M);
1716 M.getContext().yield();
1719 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1720 E = IPV.end(); I != E; ++I) {
1721 Changed |= (*I)->doFinalization(M);
1727 //===----------------------------------------------------------------------===//
1728 // PassManager implementation
1730 /// Create new pass manager
1731 PassManager::PassManager() {
1732 PM = new PassManagerImpl();
1733 // PM is the top level manager
1734 PM->setTopLevelManager(PM);
1737 PassManager::~PassManager() {
1741 void PassManager::add(Pass *P) {
1745 /// run - Execute all of the passes scheduled for execution. Keep track of
1746 /// whether any of the passes modifies the module, and if so, return true.
1747 bool PassManager::run(Module &M) {
1751 //===----------------------------------------------------------------------===//
1752 // TimingInfo implementation
1754 bool llvm::TimePassesIsEnabled = false;
1755 static cl::opt<bool,true>
1756 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1757 cl::desc("Time each pass, printing elapsed time for each on exit"));
1759 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1760 // a non-null value (if the -time-passes option is enabled) or it leaves it
1761 // null. It may be called multiple times.
1762 void TimingInfo::createTheTimeInfo() {
1763 if (!TimePassesIsEnabled || TheTimeInfo) return;
1765 // Constructed the first time this is called, iff -time-passes is enabled.
1766 // This guarantees that the object will be constructed before static globals,
1767 // thus it will be destroyed before them.
1768 static ManagedStatic<TimingInfo> TTI;
1769 TheTimeInfo = &*TTI;
1772 /// If TimingInfo is enabled then start pass timer.
1773 Timer *llvm::getPassTimer(Pass *P) {
1775 return TheTimeInfo->getPassTimer(P);
1779 //===----------------------------------------------------------------------===//
1780 // PMStack implementation
1783 // Pop Pass Manager from the stack and clear its analysis info.
1784 void PMStack::pop() {
1786 PMDataManager *Top = this->top();
1787 Top->initializeAnalysisInfo();
1792 // Push PM on the stack and set its top level manager.
1793 void PMStack::push(PMDataManager *PM) {
1794 assert(PM && "Unable to push. Pass Manager expected");
1795 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1797 if (!this->empty()) {
1798 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1799 && "pushing bad pass manager to PMStack");
1800 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1802 assert(TPM && "Unable to find top level manager");
1803 TPM->addIndirectPassManager(PM);
1804 PM->setTopLevelManager(TPM);
1805 PM->setDepth(this->top()->getDepth()+1);
1807 assert((PM->getPassManagerType() == PMT_ModulePassManager
1808 || PM->getPassManagerType() == PMT_FunctionPassManager)
1809 && "pushing bad pass manager to PMStack");
1816 // Dump content of the pass manager stack.
1817 void PMStack::dump() const {
1818 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1819 E = S.end(); I != E; ++I)
1820 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1826 /// Find appropriate Module Pass Manager in the PM Stack and
1827 /// add self into that manager.
1828 void ModulePass::assignPassManager(PMStack &PMS,
1829 PassManagerType PreferredType) {
1830 // Find Module Pass Manager
1831 while (!PMS.empty()) {
1832 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1833 if (TopPMType == PreferredType)
1834 break; // We found desired pass manager
1835 else if (TopPMType > PMT_ModulePassManager)
1836 PMS.pop(); // Pop children pass managers
1840 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1841 PMS.top()->add(this);
1844 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1845 /// in the PM Stack and add self into that manager.
1846 void FunctionPass::assignPassManager(PMStack &PMS,
1847 PassManagerType PreferredType) {
1849 // Find Function Pass Manager
1850 while (!PMS.empty()) {
1851 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1857 // Create new Function Pass Manager if needed.
1859 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1860 FPP = (FPPassManager *)PMS.top();
1862 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1863 PMDataManager *PMD = PMS.top();
1865 // [1] Create new Function Pass Manager
1866 FPP = new FPPassManager();
1867 FPP->populateInheritedAnalysis(PMS);
1869 // [2] Set up new manager's top level manager
1870 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1871 TPM->addIndirectPassManager(FPP);
1873 // [3] Assign manager to manage this new manager. This may create
1874 // and push new managers into PMS
1875 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1877 // [4] Push new manager into PMS
1881 // Assign FPP as the manager of this pass.
1885 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1886 /// in the PM Stack and add self into that manager.
1887 void BasicBlockPass::assignPassManager(PMStack &PMS,
1888 PassManagerType PreferredType) {
1891 // Basic Pass Manager is a leaf pass manager. It does not handle
1892 // any other pass manager.
1894 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1895 BBP = (BBPassManager *)PMS.top();
1897 // If leaf manager is not Basic Block Pass manager then create new
1898 // basic Block Pass manager.
1899 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1900 PMDataManager *PMD = PMS.top();
1902 // [1] Create new Basic Block Manager
1903 BBP = new BBPassManager();
1905 // [2] Set up new manager's top level manager
1906 // Basic Block Pass Manager does not live by itself
1907 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1908 TPM->addIndirectPassManager(BBP);
1910 // [3] Assign manager to manage this new manager. This may create
1911 // and push new managers into PMS
1912 BBP->assignPassManager(PMS, PreferredType);
1914 // [4] Push new manager into PMS
1918 // Assign BBP as the manager of this pass.
1922 PassManagerBase::~PassManagerBase() {}