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/Assembly/PrintModulePass.h"
16 #include "llvm/Assembly/Writer.h"
17 #include "llvm/IR/LegacyPassManager.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/IR/LegacyPassManagers.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/PassNameParser.h"
26 #include "llvm/Support/Timer.h"
27 #include "llvm/Support/raw_ostream.h"
31 using namespace llvm::legacy;
33 // See PassManagers.h for Pass Manager infrastructure overview.
35 //===----------------------------------------------------------------------===//
36 // Pass debugging information. Often it is useful to find out what pass is
37 // running when a crash occurs in a utility. When this library is compiled with
38 // debugging on, a command line option (--debug-pass) is enabled that causes the
39 // pass name to be printed before it executes.
43 // Different debug levels that can be enabled...
45 Disabled, Arguments, Structure, Executions, Details
49 static cl::opt<enum PassDebugLevel>
50 PassDebugging("debug-pass", cl::Hidden,
51 cl::desc("Print PassManager debugging information"),
53 clEnumVal(Disabled , "disable debug output"),
54 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
55 clEnumVal(Structure , "print pass structure before run()"),
56 clEnumVal(Executions, "print pass name before it is executed"),
57 clEnumVal(Details , "print pass details when it is executed"),
61 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
65 // Print IR out before/after specified passes.
67 PrintBefore("print-before",
68 llvm::cl::desc("Print IR before specified passes"),
72 PrintAfter("print-after",
73 llvm::cl::desc("Print IR after specified passes"),
77 PrintBeforeAll("print-before-all",
78 llvm::cl::desc("Print IR before each pass"),
81 PrintAfterAll("print-after-all",
82 llvm::cl::desc("Print IR after each pass"),
85 /// This is a helper to determine whether to print IR before or
88 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
89 PassOptionList &PassesToPrint) {
90 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
91 const llvm::PassInfo *PassInf = PassesToPrint[i];
93 if (PassInf->getPassArgument() == PI->getPassArgument()) {
100 /// This is a utility to check whether a pass should have IR dumped
102 static bool ShouldPrintBeforePass(const PassInfo *PI) {
103 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
106 /// This is a utility to check whether a pass should have IR dumped
108 static bool ShouldPrintAfterPass(const PassInfo *PI) {
109 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
112 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
113 /// or higher is specified.
114 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
115 return PassDebugging >= Executions;
121 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
122 if (V == 0 && M == 0)
123 OS << "Releasing pass '";
125 OS << "Running pass '";
127 OS << P->getPassName() << "'";
130 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
139 if (isa<Function>(V))
141 else if (isa<BasicBlock>(V))
147 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
153 //===----------------------------------------------------------------------===//
156 /// BBPassManager manages BasicBlockPass. It batches all the
157 /// pass together and sequence them to process one basic block before
158 /// processing next basic block.
159 class BBPassManager : public PMDataManager, public FunctionPass {
163 explicit BBPassManager()
164 : PMDataManager(), FunctionPass(ID) {}
166 /// Execute all of the passes scheduled for execution. Keep track of
167 /// whether any of the passes modifies the function, and if so, return true.
168 bool runOnFunction(Function &F);
170 /// Pass Manager itself does not invalidate any analysis info.
171 void getAnalysisUsage(AnalysisUsage &Info) const {
172 Info.setPreservesAll();
175 bool doInitialization(Module &M);
176 bool doInitialization(Function &F);
177 bool doFinalization(Module &M);
178 bool doFinalization(Function &F);
180 virtual PMDataManager *getAsPMDataManager() { return this; }
181 virtual Pass *getAsPass() { return this; }
183 virtual const char *getPassName() const {
184 return "BasicBlock Pass Manager";
187 // Print passes managed by this manager
188 void dumpPassStructure(unsigned Offset) {
189 llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
190 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
191 BasicBlockPass *BP = getContainedPass(Index);
192 BP->dumpPassStructure(Offset + 1);
193 dumpLastUses(BP, Offset+1);
197 BasicBlockPass *getContainedPass(unsigned N) {
198 assert(N < PassVector.size() && "Pass number out of range!");
199 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
203 virtual PassManagerType getPassManagerType() const {
204 return PMT_BasicBlockPassManager;
208 char BBPassManager::ID = 0;
209 } // End anonymous namespace
213 //===----------------------------------------------------------------------===//
214 // FunctionPassManagerImpl
216 /// FunctionPassManagerImpl manages FPPassManagers
217 class FunctionPassManagerImpl : public Pass,
218 public PMDataManager,
219 public PMTopLevelManager {
220 virtual void anchor();
225 explicit FunctionPassManagerImpl() :
226 Pass(PT_PassManager, ID), PMDataManager(),
227 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
229 /// add - Add a pass to the queue of passes to run. This passes ownership of
230 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
231 /// will be destroyed as well, so there is no need to delete the pass. This
232 /// implies that all passes MUST be allocated with 'new'.
237 /// createPrinterPass - Get a function printer pass.
238 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
239 return createPrintFunctionPass(Banner, &O);
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);
254 /// doFinalization - Run all of the finalizers for the function passes.
256 bool doFinalization(Module &M);
259 virtual PMDataManager *getAsPMDataManager() { return this; }
260 virtual Pass *getAsPass() { return this; }
261 virtual PassManagerType getTopLevelPassManagerType() {
262 return PMT_FunctionPassManager;
265 /// Pass Manager itself does not invalidate any analysis info.
266 void getAnalysisUsage(AnalysisUsage &Info) const {
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, const std::string &Banner) const {
308 return createPrintModulePass(&O, false, 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 {
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 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
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 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
341 virtual const char *getPassName() const {
342 return "Module Pass Manager";
345 virtual PMDataManager *getAsPMDataManager() { return this; }
346 virtual Pass *getAsPass() { return this; }
348 // Print passes managed by this manager
349 void dumpPassStructure(unsigned Offset) {
350 llvm::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 virtual PassManagerType getPassManagerType() const {
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 /// add - Add a pass to the queue of passes to run. This passes ownership of
399 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
400 /// will be destroyed as well, so there is no need to delete the pass. This
401 /// implies that all passes MUST be allocated with 'new'.
406 /// createPrinterPass - Get a module printer pass.
407 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
408 return createPrintModulePass(&O, false, Banner);
411 /// run - Execute all of the passes scheduled for execution. Keep track of
412 /// whether any of the passes modifies the module, and if so, return true.
415 using llvm::Pass::doInitialization;
416 using llvm::Pass::doFinalization;
418 /// doInitialization - Run all of the initializers for the module passes.
420 bool doInitialization();
422 /// doFinalization - Run all of the finalizers for the module passes.
424 bool doFinalization();
426 /// Pass Manager itself does not invalidate any analysis info.
427 void getAnalysisUsage(AnalysisUsage &Info) const {
428 Info.setPreservesAll();
431 virtual PMDataManager *getAsPMDataManager() { return this; }
432 virtual Pass *getAsPass() { return this; }
433 virtual PassManagerType getTopLevelPassManagerType() {
434 return PMT_ModulePassManager;
437 MPPassManager *getContainedManager(unsigned N) {
438 assert(N < PassManagers.size() && "Pass number out of range!");
439 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
444 void PassManagerImpl::anchor() {}
446 char PassManagerImpl::ID = 0;
447 } // End of legacy namespace
448 } // End of llvm namespace
452 //===----------------------------------------------------------------------===//
453 /// TimingInfo Class - This class is used to calculate information about the
454 /// amount of time each pass takes to execute. This only happens when
455 /// -time-passes is enabled on the command line.
458 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
461 DenseMap<Pass*, Timer*> TimingData;
464 // Use 'create' member to get this.
465 TimingInfo() : TG("... Pass execution timing report ...") {}
467 // TimingDtor - Print out information about timing information
469 // Delete all of the timers, which accumulate their info into the
471 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
472 E = TimingData.end(); I != E; ++I)
474 // TimerGroup is deleted next, printing the report.
477 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
478 // to a non-null value (if the -time-passes option is enabled) or it leaves it
479 // null. It may be called multiple times.
480 static void createTheTimeInfo();
482 /// getPassTimer - Return the timer for the specified pass if it exists.
483 Timer *getPassTimer(Pass *P) {
484 if (P->getAsPMDataManager())
487 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
488 Timer *&T = TimingData[P];
490 T = new Timer(P->getPassName(), TG);
495 } // End of anon namespace
497 static TimingInfo *TheTimeInfo;
499 //===----------------------------------------------------------------------===//
500 // PMTopLevelManager implementation
502 /// Initialize top level manager. Create first pass manager.
503 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
504 PMDM->setTopLevelManager(this);
505 addPassManager(PMDM);
506 activeStack.push(PMDM);
509 /// Set pass P as the last user of the given analysis passes.
511 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
513 if (P->getResolver())
514 PDepth = P->getResolver()->getPMDataManager().getDepth();
516 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
517 E = AnalysisPasses.end(); I != E; ++I) {
524 // Update the last users of passes that are required transitive by AP.
525 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
526 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
527 SmallVector<Pass *, 12> LastUses;
528 SmallVector<Pass *, 12> LastPMUses;
529 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
530 E = IDs.end(); I != E; ++I) {
531 Pass *AnalysisPass = findAnalysisPass(*I);
532 assert(AnalysisPass && "Expected analysis pass to exist.");
533 AnalysisResolver *AR = AnalysisPass->getResolver();
534 assert(AR && "Expected analysis resolver to exist.");
535 unsigned APDepth = AR->getPMDataManager().getDepth();
537 if (PDepth == APDepth)
538 LastUses.push_back(AnalysisPass);
539 else if (PDepth > APDepth)
540 LastPMUses.push_back(AnalysisPass);
543 setLastUser(LastUses, P);
545 // If this pass has a corresponding pass manager, push higher level
546 // analysis to this pass manager.
547 if (P->getResolver())
548 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
551 // If AP is the last user of other passes then make P last user of
553 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
554 LUE = LastUser.end(); LUI != LUE; ++LUI) {
555 if (LUI->second == AP)
556 // DenseMap iterator is not invalidated here because
557 // this is just updating existing entries.
558 LastUser[LUI->first] = P;
563 /// Collect passes whose last user is P
564 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
566 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
567 InversedLastUser.find(P);
568 if (DMI == InversedLastUser.end())
571 SmallPtrSet<Pass *, 8> &LU = DMI->second;
572 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
573 E = LU.end(); I != E; ++I) {
574 LastUses.push_back(*I);
579 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
580 AnalysisUsage *AnUsage = NULL;
581 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
582 if (DMI != AnUsageMap.end())
583 AnUsage = DMI->second;
585 AnUsage = new AnalysisUsage();
586 P->getAnalysisUsage(*AnUsage);
587 AnUsageMap[P] = AnUsage;
592 /// Schedule pass P for execution. Make sure that passes required by
593 /// P are run before P is run. Update analysis info maintained by
594 /// the manager. Remove dead passes. This is a recursive function.
595 void PMTopLevelManager::schedulePass(Pass *P) {
597 // TODO : Allocate function manager for this pass, other wise required set
598 // may be inserted into previous function manager
600 // Give pass a chance to prepare the stage.
601 P->preparePassManager(activeStack);
603 // If P is an analysis pass and it is available then do not
604 // generate the analysis again. Stale analysis info should not be
605 // available at this point.
607 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
608 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
613 AnalysisUsage *AnUsage = findAnalysisUsage(P);
615 bool checkAnalysis = true;
616 while (checkAnalysis) {
617 checkAnalysis = false;
619 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
620 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
621 E = RequiredSet.end(); I != E; ++I) {
623 Pass *AnalysisPass = findAnalysisPass(*I);
625 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
628 // Pass P is not in the global PassRegistry
629 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
630 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
631 dbgs() << "Required Passes:" << "\n";
632 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
633 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
634 Pass *AnalysisPass2 = findAnalysisPass(*I2);
636 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
638 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
639 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
640 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
645 assert(PI && "Expected required passes to be initialized");
646 AnalysisPass = PI->createPass();
647 if (P->getPotentialPassManagerType () ==
648 AnalysisPass->getPotentialPassManagerType())
649 // Schedule analysis pass that is managed by the same pass manager.
650 schedulePass(AnalysisPass);
651 else if (P->getPotentialPassManagerType () >
652 AnalysisPass->getPotentialPassManagerType()) {
653 // Schedule analysis pass that is managed by a new manager.
654 schedulePass(AnalysisPass);
655 // Recheck analysis passes to ensure that required analyses that
656 // are already checked are still available.
657 checkAnalysis = true;
659 // Do not schedule this analysis. Lower level analsyis
660 // passes are run on the fly.
666 // Now all required passes are available.
667 if (ImmutablePass *IP = P->getAsImmutablePass()) {
668 // P is a immutable pass and it will be managed by this
669 // top level manager. Set up analysis resolver to connect them.
670 PMDataManager *DM = getAsPMDataManager();
671 AnalysisResolver *AR = new AnalysisResolver(*DM);
673 DM->initializeAnalysisImpl(P);
674 addImmutablePass(IP);
675 DM->recordAvailableAnalysis(IP);
679 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
680 Pass *PP = P->createPrinterPass(
681 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
682 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
685 // Add the requested pass to the best available pass manager.
686 P->assignPassManager(activeStack, getTopLevelPassManagerType());
688 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
689 Pass *PP = P->createPrinterPass(
690 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
691 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
695 /// Find the pass that implements Analysis AID. Search immutable
696 /// passes and all pass managers. If desired pass is not found
697 /// then return NULL.
698 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
700 // Check pass managers
701 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
702 E = PassManagers.end(); I != E; ++I)
703 if (Pass *P = (*I)->findAnalysisPass(AID, false))
706 // Check other pass managers
707 for (SmallVectorImpl<PMDataManager *>::iterator
708 I = IndirectPassManagers.begin(),
709 E = IndirectPassManagers.end(); I != E; ++I)
710 if (Pass *P = (*I)->findAnalysisPass(AID, false))
713 // Check the immutable passes. Iterate in reverse order so that we find
714 // the most recently registered passes first.
715 for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
716 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
717 AnalysisID PI = (*I)->getPassID();
721 // If Pass not found then check the interfaces implemented by Immutable Pass
722 const PassInfo *PassInf =
723 PassRegistry::getPassRegistry()->getPassInfo(PI);
724 assert(PassInf && "Expected all immutable passes to be initialized");
725 const std::vector<const PassInfo*> &ImmPI =
726 PassInf->getInterfacesImplemented();
727 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
728 EE = ImmPI.end(); II != EE; ++II) {
729 if ((*II)->getTypeInfo() == AID)
737 // Print passes managed by this top level manager.
738 void PMTopLevelManager::dumpPasses() const {
740 if (PassDebugging < Structure)
743 // Print out the immutable passes
744 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
745 ImmutablePasses[i]->dumpPassStructure(0);
748 // Every class that derives from PMDataManager also derives from Pass
749 // (sometimes indirectly), but there's no inheritance relationship
750 // between PMDataManager and Pass, so we have to getAsPass to get
751 // from a PMDataManager* to a Pass*.
752 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
753 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
754 (*I)->getAsPass()->dumpPassStructure(1);
757 void PMTopLevelManager::dumpArguments() const {
759 if (PassDebugging < Arguments)
762 dbgs() << "Pass Arguments: ";
763 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
764 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
765 if (const PassInfo *PI =
766 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
767 assert(PI && "Expected all immutable passes to be initialized");
768 if (!PI->isAnalysisGroup())
769 dbgs() << " -" << PI->getPassArgument();
771 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
772 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
773 (*I)->dumpPassArguments();
777 void PMTopLevelManager::initializeAllAnalysisInfo() {
778 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
779 E = PassManagers.end(); I != E; ++I)
780 (*I)->initializeAnalysisInfo();
782 // Initailize other pass managers
783 for (SmallVectorImpl<PMDataManager *>::iterator
784 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
786 (*I)->initializeAnalysisInfo();
788 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
789 DME = LastUser.end(); DMI != DME; ++DMI) {
790 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
791 InversedLastUser.find(DMI->second);
792 if (InvDMI != InversedLastUser.end()) {
793 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
794 L.insert(DMI->first);
796 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
797 InversedLastUser[DMI->second] = L;
803 PMTopLevelManager::~PMTopLevelManager() {
804 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
805 E = PassManagers.end(); I != E; ++I)
808 for (SmallVectorImpl<ImmutablePass *>::iterator
809 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
812 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
813 DME = AnUsageMap.end(); DMI != DME; ++DMI)
817 //===----------------------------------------------------------------------===//
818 // PMDataManager implementation
820 /// Augement AvailableAnalysis by adding analysis made available by pass P.
821 void PMDataManager::recordAvailableAnalysis(Pass *P) {
822 AnalysisID PI = P->getPassID();
824 AvailableAnalysis[PI] = P;
826 assert(!AvailableAnalysis.empty());
828 // This pass is the current implementation of all of the interfaces it
829 // implements as well.
830 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
831 if (PInf == 0) return;
832 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
833 for (unsigned i = 0, e = II.size(); i != e; ++i)
834 AvailableAnalysis[II[i]->getTypeInfo()] = P;
837 // Return true if P preserves high level analysis used by other
838 // passes managed by this manager
839 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
840 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
841 if (AnUsage->getPreservesAll())
844 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
845 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
846 E = HigherLevelAnalysis.end(); I != E; ++I) {
848 if (P1->getAsImmutablePass() == 0 &&
849 std::find(PreservedSet.begin(), PreservedSet.end(),
858 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
859 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
860 // Don't do this unless assertions are enabled.
864 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
865 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
867 // Verify preserved analysis
868 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
869 E = PreservedSet.end(); I != E; ++I) {
871 if (Pass *AP = findAnalysisPass(AID, true)) {
872 TimeRegion PassTimer(getPassTimer(AP));
873 AP->verifyAnalysis();
878 /// Remove Analysis not preserved by Pass P
879 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
880 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
881 if (AnUsage->getPreservesAll())
884 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
885 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
886 E = AvailableAnalysis.end(); I != E; ) {
887 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
888 if (Info->second->getAsImmutablePass() == 0 &&
889 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
890 PreservedSet.end()) {
891 // Remove this analysis
892 if (PassDebugging >= Details) {
893 Pass *S = Info->second;
894 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
895 dbgs() << S->getPassName() << "'\n";
897 AvailableAnalysis.erase(Info);
901 // Check inherited analysis also. If P is not preserving analysis
902 // provided by parent manager then remove it here.
903 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
905 if (!InheritedAnalysis[Index])
908 for (DenseMap<AnalysisID, Pass*>::iterator
909 I = InheritedAnalysis[Index]->begin(),
910 E = InheritedAnalysis[Index]->end(); I != E; ) {
911 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
912 if (Info->second->getAsImmutablePass() == 0 &&
913 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
914 PreservedSet.end()) {
915 // Remove this analysis
916 if (PassDebugging >= Details) {
917 Pass *S = Info->second;
918 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
919 dbgs() << S->getPassName() << "'\n";
921 InheritedAnalysis[Index]->erase(Info);
927 /// Remove analysis passes that are not used any longer
928 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
929 enum PassDebuggingString DBG_STR) {
931 SmallVector<Pass *, 12> DeadPasses;
933 // If this is a on the fly manager then it does not have TPM.
937 TPM->collectLastUses(DeadPasses, P);
939 if (PassDebugging >= Details && !DeadPasses.empty()) {
940 dbgs() << " -*- '" << P->getPassName();
941 dbgs() << "' is the last user of following pass instances.";
942 dbgs() << " Free these instances\n";
945 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
946 E = DeadPasses.end(); I != E; ++I)
947 freePass(*I, Msg, DBG_STR);
950 void PMDataManager::freePass(Pass *P, StringRef Msg,
951 enum PassDebuggingString DBG_STR) {
952 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
955 // If the pass crashes releasing memory, remember this.
956 PassManagerPrettyStackEntry X(P);
957 TimeRegion PassTimer(getPassTimer(P));
962 AnalysisID PI = P->getPassID();
963 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
964 // Remove the pass itself (if it is not already removed).
965 AvailableAnalysis.erase(PI);
967 // Remove all interfaces this pass implements, for which it is also
968 // listed as the available implementation.
969 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
970 for (unsigned i = 0, e = II.size(); i != e; ++i) {
971 DenseMap<AnalysisID, Pass*>::iterator Pos =
972 AvailableAnalysis.find(II[i]->getTypeInfo());
973 if (Pos != AvailableAnalysis.end() && Pos->second == P)
974 AvailableAnalysis.erase(Pos);
979 /// Add pass P into the PassVector. Update
980 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
981 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
982 // This manager is going to manage pass P. Set up analysis resolver
984 AnalysisResolver *AR = new AnalysisResolver(*this);
987 // If a FunctionPass F is the last user of ModulePass info M
988 // then the F's manager, not F, records itself as a last user of M.
989 SmallVector<Pass *, 12> TransferLastUses;
991 if (!ProcessAnalysis) {
993 PassVector.push_back(P);
997 // At the moment, this pass is the last user of all required passes.
998 SmallVector<Pass *, 12> LastUses;
999 SmallVector<Pass *, 8> RequiredPasses;
1000 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1002 unsigned PDepth = this->getDepth();
1004 collectRequiredAnalysis(RequiredPasses,
1005 ReqAnalysisNotAvailable, P);
1006 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1007 E = RequiredPasses.end(); I != E; ++I) {
1008 Pass *PRequired = *I;
1009 unsigned RDepth = 0;
1011 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1012 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1013 RDepth = DM.getDepth();
1015 if (PDepth == RDepth)
1016 LastUses.push_back(PRequired);
1017 else if (PDepth > RDepth) {
1018 // Let the parent claim responsibility of last use
1019 TransferLastUses.push_back(PRequired);
1020 // Keep track of higher level analysis used by this manager.
1021 HigherLevelAnalysis.push_back(PRequired);
1023 llvm_unreachable("Unable to accommodate Required Pass");
1026 // Set P as P's last user until someone starts using P.
1027 // However, if P is a Pass Manager then it does not need
1028 // to record its last user.
1029 if (P->getAsPMDataManager() == 0)
1030 LastUses.push_back(P);
1031 TPM->setLastUser(LastUses, P);
1033 if (!TransferLastUses.empty()) {
1034 Pass *My_PM = getAsPass();
1035 TPM->setLastUser(TransferLastUses, My_PM);
1036 TransferLastUses.clear();
1039 // Now, take care of required analyses that are not available.
1040 for (SmallVectorImpl<AnalysisID>::iterator
1041 I = ReqAnalysisNotAvailable.begin(),
1042 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1043 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1044 Pass *AnalysisPass = PI->createPass();
1045 this->addLowerLevelRequiredPass(P, AnalysisPass);
1048 // Take a note of analysis required and made available by this pass.
1049 // Remove the analysis not preserved by this pass
1050 removeNotPreservedAnalysis(P);
1051 recordAvailableAnalysis(P);
1054 PassVector.push_back(P);
1058 /// Populate RP with analysis pass that are required by
1059 /// pass P and are available. Populate RP_NotAvail with analysis
1060 /// pass that are required by pass P but are not available.
1061 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1062 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1064 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1065 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1066 for (AnalysisUsage::VectorType::const_iterator
1067 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1068 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1069 RP.push_back(AnalysisPass);
1071 RP_NotAvail.push_back(*I);
1074 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1075 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1076 E = IDs.end(); I != E; ++I) {
1077 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1078 RP.push_back(AnalysisPass);
1080 RP_NotAvail.push_back(*I);
1084 // All Required analyses should be available to the pass as it runs! Here
1085 // we fill in the AnalysisImpls member of the pass so that it can
1086 // successfully use the getAnalysis() method to retrieve the
1087 // implementations it needs.
1089 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1090 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1092 for (AnalysisUsage::VectorType::const_iterator
1093 I = AnUsage->getRequiredSet().begin(),
1094 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1095 Pass *Impl = findAnalysisPass(*I, true);
1097 // This may be analysis pass that is initialized on the fly.
1098 // If that is not the case then it will raise an assert when it is used.
1100 AnalysisResolver *AR = P->getResolver();
1101 assert(AR && "Analysis Resolver is not set");
1102 AR->addAnalysisImplsPair(*I, Impl);
1106 /// Find the pass that implements Analysis AID. If desired pass is not found
1107 /// then return NULL.
1108 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1110 // Check if AvailableAnalysis map has one entry.
1111 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1113 if (I != AvailableAnalysis.end())
1116 // Search Parents through TopLevelManager
1118 return TPM->findAnalysisPass(AID);
1123 // Print list of passes that are last used by P.
1124 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1126 SmallVector<Pass *, 12> LUses;
1128 // If this is a on the fly manager then it does not have TPM.
1132 TPM->collectLastUses(LUses, P);
1134 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1135 E = LUses.end(); I != E; ++I) {
1136 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1137 (*I)->dumpPassStructure(0);
1141 void PMDataManager::dumpPassArguments() const {
1142 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1143 E = PassVector.end(); I != E; ++I) {
1144 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1145 PMD->dumpPassArguments();
1147 if (const PassInfo *PI =
1148 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1149 if (!PI->isAnalysisGroup())
1150 dbgs() << " -" << PI->getPassArgument();
1154 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1155 enum PassDebuggingString S2,
1157 if (PassDebugging < Executions)
1159 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1162 dbgs() << "Executing Pass '" << P->getPassName();
1164 case MODIFICATION_MSG:
1165 dbgs() << "Made Modification '" << P->getPassName();
1168 dbgs() << " Freeing Pass '" << P->getPassName();
1174 case ON_BASICBLOCK_MSG:
1175 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1177 case ON_FUNCTION_MSG:
1178 dbgs() << "' on Function '" << Msg << "'...\n";
1181 dbgs() << "' on Module '" << Msg << "'...\n";
1184 dbgs() << "' on Region '" << Msg << "'...\n";
1187 dbgs() << "' on Loop '" << Msg << "'...\n";
1190 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1197 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1198 if (PassDebugging < Details)
1201 AnalysisUsage analysisUsage;
1202 P->getAnalysisUsage(analysisUsage);
1203 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1206 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1207 if (PassDebugging < Details)
1210 AnalysisUsage analysisUsage;
1211 P->getAnalysisUsage(analysisUsage);
1212 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1215 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1216 const AnalysisUsage::VectorType &Set) const {
1217 assert(PassDebugging >= Details);
1220 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1221 for (unsigned i = 0; i != Set.size(); ++i) {
1222 if (i) dbgs() << ',';
1223 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1225 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1227 dbgs() << " Uninitialized Pass";
1230 dbgs() << ' ' << PInf->getPassName();
1235 /// Add RequiredPass into list of lower level passes required by pass P.
1236 /// RequiredPass is run on the fly by Pass Manager when P requests it
1237 /// through getAnalysis interface.
1238 /// This should be handled by specific pass manager.
1239 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1241 TPM->dumpArguments();
1245 // Module Level pass may required Function Level analysis info
1246 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1247 // to provide this on demand. In that case, in Pass manager terminology,
1248 // module level pass is requiring lower level analysis info managed by
1249 // lower level pass manager.
1251 // When Pass manager is not able to order required analysis info, Pass manager
1252 // checks whether any lower level manager will be able to provide this
1253 // analysis info on demand or not.
1255 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1256 dbgs() << "' required by '" << P->getPassName() << "'\n";
1258 llvm_unreachable("Unable to schedule pass");
1261 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1262 llvm_unreachable("Unable to find on the fly pass");
1266 PMDataManager::~PMDataManager() {
1267 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1268 E = PassVector.end(); I != E; ++I)
1272 //===----------------------------------------------------------------------===//
1273 // NOTE: Is this the right place to define this method ?
1274 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1275 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1276 return PM.findAnalysisPass(ID, dir);
1279 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1281 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1284 //===----------------------------------------------------------------------===//
1285 // BBPassManager implementation
1287 /// Execute all of the passes scheduled for execution by invoking
1288 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1289 /// the function, and if so, return true.
1290 bool BBPassManager::runOnFunction(Function &F) {
1291 if (F.isDeclaration())
1294 bool Changed = doInitialization(F);
1296 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1297 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1298 BasicBlockPass *BP = getContainedPass(Index);
1299 bool LocalChanged = false;
1301 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1302 dumpRequiredSet(BP);
1304 initializeAnalysisImpl(BP);
1307 // If the pass crashes, remember this.
1308 PassManagerPrettyStackEntry X(BP, *I);
1309 TimeRegion PassTimer(getPassTimer(BP));
1311 LocalChanged |= BP->runOnBasicBlock(*I);
1314 Changed |= LocalChanged;
1316 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1318 dumpPreservedSet(BP);
1320 verifyPreservedAnalysis(BP);
1321 removeNotPreservedAnalysis(BP);
1322 recordAvailableAnalysis(BP);
1323 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1326 return doFinalization(F) || Changed;
1329 // Implement doInitialization and doFinalization
1330 bool BBPassManager::doInitialization(Module &M) {
1331 bool Changed = false;
1333 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1334 Changed |= getContainedPass(Index)->doInitialization(M);
1339 bool BBPassManager::doFinalization(Module &M) {
1340 bool Changed = false;
1342 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1343 Changed |= getContainedPass(Index)->doFinalization(M);
1348 bool BBPassManager::doInitialization(Function &F) {
1349 bool Changed = false;
1351 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1352 BasicBlockPass *BP = getContainedPass(Index);
1353 Changed |= BP->doInitialization(F);
1359 bool BBPassManager::doFinalization(Function &F) {
1360 bool Changed = false;
1362 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1363 BasicBlockPass *BP = getContainedPass(Index);
1364 Changed |= BP->doFinalization(F);
1371 //===----------------------------------------------------------------------===//
1372 // FunctionPassManager implementation
1374 /// Create new Function pass manager
1375 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1376 FPM = new FunctionPassManagerImpl();
1377 // FPM is the top level manager.
1378 FPM->setTopLevelManager(FPM);
1380 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1381 FPM->setResolver(AR);
1384 FunctionPassManager::~FunctionPassManager() {
1388 /// add - Add a pass to the queue of passes to run. This passes
1389 /// ownership of the Pass to the PassManager. When the
1390 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1391 /// there is no need to delete the pass. (TODO delete passes.)
1392 /// This implies that all passes MUST be allocated with 'new'.
1393 void FunctionPassManager::add(Pass *P) {
1397 /// run - Execute all of the passes scheduled for execution. Keep
1398 /// track of whether any of the passes modifies the function, and if
1399 /// so, return true.
1401 bool FunctionPassManager::run(Function &F) {
1402 if (F.isMaterializable()) {
1404 if (F.Materialize(&errstr))
1405 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1411 /// doInitialization - Run all of the initializers for the function passes.
1413 bool FunctionPassManager::doInitialization() {
1414 return FPM->doInitialization(*M);
1417 /// doFinalization - Run all of the finalizers for the function passes.
1419 bool FunctionPassManager::doFinalization() {
1420 return FPM->doFinalization(*M);
1423 //===----------------------------------------------------------------------===//
1424 // FunctionPassManagerImpl implementation
1426 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1427 bool Changed = false;
1432 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1433 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1434 E = IPV.end(); I != E; ++I) {
1435 Changed |= (*I)->doInitialization(M);
1438 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1439 Changed |= getContainedManager(Index)->doInitialization(M);
1444 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1445 bool Changed = false;
1447 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1448 Changed |= getContainedManager(Index)->doFinalization(M);
1450 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1451 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1452 E = IPV.end(); I != E; ++I) {
1453 Changed |= (*I)->doFinalization(M);
1459 /// cleanup - After running all passes, clean up pass manager cache.
1460 void FPPassManager::cleanup() {
1461 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1462 FunctionPass *FP = getContainedPass(Index);
1463 AnalysisResolver *AR = FP->getResolver();
1464 assert(AR && "Analysis Resolver is not set");
1465 AR->clearAnalysisImpls();
1469 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1472 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1473 FPPassManager *FPPM = getContainedManager(Index);
1474 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1475 FPPM->getContainedPass(Index)->releaseMemory();
1481 // Execute all the passes managed by this top level manager.
1482 // Return true if any function is modified by a pass.
1483 bool FunctionPassManagerImpl::run(Function &F) {
1484 bool Changed = false;
1485 TimingInfo::createTheTimeInfo();
1487 initializeAllAnalysisInfo();
1488 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1489 Changed |= getContainedManager(Index)->runOnFunction(F);
1491 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1492 getContainedManager(Index)->cleanup();
1498 //===----------------------------------------------------------------------===//
1499 // FPPassManager implementation
1501 char FPPassManager::ID = 0;
1502 /// Print passes managed by this manager
1503 void FPPassManager::dumpPassStructure(unsigned Offset) {
1504 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1505 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1506 FunctionPass *FP = getContainedPass(Index);
1507 FP->dumpPassStructure(Offset + 1);
1508 dumpLastUses(FP, Offset+1);
1513 /// Execute all of the passes scheduled for execution by invoking
1514 /// runOnFunction method. Keep track of whether any of the passes modifies
1515 /// the function, and if so, return true.
1516 bool FPPassManager::runOnFunction(Function &F) {
1517 if (F.isDeclaration())
1520 bool Changed = false;
1522 // Collect inherited analysis from Module level pass manager.
1523 populateInheritedAnalysis(TPM->activeStack);
1525 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1526 FunctionPass *FP = getContainedPass(Index);
1527 bool LocalChanged = false;
1529 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1530 dumpRequiredSet(FP);
1532 initializeAnalysisImpl(FP);
1535 PassManagerPrettyStackEntry X(FP, F);
1536 TimeRegion PassTimer(getPassTimer(FP));
1538 LocalChanged |= FP->runOnFunction(F);
1541 Changed |= LocalChanged;
1543 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1544 dumpPreservedSet(FP);
1546 verifyPreservedAnalysis(FP);
1547 removeNotPreservedAnalysis(FP);
1548 recordAvailableAnalysis(FP);
1549 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1554 bool FPPassManager::runOnModule(Module &M) {
1555 bool Changed = false;
1557 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1558 Changed |= runOnFunction(*I);
1563 bool FPPassManager::doInitialization(Module &M) {
1564 bool Changed = false;
1566 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1567 Changed |= getContainedPass(Index)->doInitialization(M);
1572 bool FPPassManager::doFinalization(Module &M) {
1573 bool Changed = false;
1575 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1576 Changed |= getContainedPass(Index)->doFinalization(M);
1581 //===----------------------------------------------------------------------===//
1582 // MPPassManager implementation
1584 /// Execute all of the passes scheduled for execution by invoking
1585 /// runOnModule method. Keep track of whether any of the passes modifies
1586 /// the module, and if so, return true.
1588 MPPassManager::runOnModule(Module &M) {
1589 bool Changed = false;
1591 // Initialize on-the-fly passes
1592 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1593 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1595 FunctionPassManagerImpl *FPP = I->second;
1596 Changed |= FPP->doInitialization(M);
1599 // Initialize module passes
1600 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1601 Changed |= getContainedPass(Index)->doInitialization(M);
1603 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1604 ModulePass *MP = getContainedPass(Index);
1605 bool LocalChanged = false;
1607 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1608 dumpRequiredSet(MP);
1610 initializeAnalysisImpl(MP);
1613 PassManagerPrettyStackEntry X(MP, M);
1614 TimeRegion PassTimer(getPassTimer(MP));
1616 LocalChanged |= MP->runOnModule(M);
1619 Changed |= LocalChanged;
1621 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1622 M.getModuleIdentifier());
1623 dumpPreservedSet(MP);
1625 verifyPreservedAnalysis(MP);
1626 removeNotPreservedAnalysis(MP);
1627 recordAvailableAnalysis(MP);
1628 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1631 // Finalize module passes
1632 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1633 Changed |= getContainedPass(Index)->doFinalization(M);
1635 // Finalize on-the-fly passes
1636 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1637 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1639 FunctionPassManagerImpl *FPP = I->second;
1640 // We don't know when is the last time an on-the-fly pass is run,
1641 // so we need to releaseMemory / finalize here
1642 FPP->releaseMemoryOnTheFly();
1643 Changed |= FPP->doFinalization(M);
1649 /// Add RequiredPass into list of lower level passes required by pass P.
1650 /// RequiredPass is run on the fly by Pass Manager when P requests it
1651 /// through getAnalysis interface.
1652 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1653 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1654 "Unable to handle Pass that requires lower level Analysis pass");
1655 assert((P->getPotentialPassManagerType() <
1656 RequiredPass->getPotentialPassManagerType()) &&
1657 "Unable to handle Pass that requires lower level Analysis pass");
1659 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1661 FPP = new FunctionPassManagerImpl();
1662 // FPP is the top level manager.
1663 FPP->setTopLevelManager(FPP);
1665 OnTheFlyManagers[P] = FPP;
1667 FPP->add(RequiredPass);
1669 // Register P as the last user of RequiredPass.
1671 SmallVector<Pass *, 1> LU;
1672 LU.push_back(RequiredPass);
1673 FPP->setLastUser(LU, P);
1677 /// Return function pass corresponding to PassInfo PI, that is
1678 /// required by module pass MP. Instantiate analysis pass, by using
1679 /// its runOnFunction() for function F.
1680 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1681 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1682 assert(FPP && "Unable to find on the fly pass");
1684 FPP->releaseMemoryOnTheFly();
1686 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1690 //===----------------------------------------------------------------------===//
1691 // PassManagerImpl implementation
1694 /// run - Execute all of the passes scheduled for execution. Keep track of
1695 /// whether any of the passes modifies the module, and if so, return true.
1696 bool PassManagerImpl::run(Module &M) {
1697 bool Changed = false;
1698 TimingInfo::createTheTimeInfo();
1703 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1704 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1705 E = IPV.end(); I != E; ++I) {
1706 Changed |= (*I)->doInitialization(M);
1709 initializeAllAnalysisInfo();
1710 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1711 Changed |= getContainedManager(Index)->runOnModule(M);
1713 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1714 E = IPV.end(); I != E; ++I) {
1715 Changed |= (*I)->doFinalization(M);
1721 //===----------------------------------------------------------------------===//
1722 // PassManager implementation
1724 /// Create new pass manager
1725 PassManager::PassManager() {
1726 PM = new PassManagerImpl();
1727 // PM is the top level manager
1728 PM->setTopLevelManager(PM);
1731 PassManager::~PassManager() {
1735 /// add - Add a pass to the queue of passes to run. This passes ownership of
1736 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1737 /// will be destroyed as well, so there is no need to delete the pass. This
1738 /// implies that all passes MUST be allocated with 'new'.
1739 void PassManager::add(Pass *P) {
1743 /// run - Execute all of the passes scheduled for execution. Keep track of
1744 /// whether any of the passes modifies the module, and if so, return true.
1745 bool PassManager::run(Module &M) {
1749 //===----------------------------------------------------------------------===//
1750 // TimingInfo implementation
1752 bool llvm::TimePassesIsEnabled = false;
1753 static cl::opt<bool,true>
1754 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1755 cl::desc("Time each pass, printing elapsed time for each on exit"));
1757 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1758 // a non-null value (if the -time-passes option is enabled) or it leaves it
1759 // null. It may be called multiple times.
1760 void TimingInfo::createTheTimeInfo() {
1761 if (!TimePassesIsEnabled || TheTimeInfo) return;
1763 // Constructed the first time this is called, iff -time-passes is enabled.
1764 // This guarantees that the object will be constructed before static globals,
1765 // thus it will be destroyed before them.
1766 static ManagedStatic<TimingInfo> TTI;
1767 TheTimeInfo = &*TTI;
1770 /// If TimingInfo is enabled then start pass timer.
1771 Timer *llvm::getPassTimer(Pass *P) {
1773 return TheTimeInfo->getPassTimer(P);
1777 //===----------------------------------------------------------------------===//
1778 // PMStack implementation
1781 // Pop Pass Manager from the stack and clear its analysis info.
1782 void PMStack::pop() {
1784 PMDataManager *Top = this->top();
1785 Top->initializeAnalysisInfo();
1790 // Push PM on the stack and set its top level manager.
1791 void PMStack::push(PMDataManager *PM) {
1792 assert(PM && "Unable to push. Pass Manager expected");
1793 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1795 if (!this->empty()) {
1796 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1797 && "pushing bad pass manager to PMStack");
1798 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1800 assert(TPM && "Unable to find top level manager");
1801 TPM->addIndirectPassManager(PM);
1802 PM->setTopLevelManager(TPM);
1803 PM->setDepth(this->top()->getDepth()+1);
1805 assert((PM->getPassManagerType() == PMT_ModulePassManager
1806 || PM->getPassManagerType() == PMT_FunctionPassManager)
1807 && "pushing bad pass manager to PMStack");
1814 // Dump content of the pass manager stack.
1815 void PMStack::dump() const {
1816 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1817 E = S.end(); I != E; ++I)
1818 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1824 /// Find appropriate Module Pass Manager in the PM Stack and
1825 /// add self into that manager.
1826 void ModulePass::assignPassManager(PMStack &PMS,
1827 PassManagerType PreferredType) {
1828 // Find Module Pass Manager
1829 while (!PMS.empty()) {
1830 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1831 if (TopPMType == PreferredType)
1832 break; // We found desired pass manager
1833 else if (TopPMType > PMT_ModulePassManager)
1834 PMS.pop(); // Pop children pass managers
1838 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1839 PMS.top()->add(this);
1842 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1843 /// in the PM Stack and add self into that manager.
1844 void FunctionPass::assignPassManager(PMStack &PMS,
1845 PassManagerType PreferredType) {
1847 // Find Function Pass Manager
1848 while (!PMS.empty()) {
1849 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1855 // Create new Function Pass Manager if needed.
1857 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1858 FPP = (FPPassManager *)PMS.top();
1860 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1861 PMDataManager *PMD = PMS.top();
1863 // [1] Create new Function Pass Manager
1864 FPP = new FPPassManager();
1865 FPP->populateInheritedAnalysis(PMS);
1867 // [2] Set up new manager's top level manager
1868 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1869 TPM->addIndirectPassManager(FPP);
1871 // [3] Assign manager to manage this new manager. This may create
1872 // and push new managers into PMS
1873 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1875 // [4] Push new manager into PMS
1879 // Assign FPP as the manager of this pass.
1883 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1884 /// in the PM Stack and add self into that manager.
1885 void BasicBlockPass::assignPassManager(PMStack &PMS,
1886 PassManagerType PreferredType) {
1889 // Basic Pass Manager is a leaf pass manager. It does not handle
1890 // any other pass manager.
1892 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1893 BBP = (BBPassManager *)PMS.top();
1895 // If leaf manager is not Basic Block Pass manager then create new
1896 // basic Block Pass manager.
1897 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1898 PMDataManager *PMD = PMS.top();
1900 // [1] Create new Basic Block Manager
1901 BBP = new BBPassManager();
1903 // [2] Set up new manager's top level manager
1904 // Basic Block Pass Manager does not live by itself
1905 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1906 TPM->addIndirectPassManager(BBP);
1908 // [3] Assign manager to manage this new manager. This may create
1909 // and push new managers into PMS
1910 BBP->assignPassManager(PMS, PreferredType);
1912 // [4] Push new manager into PMS
1916 // Assign BBP as the manager of this pass.
1920 PassManagerBase::~PassManagerBase() {}