1 //===- PassManager.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 LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/PassManagers.h"
16 #include "llvm/Assembly/PrintModulePass.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.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"
32 // See PassManagers.h for Pass Manager infrastructure overview.
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information. Often it is useful to find out what pass is
38 // running when a crash occurs in a utility. When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
43 // Different debug levels that can be enabled...
45 None, 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(None , "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"),
59 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
62 // Print IR out before/after specified passes.
64 PrintBefore("print-before",
65 llvm::cl::desc("Print IR before specified passes"),
69 PrintAfter("print-after",
70 llvm::cl::desc("Print IR after specified passes"),
74 PrintBeforeAll("print-before-all",
75 llvm::cl::desc("Print IR before each pass"),
78 PrintAfterAll("print-after-all",
79 llvm::cl::desc("Print IR after each pass"),
82 /// This is a helper to determine whether to print IR before or
85 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
86 PassOptionList &PassesToPrint) {
87 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
88 const llvm::PassInfo *PassInf = PassesToPrint[i];
90 if (PassInf->getPassArgument() == PI->getPassArgument()) {
97 /// This is a utility to check whether a pass should have IR dumped
99 static bool ShouldPrintBeforePass(const PassInfo *PI) {
100 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
103 /// This is a utility to check whether a pass should have IR dumped
105 static bool ShouldPrintAfterPass(const PassInfo *PI) {
106 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
109 } // End of llvm namespace
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 {
121 if (V == 0 && M == 0)
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 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;
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;
281 //===----------------------------------------------------------------------===//
284 /// MPPassManager manages ModulePasses and function pass managers.
285 /// It batches all Module passes and function pass managers together and
286 /// sequences them to process one module.
287 class MPPassManager : public Pass, public PMDataManager {
290 explicit MPPassManager() :
291 Pass(PT_PassManager, ID), PMDataManager() { }
293 // Delete on the fly managers.
294 virtual ~MPPassManager() {
295 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
296 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
298 FunctionPassManagerImpl *FPP = I->second;
303 /// createPrinterPass - Get a module printer pass.
304 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
305 return createPrintModulePass(&O, false, Banner);
308 /// run - Execute all of the passes scheduled for execution. Keep track of
309 /// whether any of the passes modifies the module, and if so, return true.
310 bool runOnModule(Module &M);
312 using llvm::Pass::doInitialization;
313 using llvm::Pass::doFinalization;
315 /// doInitialization - Run all of the initializers for the module passes.
317 bool doInitialization();
319 /// doFinalization - Run all of the finalizers for the module passes.
321 bool doFinalization();
323 /// Pass Manager itself does not invalidate any analysis info.
324 void getAnalysisUsage(AnalysisUsage &Info) const {
325 Info.setPreservesAll();
328 /// Add RequiredPass into list of lower level passes required by pass P.
329 /// RequiredPass is run on the fly by Pass Manager when P requests it
330 /// through getAnalysis interface.
331 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
333 /// Return function pass corresponding to PassInfo PI, that is
334 /// required by module pass MP. Instantiate analysis pass, by using
335 /// its runOnFunction() for function F.
336 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
338 virtual const char *getPassName() const {
339 return "Module Pass Manager";
342 virtual PMDataManager *getAsPMDataManager() { return this; }
343 virtual Pass *getAsPass() { return this; }
345 // Print passes managed by this manager
346 void dumpPassStructure(unsigned Offset) {
347 llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
348 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
349 ModulePass *MP = getContainedPass(Index);
350 MP->dumpPassStructure(Offset + 1);
351 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
352 OnTheFlyManagers.find(MP);
353 if (I != OnTheFlyManagers.end())
354 I->second->dumpPassStructure(Offset + 2);
355 dumpLastUses(MP, Offset+1);
359 ModulePass *getContainedPass(unsigned N) {
360 assert(N < PassVector.size() && "Pass number out of range!");
361 return static_cast<ModulePass *>(PassVector[N]);
364 virtual PassManagerType getPassManagerType() const {
365 return PMT_ModulePassManager;
369 /// Collection of on the fly FPPassManagers. These managers manage
370 /// function passes that are required by module passes.
371 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
374 char MPPassManager::ID = 0;
375 //===----------------------------------------------------------------------===//
379 /// PassManagerImpl manages MPPassManagers
380 class PassManagerImpl : public Pass,
381 public PMDataManager,
382 public PMTopLevelManager {
383 virtual void anchor();
387 explicit PassManagerImpl() :
388 Pass(PT_PassManager, ID), PMDataManager(),
389 PMTopLevelManager(new MPPassManager()) {}
391 /// add - Add a pass to the queue of passes to run. This passes ownership of
392 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
393 /// will be destroyed as well, so there is no need to delete the pass. This
394 /// implies that all passes MUST be allocated with 'new'.
399 /// createPrinterPass - Get a module printer pass.
400 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
401 return createPrintModulePass(&O, false, Banner);
404 /// run - Execute all of the passes scheduled for execution. Keep track of
405 /// whether any of the passes modifies the module, and if so, return true.
408 using llvm::Pass::doInitialization;
409 using llvm::Pass::doFinalization;
411 /// doInitialization - Run all of the initializers for the module passes.
413 bool doInitialization();
415 /// doFinalization - Run all of the finalizers for the module passes.
417 bool doFinalization();
419 /// Pass Manager itself does not invalidate any analysis info.
420 void getAnalysisUsage(AnalysisUsage &Info) const {
421 Info.setPreservesAll();
424 virtual PMDataManager *getAsPMDataManager() { return this; }
425 virtual Pass *getAsPass() { return this; }
426 virtual PassManagerType getTopLevelPassManagerType() {
427 return PMT_ModulePassManager;
430 MPPassManager *getContainedManager(unsigned N) {
431 assert(N < PassManagers.size() && "Pass number out of range!");
432 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
437 void PassManagerImpl::anchor() {}
439 char PassManagerImpl::ID = 0;
440 } // End of llvm namespace
444 //===----------------------------------------------------------------------===//
445 /// TimingInfo Class - This class is used to calculate information about the
446 /// amount of time each pass takes to execute. This only happens when
447 /// -time-passes is enabled on the command line.
450 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
453 DenseMap<Pass*, Timer*> TimingData;
456 // Use 'create' member to get this.
457 TimingInfo() : TG("... Pass execution timing report ...") {}
459 // TimingDtor - Print out information about timing information
461 // Delete all of the timers, which accumulate their info into the
463 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
464 E = TimingData.end(); I != E; ++I)
466 // TimerGroup is deleted next, printing the report.
469 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
470 // to a non null value (if the -time-passes option is enabled) or it leaves it
471 // null. It may be called multiple times.
472 static void createTheTimeInfo();
474 /// getPassTimer - Return the timer for the specified pass if it exists.
475 Timer *getPassTimer(Pass *P) {
476 if (P->getAsPMDataManager())
479 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
480 Timer *&T = TimingData[P];
482 T = new Timer(P->getPassName(), TG);
487 } // End of anon namespace
489 static TimingInfo *TheTimeInfo;
491 //===----------------------------------------------------------------------===//
492 // PMTopLevelManager implementation
494 /// Initialize top level manager. Create first pass manager.
495 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
496 PMDM->setTopLevelManager(this);
497 addPassManager(PMDM);
498 activeStack.push(PMDM);
501 /// Set pass P as the last user of the given analysis passes.
503 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
505 if (P->getResolver())
506 PDepth = P->getResolver()->getPMDataManager().getDepth();
508 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
509 E = AnalysisPasses.end(); I != E; ++I) {
516 // Update the last users of passes that are required transitive by AP.
517 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
518 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
519 SmallVector<Pass *, 12> LastUses;
520 SmallVector<Pass *, 12> LastPMUses;
521 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
522 E = IDs.end(); I != E; ++I) {
523 Pass *AnalysisPass = findAnalysisPass(*I);
524 assert(AnalysisPass && "Expected analysis pass to exist.");
525 AnalysisResolver *AR = AnalysisPass->getResolver();
526 assert(AR && "Expected analysis resolver to exist.");
527 unsigned APDepth = AR->getPMDataManager().getDepth();
529 if (PDepth == APDepth)
530 LastUses.push_back(AnalysisPass);
531 else if (PDepth > APDepth)
532 LastPMUses.push_back(AnalysisPass);
535 setLastUser(LastUses, P);
537 // If this pass has a corresponding pass manager, push higher level
538 // analysis to this pass manager.
539 if (P->getResolver())
540 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
543 // If AP is the last user of other passes then make P last user of
545 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
546 LUE = LastUser.end(); LUI != LUE; ++LUI) {
547 if (LUI->second == AP)
548 // DenseMap iterator is not invalidated here because
549 // this is just updating existing entries.
550 LastUser[LUI->first] = P;
555 /// Collect passes whose last user is P
556 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
558 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
559 InversedLastUser.find(P);
560 if (DMI == InversedLastUser.end())
563 SmallPtrSet<Pass *, 8> &LU = DMI->second;
564 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
565 E = LU.end(); I != E; ++I) {
566 LastUses.push_back(*I);
571 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
572 AnalysisUsage *AnUsage = NULL;
573 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
574 if (DMI != AnUsageMap.end())
575 AnUsage = DMI->second;
577 AnUsage = new AnalysisUsage();
578 P->getAnalysisUsage(*AnUsage);
579 AnUsageMap[P] = AnUsage;
584 /// Schedule pass P for execution. Make sure that passes required by
585 /// P are run before P is run. Update analysis info maintained by
586 /// the manager. Remove dead passes. This is a recursive function.
587 void PMTopLevelManager::schedulePass(Pass *P) {
589 // TODO : Allocate function manager for this pass, other wise required set
590 // may be inserted into previous function manager
592 // Give pass a chance to prepare the stage.
593 P->preparePassManager(activeStack);
595 // If P is an analysis pass and it is available then do not
596 // generate the analysis again. Stale analysis info should not be
597 // available at this point.
599 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
600 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
605 AnalysisUsage *AnUsage = findAnalysisUsage(P);
607 bool checkAnalysis = true;
608 while (checkAnalysis) {
609 checkAnalysis = false;
611 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
612 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
613 E = RequiredSet.end(); I != E; ++I) {
615 Pass *AnalysisPass = findAnalysisPass(*I);
617 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
620 // Pass P is not in the global PassRegistry
621 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
622 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
623 dbgs() << "Required Passes:" << "\n";
624 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
625 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
626 Pass *AnalysisPass2 = findAnalysisPass(*I2);
628 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
631 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
632 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
633 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
638 assert(PI && "Expected required passes to be initialized");
639 AnalysisPass = PI->createPass();
640 if (P->getPotentialPassManagerType () ==
641 AnalysisPass->getPotentialPassManagerType())
642 // Schedule analysis pass that is managed by the same pass manager.
643 schedulePass(AnalysisPass);
644 else if (P->getPotentialPassManagerType () >
645 AnalysisPass->getPotentialPassManagerType()) {
646 // Schedule analysis pass that is managed by a new manager.
647 schedulePass(AnalysisPass);
648 // Recheck analysis passes to ensure that required analyses that
649 // are already checked are still available.
650 checkAnalysis = true;
653 // Do not schedule this analysis. Lower level analsyis
654 // passes are run on the fly.
660 // Now all required passes are available.
661 if (ImmutablePass *IP = P->getAsImmutablePass()) {
662 // P is a immutable pass and it will be managed by this
663 // top level manager. Set up analysis resolver to connect them.
664 PMDataManager *DM = getAsPMDataManager();
665 AnalysisResolver *AR = new AnalysisResolver(*DM);
667 DM->initializeAnalysisImpl(P);
668 addImmutablePass(IP);
669 DM->recordAvailableAnalysis(IP);
673 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
674 Pass *PP = P->createPrinterPass(
675 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
676 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
679 // Add the requested pass to the best available pass manager.
680 P->assignPassManager(activeStack, getTopLevelPassManagerType());
682 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
683 Pass *PP = P->createPrinterPass(
684 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
685 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
689 /// Find the pass that implements Analysis AID. Search immutable
690 /// passes and all pass managers. If desired pass is not found
691 /// then return NULL.
692 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
694 // Check pass managers
695 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
696 E = PassManagers.end(); I != E; ++I)
697 if (Pass *P = (*I)->findAnalysisPass(AID, false))
700 // Check other pass managers
701 for (SmallVectorImpl<PMDataManager *>::iterator
702 I = IndirectPassManagers.begin(),
703 E = IndirectPassManagers.end(); I != E; ++I)
704 if (Pass *P = (*I)->findAnalysisPass(AID, false))
707 // Check the immutable passes. Iterate in reverse order so that we find
708 // the most recently registered passes first.
709 for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
710 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
711 AnalysisID PI = (*I)->getPassID();
715 // If Pass not found then check the interfaces implemented by Immutable Pass
716 const PassInfo *PassInf =
717 PassRegistry::getPassRegistry()->getPassInfo(PI);
718 assert(PassInf && "Expected all immutable passes to be initialized");
719 const std::vector<const PassInfo*> &ImmPI =
720 PassInf->getInterfacesImplemented();
721 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
722 EE = ImmPI.end(); II != EE; ++II) {
723 if ((*II)->getTypeInfo() == AID)
731 // Print passes managed by this top level manager.
732 void PMTopLevelManager::dumpPasses() const {
734 if (PassDebugging < Structure)
737 // Print out the immutable passes
738 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
739 ImmutablePasses[i]->dumpPassStructure(0);
742 // Every class that derives from PMDataManager also derives from Pass
743 // (sometimes indirectly), but there's no inheritance relationship
744 // between PMDataManager and Pass, so we have to getAsPass to get
745 // from a PMDataManager* to a Pass*.
746 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
747 E = PassManagers.end(); I != E; ++I)
748 (*I)->getAsPass()->dumpPassStructure(1);
751 void PMTopLevelManager::dumpArguments() const {
753 if (PassDebugging < Arguments)
756 dbgs() << "Pass Arguments: ";
757 for (SmallVector<ImmutablePass *, 8>::const_iterator I =
758 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
759 if (const PassInfo *PI =
760 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
761 assert(PI && "Expected all immutable passes to be initialized");
762 if (!PI->isAnalysisGroup())
763 dbgs() << " -" << PI->getPassArgument();
765 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
766 E = PassManagers.end(); I != E; ++I)
767 (*I)->dumpPassArguments();
771 void PMTopLevelManager::initializeAllAnalysisInfo() {
772 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
773 E = PassManagers.end(); I != E; ++I)
774 (*I)->initializeAnalysisInfo();
776 // Initailize other pass managers
777 for (SmallVectorImpl<PMDataManager *>::iterator
778 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
780 (*I)->initializeAnalysisInfo();
782 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
783 DME = LastUser.end(); DMI != DME; ++DMI) {
784 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
785 InversedLastUser.find(DMI->second);
786 if (InvDMI != InversedLastUser.end()) {
787 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
788 L.insert(DMI->first);
790 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
791 InversedLastUser[DMI->second] = L;
797 PMTopLevelManager::~PMTopLevelManager() {
798 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
799 E = PassManagers.end(); I != E; ++I)
802 for (SmallVectorImpl<ImmutablePass *>::iterator
803 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
806 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
807 DME = AnUsageMap.end(); DMI != DME; ++DMI)
811 //===----------------------------------------------------------------------===//
812 // PMDataManager implementation
814 /// Augement AvailableAnalysis by adding analysis made available by pass P.
815 void PMDataManager::recordAvailableAnalysis(Pass *P) {
816 AnalysisID PI = P->getPassID();
818 AvailableAnalysis[PI] = P;
820 assert(!AvailableAnalysis.empty());
822 // This pass is the current implementation of all of the interfaces it
823 // implements as well.
824 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
825 if (PInf == 0) return;
826 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
827 for (unsigned i = 0, e = II.size(); i != e; ++i)
828 AvailableAnalysis[II[i]->getTypeInfo()] = P;
831 // Return true if P preserves high level analysis used by other
832 // passes managed by this manager
833 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
834 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
835 if (AnUsage->getPreservesAll())
838 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
839 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
840 E = HigherLevelAnalysis.end(); I != E; ++I) {
842 if (P1->getAsImmutablePass() == 0 &&
843 std::find(PreservedSet.begin(), PreservedSet.end(),
852 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
853 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
854 // Don't do this unless assertions are enabled.
858 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
859 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
861 // Verify preserved analysis
862 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
863 E = PreservedSet.end(); I != E; ++I) {
865 if (Pass *AP = findAnalysisPass(AID, true)) {
866 TimeRegion PassTimer(getPassTimer(AP));
867 AP->verifyAnalysis();
872 /// Remove Analysis not preserved by Pass P
873 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
874 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
875 if (AnUsage->getPreservesAll())
878 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
879 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
880 E = AvailableAnalysis.end(); I != E; ) {
881 std::map<AnalysisID, Pass*>::iterator Info = I++;
882 if (Info->second->getAsImmutablePass() == 0 &&
883 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
884 PreservedSet.end()) {
885 // Remove this analysis
886 if (PassDebugging >= Details) {
887 Pass *S = Info->second;
888 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
889 dbgs() << S->getPassName() << "'\n";
891 AvailableAnalysis.erase(Info);
895 // Check inherited analysis also. If P is not preserving analysis
896 // provided by parent manager then remove it here.
897 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
899 if (!InheritedAnalysis[Index])
902 for (std::map<AnalysisID, Pass*>::iterator
903 I = InheritedAnalysis[Index]->begin(),
904 E = InheritedAnalysis[Index]->end(); I != E; ) {
905 std::map<AnalysisID, Pass *>::iterator Info = I++;
906 if (Info->second->getAsImmutablePass() == 0 &&
907 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
908 PreservedSet.end()) {
909 // Remove this analysis
910 if (PassDebugging >= Details) {
911 Pass *S = Info->second;
912 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
913 dbgs() << S->getPassName() << "'\n";
915 InheritedAnalysis[Index]->erase(Info);
921 /// Remove analysis passes that are not used any longer
922 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
923 enum PassDebuggingString DBG_STR) {
925 SmallVector<Pass *, 12> DeadPasses;
927 // If this is a on the fly manager then it does not have TPM.
931 TPM->collectLastUses(DeadPasses, P);
933 if (PassDebugging >= Details && !DeadPasses.empty()) {
934 dbgs() << " -*- '" << P->getPassName();
935 dbgs() << "' is the last user of following pass instances.";
936 dbgs() << " Free these instances\n";
939 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
940 E = DeadPasses.end(); I != E; ++I)
941 freePass(*I, Msg, DBG_STR);
944 void PMDataManager::freePass(Pass *P, StringRef Msg,
945 enum PassDebuggingString DBG_STR) {
946 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
949 // If the pass crashes releasing memory, remember this.
950 PassManagerPrettyStackEntry X(P);
951 TimeRegion PassTimer(getPassTimer(P));
956 AnalysisID PI = P->getPassID();
957 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
958 // Remove the pass itself (if it is not already removed).
959 AvailableAnalysis.erase(PI);
961 // Remove all interfaces this pass implements, for which it is also
962 // listed as the available implementation.
963 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
964 for (unsigned i = 0, e = II.size(); i != e; ++i) {
965 std::map<AnalysisID, Pass*>::iterator Pos =
966 AvailableAnalysis.find(II[i]->getTypeInfo());
967 if (Pos != AvailableAnalysis.end() && Pos->second == P)
968 AvailableAnalysis.erase(Pos);
973 /// Add pass P into the PassVector. Update
974 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
975 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
976 // This manager is going to manage pass P. Set up analysis resolver
978 AnalysisResolver *AR = new AnalysisResolver(*this);
981 // If a FunctionPass F is the last user of ModulePass info M
982 // then the F's manager, not F, records itself as a last user of M.
983 SmallVector<Pass *, 12> TransferLastUses;
985 if (!ProcessAnalysis) {
987 PassVector.push_back(P);
991 // At the moment, this pass is the last user of all required passes.
992 SmallVector<Pass *, 12> LastUses;
993 SmallVector<Pass *, 8> RequiredPasses;
994 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
996 unsigned PDepth = this->getDepth();
998 collectRequiredAnalysis(RequiredPasses,
999 ReqAnalysisNotAvailable, P);
1000 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1001 E = RequiredPasses.end(); I != E; ++I) {
1002 Pass *PRequired = *I;
1003 unsigned RDepth = 0;
1005 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1006 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1007 RDepth = DM.getDepth();
1009 if (PDepth == RDepth)
1010 LastUses.push_back(PRequired);
1011 else if (PDepth > RDepth) {
1012 // Let the parent claim responsibility of last use
1013 TransferLastUses.push_back(PRequired);
1014 // Keep track of higher level analysis used by this manager.
1015 HigherLevelAnalysis.push_back(PRequired);
1017 llvm_unreachable("Unable to accommodate Required Pass");
1020 // Set P as P's last user until someone starts using P.
1021 // However, if P is a Pass Manager then it does not need
1022 // to record its last user.
1023 if (P->getAsPMDataManager() == 0)
1024 LastUses.push_back(P);
1025 TPM->setLastUser(LastUses, P);
1027 if (!TransferLastUses.empty()) {
1028 Pass *My_PM = getAsPass();
1029 TPM->setLastUser(TransferLastUses, My_PM);
1030 TransferLastUses.clear();
1033 // Now, take care of required analyses that are not available.
1034 for (SmallVectorImpl<AnalysisID>::iterator
1035 I = ReqAnalysisNotAvailable.begin(),
1036 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1037 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1038 Pass *AnalysisPass = PI->createPass();
1039 this->addLowerLevelRequiredPass(P, AnalysisPass);
1042 // Take a note of analysis required and made available by this pass.
1043 // Remove the analysis not preserved by this pass
1044 removeNotPreservedAnalysis(P);
1045 recordAvailableAnalysis(P);
1048 PassVector.push_back(P);
1052 /// Populate RP with analysis pass that are required by
1053 /// pass P and are available. Populate RP_NotAvail with analysis
1054 /// pass that are required by pass P but are not available.
1055 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1056 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1058 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1059 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1060 for (AnalysisUsage::VectorType::const_iterator
1061 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1062 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1063 RP.push_back(AnalysisPass);
1065 RP_NotAvail.push_back(*I);
1068 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1069 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1070 E = IDs.end(); I != E; ++I) {
1071 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1072 RP.push_back(AnalysisPass);
1074 RP_NotAvail.push_back(*I);
1078 // All Required analyses should be available to the pass as it runs! Here
1079 // we fill in the AnalysisImpls member of the pass so that it can
1080 // successfully use the getAnalysis() method to retrieve the
1081 // implementations it needs.
1083 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1084 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1086 for (AnalysisUsage::VectorType::const_iterator
1087 I = AnUsage->getRequiredSet().begin(),
1088 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1089 Pass *Impl = findAnalysisPass(*I, true);
1091 // This may be analysis pass that is initialized on the fly.
1092 // If that is not the case then it will raise an assert when it is used.
1094 AnalysisResolver *AR = P->getResolver();
1095 assert(AR && "Analysis Resolver is not set");
1096 AR->addAnalysisImplsPair(*I, Impl);
1100 /// Find the pass that implements Analysis AID. If desired pass is not found
1101 /// then return NULL.
1102 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1104 // Check if AvailableAnalysis map has one entry.
1105 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1107 if (I != AvailableAnalysis.end())
1110 // Search Parents through TopLevelManager
1112 return TPM->findAnalysisPass(AID);
1117 // Print list of passes that are last used by P.
1118 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1120 SmallVector<Pass *, 12> LUses;
1122 // If this is a on the fly manager then it does not have TPM.
1126 TPM->collectLastUses(LUses, P);
1128 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1129 E = LUses.end(); I != E; ++I) {
1130 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1131 (*I)->dumpPassStructure(0);
1135 void PMDataManager::dumpPassArguments() const {
1136 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1137 E = PassVector.end(); I != E; ++I) {
1138 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1139 PMD->dumpPassArguments();
1141 if (const PassInfo *PI =
1142 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1143 if (!PI->isAnalysisGroup())
1144 dbgs() << " -" << PI->getPassArgument();
1148 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1149 enum PassDebuggingString S2,
1151 if (PassDebugging < Executions)
1153 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1156 dbgs() << "Executing Pass '" << P->getPassName();
1158 case MODIFICATION_MSG:
1159 dbgs() << "Made Modification '" << P->getPassName();
1162 dbgs() << " Freeing Pass '" << P->getPassName();
1168 case ON_BASICBLOCK_MSG:
1169 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1171 case ON_FUNCTION_MSG:
1172 dbgs() << "' on Function '" << Msg << "'...\n";
1175 dbgs() << "' on Module '" << Msg << "'...\n";
1178 dbgs() << "' on Region '" << Msg << "'...\n";
1181 dbgs() << "' on Loop '" << Msg << "'...\n";
1184 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1191 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1192 if (PassDebugging < Details)
1195 AnalysisUsage analysisUsage;
1196 P->getAnalysisUsage(analysisUsage);
1197 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1200 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1201 if (PassDebugging < Details)
1204 AnalysisUsage analysisUsage;
1205 P->getAnalysisUsage(analysisUsage);
1206 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1209 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1210 const AnalysisUsage::VectorType &Set) const {
1211 assert(PassDebugging >= Details);
1214 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1215 for (unsigned i = 0; i != Set.size(); ++i) {
1216 if (i) dbgs() << ',';
1217 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1219 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1221 dbgs() << " Uninitialized Pass";
1224 dbgs() << ' ' << PInf->getPassName();
1229 /// Add RequiredPass into list of lower level passes required by pass P.
1230 /// RequiredPass is run on the fly by Pass Manager when P requests it
1231 /// through getAnalysis interface.
1232 /// This should be handled by specific pass manager.
1233 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1235 TPM->dumpArguments();
1239 // Module Level pass may required Function Level analysis info
1240 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1241 // to provide this on demand. In that case, in Pass manager terminology,
1242 // module level pass is requiring lower level analysis info managed by
1243 // lower level pass manager.
1245 // When Pass manager is not able to order required analysis info, Pass manager
1246 // checks whether any lower level manager will be able to provide this
1247 // analysis info on demand or not.
1249 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1250 dbgs() << "' required by '" << P->getPassName() << "'\n";
1252 llvm_unreachable("Unable to schedule pass");
1255 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1256 llvm_unreachable("Unable to find on the fly pass");
1260 PMDataManager::~PMDataManager() {
1261 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1262 E = PassVector.end(); I != E; ++I)
1266 //===----------------------------------------------------------------------===//
1267 // NOTE: Is this the right place to define this method ?
1268 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1269 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1270 return PM.findAnalysisPass(ID, dir);
1273 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1275 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1278 //===----------------------------------------------------------------------===//
1279 // BBPassManager implementation
1281 /// Execute all of the passes scheduled for execution by invoking
1282 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1283 /// the function, and if so, return true.
1284 bool BBPassManager::runOnFunction(Function &F) {
1285 if (F.isDeclaration())
1288 bool Changed = doInitialization(F);
1290 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1291 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1292 BasicBlockPass *BP = getContainedPass(Index);
1293 bool LocalChanged = false;
1295 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1296 dumpRequiredSet(BP);
1298 initializeAnalysisImpl(BP);
1301 // If the pass crashes, remember this.
1302 PassManagerPrettyStackEntry X(BP, *I);
1303 TimeRegion PassTimer(getPassTimer(BP));
1305 LocalChanged |= BP->runOnBasicBlock(*I);
1308 Changed |= LocalChanged;
1310 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1312 dumpPreservedSet(BP);
1314 verifyPreservedAnalysis(BP);
1315 removeNotPreservedAnalysis(BP);
1316 recordAvailableAnalysis(BP);
1317 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1320 return doFinalization(F) || Changed;
1323 // Implement doInitialization and doFinalization
1324 bool BBPassManager::doInitialization(Module &M) {
1325 bool Changed = false;
1327 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1328 Changed |= getContainedPass(Index)->doInitialization(M);
1333 bool BBPassManager::doFinalization(Module &M) {
1334 bool Changed = false;
1336 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1337 Changed |= getContainedPass(Index)->doFinalization(M);
1342 bool BBPassManager::doInitialization(Function &F) {
1343 bool Changed = false;
1345 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1346 BasicBlockPass *BP = getContainedPass(Index);
1347 Changed |= BP->doInitialization(F);
1353 bool BBPassManager::doFinalization(Function &F) {
1354 bool Changed = false;
1356 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1357 BasicBlockPass *BP = getContainedPass(Index);
1358 Changed |= BP->doFinalization(F);
1365 //===----------------------------------------------------------------------===//
1366 // FunctionPassManager implementation
1368 /// Create new Function pass manager
1369 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1370 FPM = new FunctionPassManagerImpl();
1371 // FPM is the top level manager.
1372 FPM->setTopLevelManager(FPM);
1374 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1375 FPM->setResolver(AR);
1378 FunctionPassManager::~FunctionPassManager() {
1382 /// add - Add a pass to the queue of passes to run. This passes
1383 /// ownership of the Pass to the PassManager. When the
1384 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1385 /// there is no need to delete the pass. (TODO delete passes.)
1386 /// This implies that all passes MUST be allocated with 'new'.
1387 void FunctionPassManager::add(Pass *P) {
1391 /// run - Execute all of the passes scheduled for execution. Keep
1392 /// track of whether any of the passes modifies the function, and if
1393 /// so, return true.
1395 bool FunctionPassManager::run(Function &F) {
1396 if (F.isMaterializable()) {
1398 if (F.Materialize(&errstr))
1399 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1405 /// doInitialization - Run all of the initializers for the function passes.
1407 bool FunctionPassManager::doInitialization() {
1408 return FPM->doInitialization(*M);
1411 /// doFinalization - Run all of the finalizers for the function passes.
1413 bool FunctionPassManager::doFinalization() {
1414 return FPM->doFinalization(*M);
1417 //===----------------------------------------------------------------------===//
1418 // FunctionPassManagerImpl implementation
1420 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1421 bool Changed = false;
1426 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1427 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1428 E = IPV.end(); I != E; ++I) {
1429 Changed |= (*I)->doInitialization(M);
1432 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1433 Changed |= getContainedManager(Index)->doInitialization(M);
1438 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1439 bool Changed = false;
1441 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1442 Changed |= getContainedManager(Index)->doFinalization(M);
1444 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1445 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1446 E = IPV.end(); I != E; ++I) {
1447 Changed |= (*I)->doFinalization(M);
1453 /// cleanup - After running all passes, clean up pass manager cache.
1454 void FPPassManager::cleanup() {
1455 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1456 FunctionPass *FP = getContainedPass(Index);
1457 AnalysisResolver *AR = FP->getResolver();
1458 assert(AR && "Analysis Resolver is not set");
1459 AR->clearAnalysisImpls();
1463 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1466 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1467 FPPassManager *FPPM = getContainedManager(Index);
1468 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1469 FPPM->getContainedPass(Index)->releaseMemory();
1475 // Execute all the passes managed by this top level manager.
1476 // Return true if any function is modified by a pass.
1477 bool FunctionPassManagerImpl::run(Function &F) {
1478 bool Changed = false;
1479 TimingInfo::createTheTimeInfo();
1481 initializeAllAnalysisInfo();
1482 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1483 Changed |= getContainedManager(Index)->runOnFunction(F);
1485 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1486 getContainedManager(Index)->cleanup();
1492 //===----------------------------------------------------------------------===//
1493 // FPPassManager implementation
1495 char FPPassManager::ID = 0;
1496 /// Print passes managed by this manager
1497 void FPPassManager::dumpPassStructure(unsigned Offset) {
1498 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1499 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1500 FunctionPass *FP = getContainedPass(Index);
1501 FP->dumpPassStructure(Offset + 1);
1502 dumpLastUses(FP, Offset+1);
1507 /// Execute all of the passes scheduled for execution by invoking
1508 /// runOnFunction method. Keep track of whether any of the passes modifies
1509 /// the function, and if so, return true.
1510 bool FPPassManager::runOnFunction(Function &F) {
1511 if (F.isDeclaration())
1514 bool Changed = false;
1516 // Collect inherited analysis from Module level pass manager.
1517 populateInheritedAnalysis(TPM->activeStack);
1519 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1520 FunctionPass *FP = getContainedPass(Index);
1521 bool LocalChanged = false;
1523 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1524 dumpRequiredSet(FP);
1526 initializeAnalysisImpl(FP);
1529 PassManagerPrettyStackEntry X(FP, F);
1530 TimeRegion PassTimer(getPassTimer(FP));
1532 LocalChanged |= FP->runOnFunction(F);
1535 Changed |= LocalChanged;
1537 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1538 dumpPreservedSet(FP);
1540 verifyPreservedAnalysis(FP);
1541 removeNotPreservedAnalysis(FP);
1542 recordAvailableAnalysis(FP);
1543 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1548 bool FPPassManager::runOnModule(Module &M) {
1549 bool Changed = false;
1551 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1552 Changed |= runOnFunction(*I);
1557 bool FPPassManager::doInitialization(Module &M) {
1558 bool Changed = false;
1560 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1561 Changed |= getContainedPass(Index)->doInitialization(M);
1566 bool FPPassManager::doFinalization(Module &M) {
1567 bool Changed = false;
1569 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1570 Changed |= getContainedPass(Index)->doFinalization(M);
1575 //===----------------------------------------------------------------------===//
1576 // MPPassManager implementation
1578 /// Execute all of the passes scheduled for execution by invoking
1579 /// runOnModule method. Keep track of whether any of the passes modifies
1580 /// the module, and if so, return true.
1582 MPPassManager::runOnModule(Module &M) {
1583 bool Changed = false;
1585 // Initialize on-the-fly passes
1586 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1587 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1589 FunctionPassManagerImpl *FPP = I->second;
1590 Changed |= FPP->doInitialization(M);
1593 // Initialize module passes
1594 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1595 Changed |= getContainedPass(Index)->doInitialization(M);
1597 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1598 ModulePass *MP = getContainedPass(Index);
1599 bool LocalChanged = false;
1601 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1602 dumpRequiredSet(MP);
1604 initializeAnalysisImpl(MP);
1607 PassManagerPrettyStackEntry X(MP, M);
1608 TimeRegion PassTimer(getPassTimer(MP));
1610 LocalChanged |= MP->runOnModule(M);
1613 Changed |= LocalChanged;
1615 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1616 M.getModuleIdentifier());
1617 dumpPreservedSet(MP);
1619 verifyPreservedAnalysis(MP);
1620 removeNotPreservedAnalysis(MP);
1621 recordAvailableAnalysis(MP);
1622 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1625 // Finalize module passes
1626 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1627 Changed |= getContainedPass(Index)->doFinalization(M);
1629 // Finalize on-the-fly passes
1630 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1631 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1633 FunctionPassManagerImpl *FPP = I->second;
1634 // We don't know when is the last time an on-the-fly pass is run,
1635 // so we need to releaseMemory / finalize here
1636 FPP->releaseMemoryOnTheFly();
1637 Changed |= FPP->doFinalization(M);
1643 /// Add RequiredPass into list of lower level passes required by pass P.
1644 /// RequiredPass is run on the fly by Pass Manager when P requests it
1645 /// through getAnalysis interface.
1646 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1647 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1648 "Unable to handle Pass that requires lower level Analysis pass");
1649 assert((P->getPotentialPassManagerType() <
1650 RequiredPass->getPotentialPassManagerType()) &&
1651 "Unable to handle Pass that requires lower level Analysis pass");
1653 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1655 FPP = new FunctionPassManagerImpl();
1656 // FPP is the top level manager.
1657 FPP->setTopLevelManager(FPP);
1659 OnTheFlyManagers[P] = FPP;
1661 FPP->add(RequiredPass);
1663 // Register P as the last user of RequiredPass.
1665 SmallVector<Pass *, 1> LU;
1666 LU.push_back(RequiredPass);
1667 FPP->setLastUser(LU, P);
1671 /// Return function pass corresponding to PassInfo PI, that is
1672 /// required by module pass MP. Instantiate analysis pass, by using
1673 /// its runOnFunction() for function F.
1674 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1675 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1676 assert(FPP && "Unable to find on the fly pass");
1678 FPP->releaseMemoryOnTheFly();
1680 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1684 //===----------------------------------------------------------------------===//
1685 // PassManagerImpl implementation
1688 /// run - Execute all of the passes scheduled for execution. Keep track of
1689 /// whether any of the passes modifies the module, and if so, return true.
1690 bool PassManagerImpl::run(Module &M) {
1691 bool Changed = false;
1692 TimingInfo::createTheTimeInfo();
1697 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1698 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1699 E = IPV.end(); I != E; ++I) {
1700 Changed |= (*I)->doInitialization(M);
1703 initializeAllAnalysisInfo();
1704 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1705 Changed |= getContainedManager(Index)->runOnModule(M);
1707 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1708 E = IPV.end(); I != E; ++I) {
1709 Changed |= (*I)->doFinalization(M);
1715 //===----------------------------------------------------------------------===//
1716 // PassManager implementation
1718 /// Create new pass manager
1719 PassManager::PassManager() {
1720 PM = new PassManagerImpl();
1721 // PM is the top level manager
1722 PM->setTopLevelManager(PM);
1725 PassManager::~PassManager() {
1729 /// add - Add a pass to the queue of passes to run. This passes ownership of
1730 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1731 /// will be destroyed as well, so there is no need to delete the pass. This
1732 /// implies that all passes MUST be allocated with 'new'.
1733 void PassManager::add(Pass *P) {
1737 /// run - Execute all of the passes scheduled for execution. Keep track of
1738 /// whether any of the passes modifies the module, and if so, return true.
1739 bool PassManager::run(Module &M) {
1743 //===----------------------------------------------------------------------===//
1744 // TimingInfo Class - This class is used to calculate information about the
1745 // amount of time each pass takes to execute. This only happens with
1746 // -time-passes is enabled on the command line.
1748 bool llvm::TimePassesIsEnabled = false;
1749 static cl::opt<bool,true>
1750 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1751 cl::desc("Time each pass, printing elapsed time for each on exit"));
1753 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1754 // a non null value (if the -time-passes option is enabled) or it leaves it
1755 // null. It may be called multiple times.
1756 void TimingInfo::createTheTimeInfo() {
1757 if (!TimePassesIsEnabled || TheTimeInfo) return;
1759 // Constructed the first time this is called, iff -time-passes is enabled.
1760 // This guarantees that the object will be constructed before static globals,
1761 // thus it will be destroyed before them.
1762 static ManagedStatic<TimingInfo> TTI;
1763 TheTimeInfo = &*TTI;
1766 /// If TimingInfo is enabled then start pass timer.
1767 Timer *llvm::getPassTimer(Pass *P) {
1769 return TheTimeInfo->getPassTimer(P);
1773 //===----------------------------------------------------------------------===//
1774 // PMStack implementation
1777 // Pop Pass Manager from the stack and clear its analysis info.
1778 void PMStack::pop() {
1780 PMDataManager *Top = this->top();
1781 Top->initializeAnalysisInfo();
1786 // Push PM on the stack and set its top level manager.
1787 void PMStack::push(PMDataManager *PM) {
1788 assert(PM && "Unable to push. Pass Manager expected");
1789 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1791 if (!this->empty()) {
1792 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1793 && "pushing bad pass manager to PMStack");
1794 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1796 assert(TPM && "Unable to find top level manager");
1797 TPM->addIndirectPassManager(PM);
1798 PM->setTopLevelManager(TPM);
1799 PM->setDepth(this->top()->getDepth()+1);
1802 assert((PM->getPassManagerType() == PMT_ModulePassManager
1803 || PM->getPassManagerType() == PMT_FunctionPassManager)
1804 && "pushing bad pass manager to PMStack");
1811 // Dump content of the pass manager stack.
1812 void PMStack::dump() const {
1813 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1814 E = S.end(); I != E; ++I)
1815 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1821 /// Find appropriate Module Pass Manager in the PM Stack and
1822 /// add self into that manager.
1823 void ModulePass::assignPassManager(PMStack &PMS,
1824 PassManagerType PreferredType) {
1825 // Find Module Pass Manager
1826 while (!PMS.empty()) {
1827 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1828 if (TopPMType == PreferredType)
1829 break; // We found desired pass manager
1830 else if (TopPMType > PMT_ModulePassManager)
1831 PMS.pop(); // Pop children pass managers
1835 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1836 PMS.top()->add(this);
1839 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1840 /// in the PM Stack and add self into that manager.
1841 void FunctionPass::assignPassManager(PMStack &PMS,
1842 PassManagerType PreferredType) {
1844 // Find Function Pass Manager
1845 while (!PMS.empty()) {
1846 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1852 // Create new Function Pass Manager if needed.
1854 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1855 FPP = (FPPassManager *)PMS.top();
1857 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1858 PMDataManager *PMD = PMS.top();
1860 // [1] Create new Function Pass Manager
1861 FPP = new FPPassManager();
1862 FPP->populateInheritedAnalysis(PMS);
1864 // [2] Set up new manager's top level manager
1865 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1866 TPM->addIndirectPassManager(FPP);
1868 // [3] Assign manager to manage this new manager. This may create
1869 // and push new managers into PMS
1870 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1872 // [4] Push new manager into PMS
1876 // Assign FPP as the manager of this pass.
1880 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1881 /// in the PM Stack and add self into that manager.
1882 void BasicBlockPass::assignPassManager(PMStack &PMS,
1883 PassManagerType PreferredType) {
1886 // Basic Pass Manager is a leaf pass manager. It does not handle
1887 // any other pass manager.
1889 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1890 BBP = (BBPassManager *)PMS.top();
1892 // If leaf manager is not Basic Block Pass manager then create new
1893 // basic Block Pass manager.
1894 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1895 PMDataManager *PMD = PMS.top();
1897 // [1] Create new Basic Block Manager
1898 BBP = new BBPassManager();
1900 // [2] Set up new manager's top level manager
1901 // Basic Block Pass Manager does not live by itself
1902 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1903 TPM->addIndirectPassManager(BBP);
1905 // [3] Assign manager to manage this new manager. This may create
1906 // and push new managers into PMS
1907 BBP->assignPassManager(PMS, PreferredType);
1909 // [4] Push new manager into PMS
1913 // Assign BBP as the manager of this pass.
1917 PassManagerBase::~PassManagerBase() {}