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/IRPrintingPasses.h"
16 #include "llvm/IR/LegacyPassManager.h"
17 #include "llvm/IR/LegacyPassManagers.h"
18 #include "llvm/IR/LegacyPassNameParser.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/Timer.h"
26 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm::legacy;
32 // See PassManagers.h for Pass Manager infrastructure overview.
34 //===----------------------------------------------------------------------===//
35 // Pass debugging information. Often it is useful to find out what pass is
36 // running when a crash occurs in a utility. When this library is compiled with
37 // debugging on, a command line option (--debug-pass) is enabled that causes the
38 // pass name to be printed before it executes.
42 // Different debug levels that can be enabled...
44 Disabled, Arguments, Structure, Executions, Details
48 static cl::opt<enum PassDebugLevel>
49 PassDebugging("debug-pass", cl::Hidden,
50 cl::desc("Print PassManager debugging information"),
52 clEnumVal(Disabled , "disable debug output"),
53 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54 clEnumVal(Structure , "print pass structure before run()"),
55 clEnumVal(Executions, "print pass name before it is executed"),
56 clEnumVal(Details , "print pass details when it is executed"),
60 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
64 // Print IR out before/after specified passes.
66 PrintBefore("print-before",
67 llvm::cl::desc("Print IR before specified passes"),
71 PrintAfter("print-after",
72 llvm::cl::desc("Print IR after specified passes"),
76 PrintBeforeAll("print-before-all",
77 llvm::cl::desc("Print IR before each pass"),
80 PrintAfterAll("print-after-all",
81 llvm::cl::desc("Print IR after each pass"),
84 /// This is a helper to determine whether to print IR before or
87 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
88 PassOptionList &PassesToPrint) {
89 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
90 const llvm::PassInfo *PassInf = PassesToPrint[i];
92 if (PassInf->getPassArgument() == PI->getPassArgument()) {
99 /// This is a utility to check whether a pass should have IR dumped
101 static bool ShouldPrintBeforePass(const PassInfo *PI) {
102 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
105 /// This is a utility to check whether a pass should have IR dumped
107 static bool ShouldPrintAfterPass(const PassInfo *PI) {
108 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
111 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
112 /// or higher is specified.
113 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
114 return PassDebugging >= Executions;
120 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
122 OS << "Releasing pass '";
124 OS << "Running pass '";
126 OS << P->getPassName() << "'";
129 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
138 if (isa<Function>(V))
140 else if (isa<BasicBlock>(V))
146 V->printAsOperand(OS, /*PrintTy=*/false, M);
152 //===----------------------------------------------------------------------===//
155 /// BBPassManager manages BasicBlockPass. It batches all the
156 /// pass together and sequence them to process one basic block before
157 /// processing next basic block.
158 class BBPassManager : public PMDataManager, public FunctionPass {
162 explicit BBPassManager()
163 : PMDataManager(), FunctionPass(ID) {}
165 /// Execute all of the passes scheduled for execution. Keep track of
166 /// whether any of the passes modifies the function, and if so, return true.
167 bool runOnFunction(Function &F) override;
169 /// Pass Manager itself does not invalidate any analysis info.
170 void getAnalysisUsage(AnalysisUsage &Info) const override {
171 Info.setPreservesAll();
174 bool doInitialization(Module &M) override;
175 bool doInitialization(Function &F);
176 bool doFinalization(Module &M) override;
177 bool doFinalization(Function &F);
179 PMDataManager *getAsPMDataManager() override { return this; }
180 Pass *getAsPass() override { return this; }
182 const char *getPassName() const override {
183 return "BasicBlock Pass Manager";
186 // Print passes managed by this manager
187 void dumpPassStructure(unsigned Offset) override {
188 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
189 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
190 BasicBlockPass *BP = getContainedPass(Index);
191 BP->dumpPassStructure(Offset + 1);
192 dumpLastUses(BP, Offset+1);
196 BasicBlockPass *getContainedPass(unsigned N) {
197 assert(N < PassVector.size() && "Pass number out of range!");
198 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
202 PassManagerType getPassManagerType() const override {
203 return PMT_BasicBlockPassManager;
207 char BBPassManager::ID = 0;
208 } // End anonymous namespace
212 //===----------------------------------------------------------------------===//
213 // FunctionPassManagerImpl
215 /// FunctionPassManagerImpl manages FPPassManagers
216 class FunctionPassManagerImpl : public Pass,
217 public PMDataManager,
218 public PMTopLevelManager {
219 virtual void anchor();
224 explicit FunctionPassManagerImpl() :
225 Pass(PT_PassManager, ID), PMDataManager(),
226 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
228 /// add - Add a pass to the queue of passes to run. This passes ownership of
229 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
230 /// will be destroyed as well, so there is no need to delete the pass. This
231 /// implies that all passes MUST be allocated with 'new'.
236 /// createPrinterPass - Get a function printer pass.
237 Pass *createPrinterPass(raw_ostream &O,
238 const std::string &Banner) const override {
239 return createPrintFunctionPass(O, Banner);
242 // Prepare for running an on the fly pass, freeing memory if needed
243 // from a previous run.
244 void releaseMemoryOnTheFly();
246 /// run - Execute all of the passes scheduled for execution. Keep track of
247 /// whether any of the passes modifies the module, and if so, return true.
248 bool run(Function &F);
250 /// doInitialization - Run all of the initializers for the function passes.
252 bool doInitialization(Module &M) override;
254 /// doFinalization - Run all of the finalizers for the function passes.
256 bool doFinalization(Module &M) override;
259 PMDataManager *getAsPMDataManager() override { return this; }
260 Pass *getAsPass() override { return this; }
261 PassManagerType getTopLevelPassManagerType() override {
262 return PMT_FunctionPassManager;
265 /// Pass Manager itself does not invalidate any analysis info.
266 void getAnalysisUsage(AnalysisUsage &Info) const override {
267 Info.setPreservesAll();
270 FPPassManager *getContainedManager(unsigned N) {
271 assert(N < PassManagers.size() && "Pass number out of range!");
272 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
277 void FunctionPassManagerImpl::anchor() {}
279 char FunctionPassManagerImpl::ID = 0;
280 } // End of legacy namespace
281 } // End of llvm namespace
284 //===----------------------------------------------------------------------===//
287 /// MPPassManager manages ModulePasses and function pass managers.
288 /// It batches all Module passes and function pass managers together and
289 /// sequences them to process one module.
290 class MPPassManager : public Pass, public PMDataManager {
293 explicit MPPassManager() :
294 Pass(PT_PassManager, ID), PMDataManager() { }
296 // Delete on the fly managers.
297 virtual ~MPPassManager() {
298 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
299 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
301 FunctionPassManagerImpl *FPP = I->second;
306 /// createPrinterPass - Get a module printer pass.
307 Pass *createPrinterPass(raw_ostream &O,
308 const std::string &Banner) const override {
309 return createPrintModulePass(O, Banner);
312 /// run - Execute all of the passes scheduled for execution. Keep track of
313 /// whether any of the passes modifies the module, and if so, return true.
314 bool runOnModule(Module &M);
316 using llvm::Pass::doInitialization;
317 using llvm::Pass::doFinalization;
319 /// doInitialization - Run all of the initializers for the module passes.
321 bool doInitialization();
323 /// doFinalization - Run all of the finalizers for the module passes.
325 bool doFinalization();
327 /// Pass Manager itself does not invalidate any analysis info.
328 void getAnalysisUsage(AnalysisUsage &Info) const override {
329 Info.setPreservesAll();
332 /// Add RequiredPass into list of lower level passes required by pass P.
333 /// RequiredPass is run on the fly by Pass Manager when P requests it
334 /// through getAnalysis interface.
335 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
337 /// Return function pass corresponding to PassInfo PI, that is
338 /// required by module pass MP. Instantiate analysis pass, by using
339 /// its runOnFunction() for function F.
340 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
342 const char *getPassName() const override {
343 return "Module Pass Manager";
346 PMDataManager *getAsPMDataManager() override { return this; }
347 Pass *getAsPass() override { return this; }
349 // Print passes managed by this manager
350 void dumpPassStructure(unsigned Offset) override {
351 dbgs().indent(Offset*2) << "ModulePass Manager\n";
352 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
353 ModulePass *MP = getContainedPass(Index);
354 MP->dumpPassStructure(Offset + 1);
355 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
356 OnTheFlyManagers.find(MP);
357 if (I != OnTheFlyManagers.end())
358 I->second->dumpPassStructure(Offset + 2);
359 dumpLastUses(MP, Offset+1);
363 ModulePass *getContainedPass(unsigned N) {
364 assert(N < PassVector.size() && "Pass number out of range!");
365 return static_cast<ModulePass *>(PassVector[N]);
368 PassManagerType getPassManagerType() const override {
369 return PMT_ModulePassManager;
373 /// Collection of on the fly FPPassManagers. These managers manage
374 /// function passes that are required by module passes.
375 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
378 char MPPassManager::ID = 0;
379 } // End anonymous namespace
383 //===----------------------------------------------------------------------===//
387 /// PassManagerImpl manages MPPassManagers
388 class PassManagerImpl : public Pass,
389 public PMDataManager,
390 public PMTopLevelManager {
391 virtual void anchor();
395 explicit PassManagerImpl() :
396 Pass(PT_PassManager, ID), PMDataManager(),
397 PMTopLevelManager(new MPPassManager()) {}
399 /// add - Add a pass to the queue of passes to run. This passes ownership of
400 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
401 /// will be destroyed as well, so there is no need to delete the pass. This
402 /// implies that all passes MUST be allocated with 'new'.
407 /// createPrinterPass - Get a module printer pass.
408 Pass *createPrinterPass(raw_ostream &O,
409 const std::string &Banner) const override {
410 return createPrintModulePass(O, Banner);
413 /// run - Execute all of the passes scheduled for execution. Keep track of
414 /// whether any of the passes modifies the module, and if so, return true.
417 using llvm::Pass::doInitialization;
418 using llvm::Pass::doFinalization;
420 /// doInitialization - Run all of the initializers for the module passes.
422 bool doInitialization();
424 /// doFinalization - Run all of the finalizers for the module passes.
426 bool doFinalization();
428 /// Pass Manager itself does not invalidate any analysis info.
429 void getAnalysisUsage(AnalysisUsage &Info) const override {
430 Info.setPreservesAll();
433 PMDataManager *getAsPMDataManager() override { return this; }
434 Pass *getAsPass() override { return this; }
435 PassManagerType getTopLevelPassManagerType() override {
436 return PMT_ModulePassManager;
439 MPPassManager *getContainedManager(unsigned N) {
440 assert(N < PassManagers.size() && "Pass number out of range!");
441 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
446 void PassManagerImpl::anchor() {}
448 char PassManagerImpl::ID = 0;
449 } // End of legacy namespace
450 } // End of llvm namespace
454 //===----------------------------------------------------------------------===//
455 /// TimingInfo Class - This class is used to calculate information about the
456 /// amount of time each pass takes to execute. This only happens when
457 /// -time-passes is enabled on the command line.
460 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
463 DenseMap<Pass*, Timer*> TimingData;
466 // Use 'create' member to get this.
467 TimingInfo() : TG("... Pass execution timing report ...") {}
469 // TimingDtor - Print out information about timing information
471 // Delete all of the timers, which accumulate their info into the
473 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
474 E = TimingData.end(); I != E; ++I)
476 // TimerGroup is deleted next, printing the report.
479 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
480 // to a non-null value (if the -time-passes option is enabled) or it leaves it
481 // null. It may be called multiple times.
482 static void createTheTimeInfo();
484 /// getPassTimer - Return the timer for the specified pass if it exists.
485 Timer *getPassTimer(Pass *P) {
486 if (P->getAsPMDataManager())
489 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
490 Timer *&T = TimingData[P];
492 T = new Timer(P->getPassName(), TG);
497 } // End of anon namespace
499 static TimingInfo *TheTimeInfo;
501 //===----------------------------------------------------------------------===//
502 // PMTopLevelManager implementation
504 /// Initialize top level manager. Create first pass manager.
505 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
506 PMDM->setTopLevelManager(this);
507 addPassManager(PMDM);
508 activeStack.push(PMDM);
511 /// Set pass P as the last user of the given analysis passes.
513 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
515 if (P->getResolver())
516 PDepth = P->getResolver()->getPMDataManager().getDepth();
518 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
519 E = AnalysisPasses.end(); I != E; ++I) {
526 // Update the last users of passes that are required transitive by AP.
527 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
528 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
529 SmallVector<Pass *, 12> LastUses;
530 SmallVector<Pass *, 12> LastPMUses;
531 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
532 E = IDs.end(); I != E; ++I) {
533 Pass *AnalysisPass = findAnalysisPass(*I);
534 assert(AnalysisPass && "Expected analysis pass to exist.");
535 AnalysisResolver *AR = AnalysisPass->getResolver();
536 assert(AR && "Expected analysis resolver to exist.");
537 unsigned APDepth = AR->getPMDataManager().getDepth();
539 if (PDepth == APDepth)
540 LastUses.push_back(AnalysisPass);
541 else if (PDepth > APDepth)
542 LastPMUses.push_back(AnalysisPass);
545 setLastUser(LastUses, P);
547 // If this pass has a corresponding pass manager, push higher level
548 // analysis to this pass manager.
549 if (P->getResolver())
550 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
553 // If AP is the last user of other passes then make P last user of
555 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
556 LUE = LastUser.end(); LUI != LUE; ++LUI) {
557 if (LUI->second == AP)
558 // DenseMap iterator is not invalidated here because
559 // this is just updating existing entries.
560 LastUser[LUI->first] = P;
565 /// Collect passes whose last user is P
566 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
568 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
569 InversedLastUser.find(P);
570 if (DMI == InversedLastUser.end())
573 SmallPtrSet<Pass *, 8> &LU = DMI->second;
574 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
575 E = LU.end(); I != E; ++I) {
576 LastUses.push_back(*I);
581 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
582 AnalysisUsage *AnUsage = nullptr;
583 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
584 if (DMI != AnUsageMap.end())
585 AnUsage = DMI->second;
587 AnUsage = new AnalysisUsage();
588 P->getAnalysisUsage(*AnUsage);
589 AnUsageMap[P] = AnUsage;
594 /// Schedule pass P for execution. Make sure that passes required by
595 /// P are run before P is run. Update analysis info maintained by
596 /// the manager. Remove dead passes. This is a recursive function.
597 void PMTopLevelManager::schedulePass(Pass *P) {
599 // TODO : Allocate function manager for this pass, other wise required set
600 // may be inserted into previous function manager
602 // Give pass a chance to prepare the stage.
603 P->preparePassManager(activeStack);
605 // If P is an analysis pass and it is available then do not
606 // generate the analysis again. Stale analysis info should not be
607 // available at this point.
609 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
610 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
615 AnalysisUsage *AnUsage = findAnalysisUsage(P);
617 bool checkAnalysis = true;
618 while (checkAnalysis) {
619 checkAnalysis = false;
621 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
622 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
623 E = RequiredSet.end(); I != E; ++I) {
625 Pass *AnalysisPass = findAnalysisPass(*I);
627 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
630 // Pass P is not in the global PassRegistry
631 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
632 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
633 dbgs() << "Required Passes:" << "\n";
634 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
635 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
636 Pass *AnalysisPass2 = findAnalysisPass(*I2);
638 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
640 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
641 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
642 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
647 assert(PI && "Expected required passes to be initialized");
648 AnalysisPass = PI->createPass();
649 if (P->getPotentialPassManagerType () ==
650 AnalysisPass->getPotentialPassManagerType())
651 // Schedule analysis pass that is managed by the same pass manager.
652 schedulePass(AnalysisPass);
653 else if (P->getPotentialPassManagerType () >
654 AnalysisPass->getPotentialPassManagerType()) {
655 // Schedule analysis pass that is managed by a new manager.
656 schedulePass(AnalysisPass);
657 // Recheck analysis passes to ensure that required analyses that
658 // are already checked are still available.
659 checkAnalysis = true;
661 // Do not schedule this analysis. Lower level analsyis
662 // passes are run on the fly.
668 // Now all required passes are available.
669 if (ImmutablePass *IP = P->getAsImmutablePass()) {
670 // P is a immutable pass and it will be managed by this
671 // top level manager. Set up analysis resolver to connect them.
672 PMDataManager *DM = getAsPMDataManager();
673 AnalysisResolver *AR = new AnalysisResolver(*DM);
675 DM->initializeAnalysisImpl(P);
676 addImmutablePass(IP);
677 DM->recordAvailableAnalysis(IP);
681 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
682 Pass *PP = P->createPrinterPass(
683 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
684 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
687 // Add the requested pass to the best available pass manager.
688 P->assignPassManager(activeStack, getTopLevelPassManagerType());
690 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
691 Pass *PP = P->createPrinterPass(
692 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
693 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
697 /// Find the pass that implements Analysis AID. Search immutable
698 /// passes and all pass managers. If desired pass is not found
699 /// then return NULL.
700 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
702 // Check pass managers
703 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
704 E = PassManagers.end(); I != E; ++I)
705 if (Pass *P = (*I)->findAnalysisPass(AID, false))
708 // Check other pass managers
709 for (SmallVectorImpl<PMDataManager *>::iterator
710 I = IndirectPassManagers.begin(),
711 E = IndirectPassManagers.end(); I != E; ++I)
712 if (Pass *P = (*I)->findAnalysisPass(AID, false))
715 // Check the immutable passes. Iterate in reverse order so that we find
716 // the most recently registered passes first.
717 for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
718 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
719 AnalysisID PI = (*I)->getPassID();
723 // If Pass not found then check the interfaces implemented by Immutable Pass
724 const PassInfo *PassInf =
725 PassRegistry::getPassRegistry()->getPassInfo(PI);
726 assert(PassInf && "Expected all immutable passes to be initialized");
727 const std::vector<const PassInfo*> &ImmPI =
728 PassInf->getInterfacesImplemented();
729 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
730 EE = ImmPI.end(); II != EE; ++II) {
731 if ((*II)->getTypeInfo() == AID)
739 // Print passes managed by this top level manager.
740 void PMTopLevelManager::dumpPasses() const {
742 if (PassDebugging < Structure)
745 // Print out the immutable passes
746 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
747 ImmutablePasses[i]->dumpPassStructure(0);
750 // Every class that derives from PMDataManager also derives from Pass
751 // (sometimes indirectly), but there's no inheritance relationship
752 // between PMDataManager and Pass, so we have to getAsPass to get
753 // from a PMDataManager* to a Pass*.
754 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
755 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
756 (*I)->getAsPass()->dumpPassStructure(1);
759 void PMTopLevelManager::dumpArguments() const {
761 if (PassDebugging < Arguments)
764 dbgs() << "Pass Arguments: ";
765 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
766 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
767 if (const PassInfo *PI =
768 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
769 assert(PI && "Expected all immutable passes to be initialized");
770 if (!PI->isAnalysisGroup())
771 dbgs() << " -" << PI->getPassArgument();
773 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
774 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
775 (*I)->dumpPassArguments();
779 void PMTopLevelManager::initializeAllAnalysisInfo() {
780 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
781 E = PassManagers.end(); I != E; ++I)
782 (*I)->initializeAnalysisInfo();
784 // Initailize other pass managers
785 for (SmallVectorImpl<PMDataManager *>::iterator
786 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
788 (*I)->initializeAnalysisInfo();
790 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
791 DME = LastUser.end(); DMI != DME; ++DMI) {
792 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
793 InversedLastUser.find(DMI->second);
794 if (InvDMI != InversedLastUser.end()) {
795 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
796 L.insert(DMI->first);
798 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
799 InversedLastUser[DMI->second] = L;
805 PMTopLevelManager::~PMTopLevelManager() {
806 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
807 E = PassManagers.end(); I != E; ++I)
810 for (SmallVectorImpl<ImmutablePass *>::iterator
811 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
814 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
815 DME = AnUsageMap.end(); DMI != DME; ++DMI)
819 //===----------------------------------------------------------------------===//
820 // PMDataManager implementation
822 /// Augement AvailableAnalysis by adding analysis made available by pass P.
823 void PMDataManager::recordAvailableAnalysis(Pass *P) {
824 AnalysisID PI = P->getPassID();
826 AvailableAnalysis[PI] = P;
828 assert(!AvailableAnalysis.empty());
830 // This pass is the current implementation of all of the interfaces it
831 // implements as well.
832 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
834 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
835 for (unsigned i = 0, e = II.size(); i != e; ++i)
836 AvailableAnalysis[II[i]->getTypeInfo()] = P;
839 // Return true if P preserves high level analysis used by other
840 // passes managed by this manager
841 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
842 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
843 if (AnUsage->getPreservesAll())
846 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
847 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
848 E = HigherLevelAnalysis.end(); I != E; ++I) {
850 if (P1->getAsImmutablePass() == nullptr &&
851 std::find(PreservedSet.begin(), PreservedSet.end(),
860 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
861 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
862 // Don't do this unless assertions are enabled.
866 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
867 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
869 // Verify preserved analysis
870 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
871 E = PreservedSet.end(); I != E; ++I) {
873 if (Pass *AP = findAnalysisPass(AID, true)) {
874 TimeRegion PassTimer(getPassTimer(AP));
875 AP->verifyAnalysis();
880 /// Remove Analysis not preserved by Pass P
881 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
882 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
883 if (AnUsage->getPreservesAll())
886 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
887 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
888 E = AvailableAnalysis.end(); I != E; ) {
889 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
890 if (Info->second->getAsImmutablePass() == nullptr &&
891 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
892 PreservedSet.end()) {
893 // Remove this analysis
894 if (PassDebugging >= Details) {
895 Pass *S = Info->second;
896 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
897 dbgs() << S->getPassName() << "'\n";
899 AvailableAnalysis.erase(Info);
903 // Check inherited analysis also. If P is not preserving analysis
904 // provided by parent manager then remove it here.
905 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
907 if (!InheritedAnalysis[Index])
910 for (DenseMap<AnalysisID, Pass*>::iterator
911 I = InheritedAnalysis[Index]->begin(),
912 E = InheritedAnalysis[Index]->end(); I != E; ) {
913 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
914 if (Info->second->getAsImmutablePass() == nullptr &&
915 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
916 PreservedSet.end()) {
917 // Remove this analysis
918 if (PassDebugging >= Details) {
919 Pass *S = Info->second;
920 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
921 dbgs() << S->getPassName() << "'\n";
923 InheritedAnalysis[Index]->erase(Info);
929 /// Remove analysis passes that are not used any longer
930 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
931 enum PassDebuggingString DBG_STR) {
933 SmallVector<Pass *, 12> DeadPasses;
935 // If this is a on the fly manager then it does not have TPM.
939 TPM->collectLastUses(DeadPasses, P);
941 if (PassDebugging >= Details && !DeadPasses.empty()) {
942 dbgs() << " -*- '" << P->getPassName();
943 dbgs() << "' is the last user of following pass instances.";
944 dbgs() << " Free these instances\n";
947 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
948 E = DeadPasses.end(); I != E; ++I)
949 freePass(*I, Msg, DBG_STR);
952 void PMDataManager::freePass(Pass *P, StringRef Msg,
953 enum PassDebuggingString DBG_STR) {
954 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
957 // If the pass crashes releasing memory, remember this.
958 PassManagerPrettyStackEntry X(P);
959 TimeRegion PassTimer(getPassTimer(P));
964 AnalysisID PI = P->getPassID();
965 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
966 // Remove the pass itself (if it is not already removed).
967 AvailableAnalysis.erase(PI);
969 // Remove all interfaces this pass implements, for which it is also
970 // listed as the available implementation.
971 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
972 for (unsigned i = 0, e = II.size(); i != e; ++i) {
973 DenseMap<AnalysisID, Pass*>::iterator Pos =
974 AvailableAnalysis.find(II[i]->getTypeInfo());
975 if (Pos != AvailableAnalysis.end() && Pos->second == P)
976 AvailableAnalysis.erase(Pos);
981 /// Add pass P into the PassVector. Update
982 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
983 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
984 // This manager is going to manage pass P. Set up analysis resolver
986 AnalysisResolver *AR = new AnalysisResolver(*this);
989 // If a FunctionPass F is the last user of ModulePass info M
990 // then the F's manager, not F, records itself as a last user of M.
991 SmallVector<Pass *, 12> TransferLastUses;
993 if (!ProcessAnalysis) {
995 PassVector.push_back(P);
999 // At the moment, this pass is the last user of all required passes.
1000 SmallVector<Pass *, 12> LastUses;
1001 SmallVector<Pass *, 8> RequiredPasses;
1002 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1004 unsigned PDepth = this->getDepth();
1006 collectRequiredAnalysis(RequiredPasses,
1007 ReqAnalysisNotAvailable, P);
1008 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1009 E = RequiredPasses.end(); I != E; ++I) {
1010 Pass *PRequired = *I;
1011 unsigned RDepth = 0;
1013 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1014 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1015 RDepth = DM.getDepth();
1017 if (PDepth == RDepth)
1018 LastUses.push_back(PRequired);
1019 else if (PDepth > RDepth) {
1020 // Let the parent claim responsibility of last use
1021 TransferLastUses.push_back(PRequired);
1022 // Keep track of higher level analysis used by this manager.
1023 HigherLevelAnalysis.push_back(PRequired);
1025 llvm_unreachable("Unable to accommodate Required Pass");
1028 // Set P as P's last user until someone starts using P.
1029 // However, if P is a Pass Manager then it does not need
1030 // to record its last user.
1031 if (!P->getAsPMDataManager())
1032 LastUses.push_back(P);
1033 TPM->setLastUser(LastUses, P);
1035 if (!TransferLastUses.empty()) {
1036 Pass *My_PM = getAsPass();
1037 TPM->setLastUser(TransferLastUses, My_PM);
1038 TransferLastUses.clear();
1041 // Now, take care of required analyses that are not available.
1042 for (SmallVectorImpl<AnalysisID>::iterator
1043 I = ReqAnalysisNotAvailable.begin(),
1044 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1045 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1046 Pass *AnalysisPass = PI->createPass();
1047 this->addLowerLevelRequiredPass(P, AnalysisPass);
1050 // Take a note of analysis required and made available by this pass.
1051 // Remove the analysis not preserved by this pass
1052 removeNotPreservedAnalysis(P);
1053 recordAvailableAnalysis(P);
1056 PassVector.push_back(P);
1060 /// Populate RP with analysis pass that are required by
1061 /// pass P and are available. Populate RP_NotAvail with analysis
1062 /// pass that are required by pass P but are not available.
1063 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1064 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1066 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1067 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1068 for (AnalysisUsage::VectorType::const_iterator
1069 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1070 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1071 RP.push_back(AnalysisPass);
1073 RP_NotAvail.push_back(*I);
1076 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1077 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1078 E = IDs.end(); I != E; ++I) {
1079 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1080 RP.push_back(AnalysisPass);
1082 RP_NotAvail.push_back(*I);
1086 // All Required analyses should be available to the pass as it runs! Here
1087 // we fill in the AnalysisImpls member of the pass so that it can
1088 // successfully use the getAnalysis() method to retrieve the
1089 // implementations it needs.
1091 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1092 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1094 for (AnalysisUsage::VectorType::const_iterator
1095 I = AnUsage->getRequiredSet().begin(),
1096 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1097 Pass *Impl = findAnalysisPass(*I, true);
1099 // This may be analysis pass that is initialized on the fly.
1100 // If that is not the case then it will raise an assert when it is used.
1102 AnalysisResolver *AR = P->getResolver();
1103 assert(AR && "Analysis Resolver is not set");
1104 AR->addAnalysisImplsPair(*I, Impl);
1108 /// Find the pass that implements Analysis AID. If desired pass is not found
1109 /// then return NULL.
1110 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1112 // Check if AvailableAnalysis map has one entry.
1113 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1115 if (I != AvailableAnalysis.end())
1118 // Search Parents through TopLevelManager
1120 return TPM->findAnalysisPass(AID);
1125 // Print list of passes that are last used by P.
1126 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1128 SmallVector<Pass *, 12> LUses;
1130 // If this is a on the fly manager then it does not have TPM.
1134 TPM->collectLastUses(LUses, P);
1136 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1137 E = LUses.end(); I != E; ++I) {
1138 dbgs() << "--" << std::string(Offset*2, ' ');
1139 (*I)->dumpPassStructure(0);
1143 void PMDataManager::dumpPassArguments() const {
1144 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1145 E = PassVector.end(); I != E; ++I) {
1146 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1147 PMD->dumpPassArguments();
1149 if (const PassInfo *PI =
1150 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1151 if (!PI->isAnalysisGroup())
1152 dbgs() << " -" << PI->getPassArgument();
1156 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1157 enum PassDebuggingString S2,
1159 if (PassDebugging < Executions)
1161 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1164 dbgs() << "Executing Pass '" << P->getPassName();
1166 case MODIFICATION_MSG:
1167 dbgs() << "Made Modification '" << P->getPassName();
1170 dbgs() << " Freeing Pass '" << P->getPassName();
1176 case ON_BASICBLOCK_MSG:
1177 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1179 case ON_FUNCTION_MSG:
1180 dbgs() << "' on Function '" << Msg << "'...\n";
1183 dbgs() << "' on Module '" << Msg << "'...\n";
1186 dbgs() << "' on Region '" << Msg << "'...\n";
1189 dbgs() << "' on Loop '" << Msg << "'...\n";
1192 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1199 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1200 if (PassDebugging < Details)
1203 AnalysisUsage analysisUsage;
1204 P->getAnalysisUsage(analysisUsage);
1205 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1208 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1209 if (PassDebugging < Details)
1212 AnalysisUsage analysisUsage;
1213 P->getAnalysisUsage(analysisUsage);
1214 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1217 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1218 const AnalysisUsage::VectorType &Set) const {
1219 assert(PassDebugging >= Details);
1222 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1223 for (unsigned i = 0; i != Set.size(); ++i) {
1224 if (i) dbgs() << ',';
1225 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1227 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1229 dbgs() << " Uninitialized Pass";
1232 dbgs() << ' ' << PInf->getPassName();
1237 /// Add RequiredPass into list of lower level passes required by pass P.
1238 /// RequiredPass is run on the fly by Pass Manager when P requests it
1239 /// through getAnalysis interface.
1240 /// This should be handled by specific pass manager.
1241 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1243 TPM->dumpArguments();
1247 // Module Level pass may required Function Level analysis info
1248 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1249 // to provide this on demand. In that case, in Pass manager terminology,
1250 // module level pass is requiring lower level analysis info managed by
1251 // lower level pass manager.
1253 // When Pass manager is not able to order required analysis info, Pass manager
1254 // checks whether any lower level manager will be able to provide this
1255 // analysis info on demand or not.
1257 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1258 dbgs() << "' required by '" << P->getPassName() << "'\n";
1260 llvm_unreachable("Unable to schedule pass");
1263 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1264 llvm_unreachable("Unable to find on the fly pass");
1268 PMDataManager::~PMDataManager() {
1269 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1270 E = PassVector.end(); I != E; ++I)
1274 //===----------------------------------------------------------------------===//
1275 // NOTE: Is this the right place to define this method ?
1276 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1277 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1278 return PM.findAnalysisPass(ID, dir);
1281 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1283 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1286 //===----------------------------------------------------------------------===//
1287 // BBPassManager implementation
1289 /// Execute all of the passes scheduled for execution by invoking
1290 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1291 /// the function, and if so, return true.
1292 bool BBPassManager::runOnFunction(Function &F) {
1293 if (F.isDeclaration())
1296 bool Changed = doInitialization(F);
1298 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1299 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1300 BasicBlockPass *BP = getContainedPass(Index);
1301 bool LocalChanged = false;
1303 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1304 dumpRequiredSet(BP);
1306 initializeAnalysisImpl(BP);
1309 // If the pass crashes, remember this.
1310 PassManagerPrettyStackEntry X(BP, *I);
1311 TimeRegion PassTimer(getPassTimer(BP));
1313 LocalChanged |= BP->runOnBasicBlock(*I);
1316 Changed |= LocalChanged;
1318 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1320 dumpPreservedSet(BP);
1322 verifyPreservedAnalysis(BP);
1323 removeNotPreservedAnalysis(BP);
1324 recordAvailableAnalysis(BP);
1325 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1328 return doFinalization(F) || Changed;
1331 // Implement doInitialization and doFinalization
1332 bool BBPassManager::doInitialization(Module &M) {
1333 bool Changed = false;
1335 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1336 Changed |= getContainedPass(Index)->doInitialization(M);
1341 bool BBPassManager::doFinalization(Module &M) {
1342 bool Changed = false;
1344 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1345 Changed |= getContainedPass(Index)->doFinalization(M);
1350 bool BBPassManager::doInitialization(Function &F) {
1351 bool Changed = false;
1353 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1354 BasicBlockPass *BP = getContainedPass(Index);
1355 Changed |= BP->doInitialization(F);
1361 bool BBPassManager::doFinalization(Function &F) {
1362 bool Changed = false;
1364 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1365 BasicBlockPass *BP = getContainedPass(Index);
1366 Changed |= BP->doFinalization(F);
1373 //===----------------------------------------------------------------------===//
1374 // FunctionPassManager implementation
1376 /// Create new Function pass manager
1377 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1378 FPM = new FunctionPassManagerImpl();
1379 // FPM is the top level manager.
1380 FPM->setTopLevelManager(FPM);
1382 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1383 FPM->setResolver(AR);
1386 FunctionPassManager::~FunctionPassManager() {
1390 /// add - Add a pass to the queue of passes to run. This passes
1391 /// ownership of the Pass to the PassManager. When the
1392 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1393 /// there is no need to delete the pass. (TODO delete passes.)
1394 /// This implies that all passes MUST be allocated with 'new'.
1395 void FunctionPassManager::add(Pass *P) {
1399 /// run - Execute all of the passes scheduled for execution. Keep
1400 /// track of whether any of the passes modifies the function, and if
1401 /// so, return true.
1403 bool FunctionPassManager::run(Function &F) {
1404 if (F.isMaterializable()) {
1406 if (F.Materialize(&errstr))
1407 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1413 /// doInitialization - Run all of the initializers for the function passes.
1415 bool FunctionPassManager::doInitialization() {
1416 return FPM->doInitialization(*M);
1419 /// doFinalization - Run all of the finalizers for the function passes.
1421 bool FunctionPassManager::doFinalization() {
1422 return FPM->doFinalization(*M);
1425 //===----------------------------------------------------------------------===//
1426 // FunctionPassManagerImpl implementation
1428 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1429 bool Changed = false;
1434 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1435 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1436 E = IPV.end(); I != E; ++I) {
1437 Changed |= (*I)->doInitialization(M);
1440 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1441 Changed |= getContainedManager(Index)->doInitialization(M);
1446 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1447 bool Changed = false;
1449 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1450 Changed |= getContainedManager(Index)->doFinalization(M);
1452 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1453 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1454 E = IPV.end(); I != E; ++I) {
1455 Changed |= (*I)->doFinalization(M);
1461 /// cleanup - After running all passes, clean up pass manager cache.
1462 void FPPassManager::cleanup() {
1463 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1464 FunctionPass *FP = getContainedPass(Index);
1465 AnalysisResolver *AR = FP->getResolver();
1466 assert(AR && "Analysis Resolver is not set");
1467 AR->clearAnalysisImpls();
1471 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1474 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1475 FPPassManager *FPPM = getContainedManager(Index);
1476 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1477 FPPM->getContainedPass(Index)->releaseMemory();
1483 // Execute all the passes managed by this top level manager.
1484 // Return true if any function is modified by a pass.
1485 bool FunctionPassManagerImpl::run(Function &F) {
1486 bool Changed = false;
1487 TimingInfo::createTheTimeInfo();
1489 initializeAllAnalysisInfo();
1490 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1491 Changed |= getContainedManager(Index)->runOnFunction(F);
1493 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1494 getContainedManager(Index)->cleanup();
1500 //===----------------------------------------------------------------------===//
1501 // FPPassManager implementation
1503 char FPPassManager::ID = 0;
1504 /// Print passes managed by this manager
1505 void FPPassManager::dumpPassStructure(unsigned Offset) {
1506 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1507 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1508 FunctionPass *FP = getContainedPass(Index);
1509 FP->dumpPassStructure(Offset + 1);
1510 dumpLastUses(FP, Offset+1);
1515 /// Execute all of the passes scheduled for execution by invoking
1516 /// runOnFunction method. Keep track of whether any of the passes modifies
1517 /// the function, and if so, return true.
1518 bool FPPassManager::runOnFunction(Function &F) {
1519 if (F.isDeclaration())
1522 bool Changed = false;
1524 // Collect inherited analysis from Module level pass manager.
1525 populateInheritedAnalysis(TPM->activeStack);
1527 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1528 FunctionPass *FP = getContainedPass(Index);
1529 bool LocalChanged = false;
1531 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1532 dumpRequiredSet(FP);
1534 initializeAnalysisImpl(FP);
1537 PassManagerPrettyStackEntry X(FP, F);
1538 TimeRegion PassTimer(getPassTimer(FP));
1540 LocalChanged |= FP->runOnFunction(F);
1543 Changed |= LocalChanged;
1545 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1546 dumpPreservedSet(FP);
1548 verifyPreservedAnalysis(FP);
1549 removeNotPreservedAnalysis(FP);
1550 recordAvailableAnalysis(FP);
1551 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1556 bool FPPassManager::runOnModule(Module &M) {
1557 bool Changed = false;
1559 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1560 Changed |= runOnFunction(*I);
1565 bool FPPassManager::doInitialization(Module &M) {
1566 bool Changed = false;
1568 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1569 Changed |= getContainedPass(Index)->doInitialization(M);
1574 bool FPPassManager::doFinalization(Module &M) {
1575 bool Changed = false;
1577 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1578 Changed |= getContainedPass(Index)->doFinalization(M);
1583 //===----------------------------------------------------------------------===//
1584 // MPPassManager implementation
1586 /// Execute all of the passes scheduled for execution by invoking
1587 /// runOnModule method. Keep track of whether any of the passes modifies
1588 /// the module, and if so, return true.
1590 MPPassManager::runOnModule(Module &M) {
1591 bool Changed = false;
1593 // Initialize on-the-fly passes
1594 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1595 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1597 FunctionPassManagerImpl *FPP = I->second;
1598 Changed |= FPP->doInitialization(M);
1601 // Initialize module passes
1602 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1603 Changed |= getContainedPass(Index)->doInitialization(M);
1605 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1606 ModulePass *MP = getContainedPass(Index);
1607 bool LocalChanged = false;
1609 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1610 dumpRequiredSet(MP);
1612 initializeAnalysisImpl(MP);
1615 PassManagerPrettyStackEntry X(MP, M);
1616 TimeRegion PassTimer(getPassTimer(MP));
1618 LocalChanged |= MP->runOnModule(M);
1621 Changed |= LocalChanged;
1623 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1624 M.getModuleIdentifier());
1625 dumpPreservedSet(MP);
1627 verifyPreservedAnalysis(MP);
1628 removeNotPreservedAnalysis(MP);
1629 recordAvailableAnalysis(MP);
1630 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1633 // Finalize module passes
1634 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1635 Changed |= getContainedPass(Index)->doFinalization(M);
1637 // Finalize on-the-fly passes
1638 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1639 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1641 FunctionPassManagerImpl *FPP = I->second;
1642 // We don't know when is the last time an on-the-fly pass is run,
1643 // so we need to releaseMemory / finalize here
1644 FPP->releaseMemoryOnTheFly();
1645 Changed |= FPP->doFinalization(M);
1651 /// Add RequiredPass into list of lower level passes required by pass P.
1652 /// RequiredPass is run on the fly by Pass Manager when P requests it
1653 /// through getAnalysis interface.
1654 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1655 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1656 "Unable to handle Pass that requires lower level Analysis pass");
1657 assert((P->getPotentialPassManagerType() <
1658 RequiredPass->getPotentialPassManagerType()) &&
1659 "Unable to handle Pass that requires lower level Analysis pass");
1663 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1665 FPP = new FunctionPassManagerImpl();
1666 // FPP is the top level manager.
1667 FPP->setTopLevelManager(FPP);
1669 OnTheFlyManagers[P] = FPP;
1671 const PassInfo * RequiredPassPI =
1672 PassRegistry::getPassRegistry()->getPassInfo(RequiredPass->getPassID());
1674 Pass *FoundPass = nullptr;
1675 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1677 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1680 FoundPass = RequiredPass;
1681 // This should be guaranteed to add RequiredPass to the passmanager given
1682 // that we checked for an avaiable analysis above.
1683 FPP->add(RequiredPass);
1685 // Register P as the last user of FoundPass or RequiredPass.
1686 SmallVector<Pass *, 1> LU;
1687 LU.push_back(FoundPass);
1688 FPP->setLastUser(LU, P);
1691 /// Return function pass corresponding to PassInfo PI, that is
1692 /// required by module pass MP. Instantiate analysis pass, by using
1693 /// its runOnFunction() for function F.
1694 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1695 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1696 assert(FPP && "Unable to find on the fly pass");
1698 FPP->releaseMemoryOnTheFly();
1700 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1704 //===----------------------------------------------------------------------===//
1705 // PassManagerImpl implementation
1708 /// run - Execute all of the passes scheduled for execution. Keep track of
1709 /// whether any of the passes modifies the module, and if so, return true.
1710 bool PassManagerImpl::run(Module &M) {
1711 bool Changed = false;
1712 TimingInfo::createTheTimeInfo();
1717 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1718 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1719 E = IPV.end(); I != E; ++I) {
1720 Changed |= (*I)->doInitialization(M);
1723 initializeAllAnalysisInfo();
1724 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1725 Changed |= getContainedManager(Index)->runOnModule(M);
1727 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1728 E = IPV.end(); I != E; ++I) {
1729 Changed |= (*I)->doFinalization(M);
1735 //===----------------------------------------------------------------------===//
1736 // PassManager implementation
1738 /// Create new pass manager
1739 PassManager::PassManager() {
1740 PM = new PassManagerImpl();
1741 // PM is the top level manager
1742 PM->setTopLevelManager(PM);
1745 PassManager::~PassManager() {
1749 /// add - Add a pass to the queue of passes to run. This passes ownership of
1750 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1751 /// will be destroyed as well, so there is no need to delete the pass. This
1752 /// implies that all passes MUST be allocated with 'new'.
1753 void PassManager::add(Pass *P) {
1757 /// run - Execute all of the passes scheduled for execution. Keep track of
1758 /// whether any of the passes modifies the module, and if so, return true.
1759 bool PassManager::run(Module &M) {
1763 //===----------------------------------------------------------------------===//
1764 // TimingInfo implementation
1766 bool llvm::TimePassesIsEnabled = false;
1767 static cl::opt<bool,true>
1768 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1769 cl::desc("Time each pass, printing elapsed time for each on exit"));
1771 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1772 // a non-null value (if the -time-passes option is enabled) or it leaves it
1773 // null. It may be called multiple times.
1774 void TimingInfo::createTheTimeInfo() {
1775 if (!TimePassesIsEnabled || TheTimeInfo) return;
1777 // Constructed the first time this is called, iff -time-passes is enabled.
1778 // This guarantees that the object will be constructed before static globals,
1779 // thus it will be destroyed before them.
1780 static ManagedStatic<TimingInfo> TTI;
1781 TheTimeInfo = &*TTI;
1784 /// If TimingInfo is enabled then start pass timer.
1785 Timer *llvm::getPassTimer(Pass *P) {
1787 return TheTimeInfo->getPassTimer(P);
1791 //===----------------------------------------------------------------------===//
1792 // PMStack implementation
1795 // Pop Pass Manager from the stack and clear its analysis info.
1796 void PMStack::pop() {
1798 PMDataManager *Top = this->top();
1799 Top->initializeAnalysisInfo();
1804 // Push PM on the stack and set its top level manager.
1805 void PMStack::push(PMDataManager *PM) {
1806 assert(PM && "Unable to push. Pass Manager expected");
1807 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1809 if (!this->empty()) {
1810 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1811 && "pushing bad pass manager to PMStack");
1812 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1814 assert(TPM && "Unable to find top level manager");
1815 TPM->addIndirectPassManager(PM);
1816 PM->setTopLevelManager(TPM);
1817 PM->setDepth(this->top()->getDepth()+1);
1819 assert((PM->getPassManagerType() == PMT_ModulePassManager
1820 || PM->getPassManagerType() == PMT_FunctionPassManager)
1821 && "pushing bad pass manager to PMStack");
1828 // Dump content of the pass manager stack.
1829 void PMStack::dump() const {
1830 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1831 E = S.end(); I != E; ++I)
1832 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1838 /// Find appropriate Module Pass Manager in the PM Stack and
1839 /// add self into that manager.
1840 void ModulePass::assignPassManager(PMStack &PMS,
1841 PassManagerType PreferredType) {
1842 // Find Module Pass Manager
1843 while (!PMS.empty()) {
1844 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1845 if (TopPMType == PreferredType)
1846 break; // We found desired pass manager
1847 else if (TopPMType > PMT_ModulePassManager)
1848 PMS.pop(); // Pop children pass managers
1852 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1853 PMS.top()->add(this);
1856 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1857 /// in the PM Stack and add self into that manager.
1858 void FunctionPass::assignPassManager(PMStack &PMS,
1859 PassManagerType PreferredType) {
1861 // Find Function Pass Manager
1862 while (!PMS.empty()) {
1863 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1869 // Create new Function Pass Manager if needed.
1871 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1872 FPP = (FPPassManager *)PMS.top();
1874 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1875 PMDataManager *PMD = PMS.top();
1877 // [1] Create new Function Pass Manager
1878 FPP = new FPPassManager();
1879 FPP->populateInheritedAnalysis(PMS);
1881 // [2] Set up new manager's top level manager
1882 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1883 TPM->addIndirectPassManager(FPP);
1885 // [3] Assign manager to manage this new manager. This may create
1886 // and push new managers into PMS
1887 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1889 // [4] Push new manager into PMS
1893 // Assign FPP as the manager of this pass.
1897 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1898 /// in the PM Stack and add self into that manager.
1899 void BasicBlockPass::assignPassManager(PMStack &PMS,
1900 PassManagerType PreferredType) {
1903 // Basic Pass Manager is a leaf pass manager. It does not handle
1904 // any other pass manager.
1906 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1907 BBP = (BBPassManager *)PMS.top();
1909 // If leaf manager is not Basic Block Pass manager then create new
1910 // basic Block Pass manager.
1911 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1912 PMDataManager *PMD = PMS.top();
1914 // [1] Create new Basic Block Manager
1915 BBP = new BBPassManager();
1917 // [2] Set up new manager's top level manager
1918 // Basic Block Pass Manager does not live by itself
1919 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1920 TPM->addIndirectPassManager(BBP);
1922 // [3] Assign manager to manage this new manager. This may create
1923 // and push new managers into PMS
1924 BBP->assignPassManager(PMS, PreferredType);
1926 // [4] Push new manager into PMS
1930 // Assign BBP as the manager of this pass.
1934 PassManagerBase::~PassManagerBase() {}