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/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/System/Mutex.h"
24 #include "llvm/System/Threading.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm-c/Core.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 // Always verify dominfo if expensive checking is enabled.
50 bool VerifyDomInfo = true;
52 bool VerifyDomInfo = false;
54 static cl::opt<bool,true>
55 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
56 cl::desc("Verify dominator info (time consuming)"));
58 static cl::opt<enum PassDebugLevel>
59 PassDebugging("debug-pass", cl::Hidden,
60 cl::desc("Print PassManager debugging information"),
62 clEnumVal(None , "disable debug output"),
63 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
64 clEnumVal(Structure , "print pass structure before run()"),
65 clEnumVal(Executions, "print pass name before it is executed"),
66 clEnumVal(Details , "print pass details when it is executed"),
68 } // End of llvm namespace
70 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
72 OS << "Releasing pass '";
74 OS << "Running pass '";
76 OS << P->getPassName() << "'";
79 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
90 else if (isa<BasicBlock>(V))
96 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
103 //===----------------------------------------------------------------------===//
106 /// BBPassManager manages BasicBlockPass. It batches all the
107 /// pass together and sequence them to process one basic block before
108 /// processing next basic block.
109 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
110 public FunctionPass {
114 explicit BBPassManager(int Depth)
115 : PMDataManager(Depth), FunctionPass(&ID) {}
117 /// Execute all of the passes scheduled for execution. Keep track of
118 /// whether any of the passes modifies the function, and if so, return true.
119 bool runOnFunction(Function &F);
121 /// Pass Manager itself does not invalidate any analysis info.
122 void getAnalysisUsage(AnalysisUsage &Info) const {
123 Info.setPreservesAll();
126 bool doInitialization(Module &M);
127 bool doInitialization(Function &F);
128 bool doFinalization(Module &M);
129 bool doFinalization(Function &F);
131 virtual const char *getPassName() const {
132 return "BasicBlock Pass Manager";
135 // Print passes managed by this manager
136 void dumpPassStructure(unsigned Offset) {
137 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
138 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
139 BasicBlockPass *BP = getContainedPass(Index);
140 BP->dumpPassStructure(Offset + 1);
141 dumpLastUses(BP, Offset+1);
145 BasicBlockPass *getContainedPass(unsigned N) {
146 assert(N < PassVector.size() && "Pass number out of range!");
147 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
151 virtual PassManagerType getPassManagerType() const {
152 return PMT_BasicBlockPassManager;
156 char BBPassManager::ID = 0;
161 //===----------------------------------------------------------------------===//
162 // FunctionPassManagerImpl
164 /// FunctionPassManagerImpl manages FPPassManagers
165 class FunctionPassManagerImpl : public Pass,
166 public PMDataManager,
167 public PMTopLevelManager {
172 explicit FunctionPassManagerImpl(int Depth) :
173 Pass(&ID), PMDataManager(Depth),
174 PMTopLevelManager(TLM_Function), wasRun(false) { }
176 /// add - Add a pass to the queue of passes to run. This passes ownership of
177 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
178 /// will be destroyed as well, so there is no need to delete the pass. This
179 /// implies that all passes MUST be allocated with 'new'.
184 // Prepare for running an on the fly pass, freeing memory if needed
185 // from a previous run.
186 void releaseMemoryOnTheFly();
188 /// run - Execute all of the passes scheduled for execution. Keep track of
189 /// whether any of the passes modifies the module, and if so, return true.
190 bool run(Function &F);
192 /// doInitialization - Run all of the initializers for the function passes.
194 bool doInitialization(Module &M);
196 /// doFinalization - Run all of the finalizers for the function passes.
198 bool doFinalization(Module &M);
200 /// Pass Manager itself does not invalidate any analysis info.
201 void getAnalysisUsage(AnalysisUsage &Info) const {
202 Info.setPreservesAll();
205 inline void addTopLevelPass(Pass *P) {
207 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
209 // P is a immutable pass and it will be managed by this
210 // top level manager. Set up analysis resolver to connect them.
211 AnalysisResolver *AR = new AnalysisResolver(*this);
213 initializeAnalysisImpl(P);
214 addImmutablePass(IP);
215 recordAvailableAnalysis(IP);
217 P->assignPassManager(activeStack);
222 FPPassManager *getContainedManager(unsigned N) {
223 assert(N < PassManagers.size() && "Pass number out of range!");
224 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
229 char FunctionPassManagerImpl::ID = 0;
230 //===----------------------------------------------------------------------===//
233 /// MPPassManager manages ModulePasses and function pass managers.
234 /// It batches all Module passes and function pass managers together and
235 /// sequences them to process one module.
236 class MPPassManager : public Pass, public PMDataManager {
239 explicit MPPassManager(int Depth) :
240 Pass(&ID), PMDataManager(Depth) { }
242 // Delete on the fly managers.
243 virtual ~MPPassManager() {
244 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
245 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
247 FunctionPassManagerImpl *FPP = I->second;
252 /// run - Execute all of the passes scheduled for execution. Keep track of
253 /// whether any of the passes modifies the module, and if so, return true.
254 bool runOnModule(Module &M);
256 /// Pass Manager itself does not invalidate any analysis info.
257 void getAnalysisUsage(AnalysisUsage &Info) const {
258 Info.setPreservesAll();
261 /// Add RequiredPass into list of lower level passes required by pass P.
262 /// RequiredPass is run on the fly by Pass Manager when P requests it
263 /// through getAnalysis interface.
264 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
266 /// Return function pass corresponding to PassInfo PI, that is
267 /// required by module pass MP. Instantiate analysis pass, by using
268 /// its runOnFunction() for function F.
269 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
271 virtual const char *getPassName() const {
272 return "Module Pass Manager";
275 // Print passes managed by this manager
276 void dumpPassStructure(unsigned Offset) {
277 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
278 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
279 ModulePass *MP = getContainedPass(Index);
280 MP->dumpPassStructure(Offset + 1);
281 if (FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP])
282 FPP->dumpPassStructure(Offset + 2);
283 dumpLastUses(MP, Offset+1);
287 ModulePass *getContainedPass(unsigned N) {
288 assert(N < PassVector.size() && "Pass number out of range!");
289 return static_cast<ModulePass *>(PassVector[N]);
292 virtual PassManagerType getPassManagerType() const {
293 return PMT_ModulePassManager;
297 /// Collection of on the fly FPPassManagers. These managers manage
298 /// function passes that are required by module passes.
299 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
302 char MPPassManager::ID = 0;
303 //===----------------------------------------------------------------------===//
307 /// PassManagerImpl manages MPPassManagers
308 class PassManagerImpl : public Pass,
309 public PMDataManager,
310 public PMTopLevelManager {
314 explicit PassManagerImpl(int Depth) :
315 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
317 /// add - Add a pass to the queue of passes to run. This passes ownership of
318 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
319 /// will be destroyed as well, so there is no need to delete the pass. This
320 /// implies that all passes MUST be allocated with 'new'.
325 /// run - Execute all of the passes scheduled for execution. Keep track of
326 /// whether any of the passes modifies the module, and if so, return true.
329 /// Pass Manager itself does not invalidate any analysis info.
330 void getAnalysisUsage(AnalysisUsage &Info) const {
331 Info.setPreservesAll();
334 inline void addTopLevelPass(Pass *P) {
335 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
337 // P is a immutable pass and it will be managed by this
338 // top level manager. Set up analysis resolver to connect them.
339 AnalysisResolver *AR = new AnalysisResolver(*this);
341 initializeAnalysisImpl(P);
342 addImmutablePass(IP);
343 recordAvailableAnalysis(IP);
345 P->assignPassManager(activeStack);
349 MPPassManager *getContainedManager(unsigned N) {
350 assert(N < PassManagers.size() && "Pass number out of range!");
351 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
356 char PassManagerImpl::ID = 0;
357 } // End of llvm namespace
361 //===----------------------------------------------------------------------===//
362 /// TimingInfo Class - This class is used to calculate information about the
363 /// amount of time each pass takes to execute. This only happens when
364 /// -time-passes is enabled on the command line.
367 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
369 class VISIBILITY_HIDDEN TimingInfo {
370 std::map<Pass*, Timer> TimingData;
374 // Use 'create' member to get this.
375 TimingInfo() : TG("... Pass execution timing report ...") {}
377 // TimingDtor - Print out information about timing information
379 // Delete all of the timers...
381 // TimerGroup is deleted next, printing the report.
384 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
385 // to a non null value (if the -time-passes option is enabled) or it leaves it
386 // null. It may be called multiple times.
387 static void createTheTimeInfo();
389 void passStarted(Pass *P) {
390 if (dynamic_cast<PMDataManager *>(P))
393 sys::SmartScopedLock<true> Lock(&*TimingInfoMutex);
394 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
395 if (I == TimingData.end())
396 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
397 I->second.startTimer();
400 void passEnded(Pass *P) {
401 if (dynamic_cast<PMDataManager *>(P))
404 sys::SmartScopedLock<true> Lock(&*TimingInfoMutex);
405 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
406 assert(I != TimingData.end() && "passStarted/passEnded not nested right!");
407 I->second.stopTimer();
411 } // End of anon namespace
413 static TimingInfo *TheTimeInfo;
415 //===----------------------------------------------------------------------===//
416 // PMTopLevelManager implementation
418 /// Initialize top level manager. Create first pass manager.
419 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
421 MPPassManager *MPP = new MPPassManager(1);
422 MPP->setTopLevelManager(this);
424 activeStack.push(MPP);
425 } else if (t == TLM_Function) {
426 FPPassManager *FPP = new FPPassManager(1);
427 FPP->setTopLevelManager(this);
429 activeStack.push(FPP);
433 /// Set pass P as the last user of the given analysis passes.
434 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
436 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
437 E = AnalysisPasses.end(); I != E; ++I) {
444 // If AP is the last user of other passes then make P last user of
446 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
447 LUE = LastUser.end(); LUI != LUE; ++LUI) {
448 if (LUI->second == AP)
449 // DenseMap iterator is not invalidated here because
450 // this is just updating exisitng entry.
451 LastUser[LUI->first] = P;
456 /// Collect passes whose last user is P
457 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
459 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
460 InversedLastUser.find(P);
461 if (DMI == InversedLastUser.end())
464 SmallPtrSet<Pass *, 8> &LU = DMI->second;
465 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
466 E = LU.end(); I != E; ++I) {
467 LastUses.push_back(*I);
472 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
473 AnalysisUsage *AnUsage = NULL;
474 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
475 if (DMI != AnUsageMap.end())
476 AnUsage = DMI->second;
478 AnUsage = new AnalysisUsage();
479 P->getAnalysisUsage(*AnUsage);
480 AnUsageMap[P] = AnUsage;
485 /// Schedule pass P for execution. Make sure that passes required by
486 /// P are run before P is run. Update analysis info maintained by
487 /// the manager. Remove dead passes. This is a recursive function.
488 void PMTopLevelManager::schedulePass(Pass *P) {
490 // TODO : Allocate function manager for this pass, other wise required set
491 // may be inserted into previous function manager
493 // Give pass a chance to prepare the stage.
494 P->preparePassManager(activeStack);
496 // If P is an analysis pass and it is available then do not
497 // generate the analysis again. Stale analysis info should not be
498 // available at this point.
499 if (P->getPassInfo() &&
500 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
505 AnalysisUsage *AnUsage = findAnalysisUsage(P);
507 bool checkAnalysis = true;
508 while (checkAnalysis) {
509 checkAnalysis = false;
511 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
512 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
513 E = RequiredSet.end(); I != E; ++I) {
515 Pass *AnalysisPass = findAnalysisPass(*I);
517 AnalysisPass = (*I)->createPass();
518 if (P->getPotentialPassManagerType () ==
519 AnalysisPass->getPotentialPassManagerType())
520 // Schedule analysis pass that is managed by the same pass manager.
521 schedulePass(AnalysisPass);
522 else if (P->getPotentialPassManagerType () >
523 AnalysisPass->getPotentialPassManagerType()) {
524 // Schedule analysis pass that is managed by a new manager.
525 schedulePass(AnalysisPass);
526 // Recheck analysis passes to ensure that required analysises that
527 // are already checked are still available.
528 checkAnalysis = true;
531 // Do not schedule this analysis. Lower level analsyis
532 // passes are run on the fly.
538 // Now all required passes are available.
542 /// Find the pass that implements Analysis AID. Search immutable
543 /// passes and all pass managers. If desired pass is not found
544 /// then return NULL.
545 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
548 // Check pass managers
549 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
550 E = PassManagers.end(); P == NULL && I != E; ++I) {
551 PMDataManager *PMD = *I;
552 P = PMD->findAnalysisPass(AID, false);
555 // Check other pass managers
556 for (SmallVector<PMDataManager *, 8>::iterator
557 I = IndirectPassManagers.begin(),
558 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
559 P = (*I)->findAnalysisPass(AID, false);
561 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
562 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
563 const PassInfo *PI = (*I)->getPassInfo();
567 // If Pass not found then check the interfaces implemented by Immutable Pass
569 const std::vector<const PassInfo*> &ImmPI =
570 PI->getInterfacesImplemented();
571 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
579 // Print passes managed by this top level manager.
580 void PMTopLevelManager::dumpPasses() const {
582 if (PassDebugging < Structure)
585 // Print out the immutable passes
586 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
587 ImmutablePasses[i]->dumpPassStructure(0);
590 // Every class that derives from PMDataManager also derives from Pass
591 // (sometimes indirectly), but there's no inheritance relationship
592 // between PMDataManager and Pass, so we have to dynamic_cast to get
593 // from a PMDataManager* to a Pass*.
594 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
595 E = PassManagers.end(); I != E; ++I)
596 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
599 void PMTopLevelManager::dumpArguments() const {
601 if (PassDebugging < Arguments)
604 cerr << "Pass Arguments: ";
605 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
606 E = PassManagers.end(); I != E; ++I)
607 (*I)->dumpPassArguments();
611 void PMTopLevelManager::initializeAllAnalysisInfo() {
612 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
613 E = PassManagers.end(); I != E; ++I)
614 (*I)->initializeAnalysisInfo();
616 // Initailize other pass managers
617 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
618 E = IndirectPassManagers.end(); I != E; ++I)
619 (*I)->initializeAnalysisInfo();
621 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
622 DME = LastUser.end(); DMI != DME; ++DMI) {
623 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
624 InversedLastUser.find(DMI->second);
625 if (InvDMI != InversedLastUser.end()) {
626 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
627 L.insert(DMI->first);
629 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
630 InversedLastUser[DMI->second] = L;
636 PMTopLevelManager::~PMTopLevelManager() {
637 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
638 E = PassManagers.end(); I != E; ++I)
641 for (SmallVector<ImmutablePass *, 8>::iterator
642 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
645 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
646 DME = AnUsageMap.end(); DMI != DME; ++DMI)
650 //===----------------------------------------------------------------------===//
651 // PMDataManager implementation
653 /// Augement AvailableAnalysis by adding analysis made available by pass P.
654 void PMDataManager::recordAvailableAnalysis(Pass *P) {
655 const PassInfo *PI = P->getPassInfo();
658 AvailableAnalysis[PI] = P;
660 //This pass is the current implementation of all of the interfaces it
661 //implements as well.
662 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
663 for (unsigned i = 0, e = II.size(); i != e; ++i)
664 AvailableAnalysis[II[i]] = P;
667 // Return true if P preserves high level analysis used by other
668 // passes managed by this manager
669 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
670 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
671 if (AnUsage->getPreservesAll())
674 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
675 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
676 E = HigherLevelAnalysis.end(); I != E; ++I) {
678 if (!dynamic_cast<ImmutablePass*>(P1) &&
679 std::find(PreservedSet.begin(), PreservedSet.end(),
680 P1->getPassInfo()) ==
688 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
689 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
690 // Don't do this unless assertions are enabled.
694 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
695 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
697 // Verify preserved analysis
698 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
699 E = PreservedSet.end(); I != E; ++I) {
701 if (Pass *AP = findAnalysisPass(AID, true))
702 AP->verifyAnalysis();
706 /// verifyDomInfo - Verify dominator information if it is available.
707 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
708 if (!VerifyDomInfo || !P.getResolver())
711 DominatorTree *DT = P.getAnalysisIfAvailable<DominatorTree>();
715 DominatorTree OtherDT;
716 OtherDT.getBase().recalculate(F);
717 if (DT->compare(OtherDT)) {
718 cerr << "Dominator Information for " << F.getNameStart() << "\n";
719 cerr << "Pass '" << P.getPassName() << "'\n";
720 cerr << "----- Valid -----\n";
722 cerr << "----- Invalid -----\n";
724 assert(0 && "Invalid dominator info");
727 DominanceFrontier *DF = P.getAnalysisIfAvailable<DominanceFrontier>();
731 DominanceFrontier OtherDF;
732 std::vector<BasicBlock*> DTRoots = DT->getRoots();
733 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
734 if (DF->compare(OtherDF)) {
735 cerr << "Dominator Information for " << F.getNameStart() << "\n";
736 cerr << "Pass '" << P.getPassName() << "'\n";
737 cerr << "----- Valid -----\n";
739 cerr << "----- Invalid -----\n";
741 assert(0 && "Invalid dominator info");
745 /// Remove Analysis not preserved by Pass P
746 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
747 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
748 if (AnUsage->getPreservesAll())
751 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
752 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
753 E = AvailableAnalysis.end(); I != E; ) {
754 std::map<AnalysisID, Pass*>::iterator Info = I++;
755 if (!dynamic_cast<ImmutablePass*>(Info->second)
756 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
757 PreservedSet.end()) {
758 // Remove this analysis
759 if (PassDebugging >= Details) {
760 Pass *S = Info->second;
761 cerr << " -- '" << P->getPassName() << "' is not preserving '";
762 cerr << S->getPassName() << "'\n";
764 AvailableAnalysis.erase(Info);
768 // Check inherited analysis also. If P is not preserving analysis
769 // provided by parent manager then remove it here.
770 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
772 if (!InheritedAnalysis[Index])
775 for (std::map<AnalysisID, Pass*>::iterator
776 I = InheritedAnalysis[Index]->begin(),
777 E = InheritedAnalysis[Index]->end(); I != E; ) {
778 std::map<AnalysisID, Pass *>::iterator Info = I++;
779 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
780 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
782 // Remove this analysis
783 InheritedAnalysis[Index]->erase(Info);
788 /// Remove analysis passes that are not used any longer
789 void PMDataManager::removeDeadPasses(Pass *P, const char *Msg,
790 enum PassDebuggingString DBG_STR) {
792 SmallVector<Pass *, 12> DeadPasses;
794 // If this is a on the fly manager then it does not have TPM.
798 TPM->collectLastUses(DeadPasses, P);
800 if (PassDebugging >= Details && !DeadPasses.empty()) {
801 cerr << " -*- '" << P->getPassName();
802 cerr << "' is the last user of following pass instances.";
803 cerr << " Free these instances\n";
806 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
807 E = DeadPasses.end(); I != E; ++I) {
809 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
812 // If the pass crashes releasing memory, remember this.
813 PassManagerPrettyStackEntry X(*I);
815 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
816 (*I)->releaseMemory();
817 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
819 if (const PassInfo *PI = (*I)->getPassInfo()) {
820 std::map<AnalysisID, Pass*>::iterator Pos =
821 AvailableAnalysis.find(PI);
823 // It is possible that pass is already removed from the AvailableAnalysis
824 if (Pos != AvailableAnalysis.end())
825 AvailableAnalysis.erase(Pos);
827 // Remove all interfaces this pass implements, for which it is also
828 // listed as the available implementation.
829 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
830 for (unsigned i = 0, e = II.size(); i != e; ++i) {
831 Pos = AvailableAnalysis.find(II[i]);
832 if (Pos != AvailableAnalysis.end() && Pos->second == *I)
833 AvailableAnalysis.erase(Pos);
839 /// Add pass P into the PassVector. Update
840 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
841 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
842 // This manager is going to manage pass P. Set up analysis resolver
844 AnalysisResolver *AR = new AnalysisResolver(*this);
847 // If a FunctionPass F is the last user of ModulePass info M
848 // then the F's manager, not F, records itself as a last user of M.
849 SmallVector<Pass *, 12> TransferLastUses;
851 if (!ProcessAnalysis) {
853 PassVector.push_back(P);
857 // At the moment, this pass is the last user of all required passes.
858 SmallVector<Pass *, 12> LastUses;
859 SmallVector<Pass *, 8> RequiredPasses;
860 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
862 unsigned PDepth = this->getDepth();
864 collectRequiredAnalysis(RequiredPasses,
865 ReqAnalysisNotAvailable, P);
866 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
867 E = RequiredPasses.end(); I != E; ++I) {
868 Pass *PRequired = *I;
871 assert(PRequired->getResolver() && "Analysis Resolver is not set");
872 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
873 RDepth = DM.getDepth();
875 if (PDepth == RDepth)
876 LastUses.push_back(PRequired);
877 else if (PDepth > RDepth) {
878 // Let the parent claim responsibility of last use
879 TransferLastUses.push_back(PRequired);
880 // Keep track of higher level analysis used by this manager.
881 HigherLevelAnalysis.push_back(PRequired);
883 assert(0 && "Unable to accomodate Required Pass");
886 // Set P as P's last user until someone starts using P.
887 // However, if P is a Pass Manager then it does not need
888 // to record its last user.
889 if (!dynamic_cast<PMDataManager *>(P))
890 LastUses.push_back(P);
891 TPM->setLastUser(LastUses, P);
893 if (!TransferLastUses.empty()) {
894 Pass *My_PM = dynamic_cast<Pass *>(this);
895 TPM->setLastUser(TransferLastUses, My_PM);
896 TransferLastUses.clear();
899 // Now, take care of required analysises that are not available.
900 for (SmallVector<AnalysisID, 8>::iterator
901 I = ReqAnalysisNotAvailable.begin(),
902 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
903 Pass *AnalysisPass = (*I)->createPass();
904 this->addLowerLevelRequiredPass(P, AnalysisPass);
907 // Take a note of analysis required and made available by this pass.
908 // Remove the analysis not preserved by this pass
909 removeNotPreservedAnalysis(P);
910 recordAvailableAnalysis(P);
913 PassVector.push_back(P);
917 /// Populate RP with analysis pass that are required by
918 /// pass P and are available. Populate RP_NotAvail with analysis
919 /// pass that are required by pass P but are not available.
920 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
921 SmallVector<AnalysisID, 8> &RP_NotAvail,
923 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
924 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
925 for (AnalysisUsage::VectorType::const_iterator
926 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
927 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
928 RP.push_back(AnalysisPass);
930 RP_NotAvail.push_back(*I);
933 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
934 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
935 E = IDs.end(); I != E; ++I) {
936 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
937 RP.push_back(AnalysisPass);
939 RP_NotAvail.push_back(*I);
943 // All Required analyses should be available to the pass as it runs! Here
944 // we fill in the AnalysisImpls member of the pass so that it can
945 // successfully use the getAnalysis() method to retrieve the
946 // implementations it needs.
948 void PMDataManager::initializeAnalysisImpl(Pass *P) {
949 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
951 for (AnalysisUsage::VectorType::const_iterator
952 I = AnUsage->getRequiredSet().begin(),
953 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
954 Pass *Impl = findAnalysisPass(*I, true);
956 // This may be analysis pass that is initialized on the fly.
957 // If that is not the case then it will raise an assert when it is used.
959 AnalysisResolver *AR = P->getResolver();
960 assert(AR && "Analysis Resolver is not set");
961 AR->addAnalysisImplsPair(*I, Impl);
965 /// Find the pass that implements Analysis AID. If desired pass is not found
966 /// then return NULL.
967 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
969 // Check if AvailableAnalysis map has one entry.
970 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
972 if (I != AvailableAnalysis.end())
975 // Search Parents through TopLevelManager
977 return TPM->findAnalysisPass(AID);
982 // Print list of passes that are last used by P.
983 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
985 SmallVector<Pass *, 12> LUses;
987 // If this is a on the fly manager then it does not have TPM.
991 TPM->collectLastUses(LUses, P);
993 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
994 E = LUses.end(); I != E; ++I) {
995 llvm::cerr << "--" << std::string(Offset*2, ' ');
996 (*I)->dumpPassStructure(0);
1000 void PMDataManager::dumpPassArguments() const {
1001 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1002 E = PassVector.end(); I != E; ++I) {
1003 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
1004 PMD->dumpPassArguments();
1006 if (const PassInfo *PI = (*I)->getPassInfo())
1007 if (!PI->isAnalysisGroup())
1008 cerr << " -" << PI->getPassArgument();
1012 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1013 enum PassDebuggingString S2,
1015 if (PassDebugging < Executions)
1017 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
1020 cerr << "Executing Pass '" << P->getPassName();
1022 case MODIFICATION_MSG:
1023 cerr << "Made Modification '" << P->getPassName();
1026 cerr << " Freeing Pass '" << P->getPassName();
1032 case ON_BASICBLOCK_MSG:
1033 cerr << "' on BasicBlock '" << Msg << "'...\n";
1035 case ON_FUNCTION_MSG:
1036 cerr << "' on Function '" << Msg << "'...\n";
1039 cerr << "' on Module '" << Msg << "'...\n";
1042 cerr << "' on Loop " << Msg << "'...\n";
1045 cerr << "' on Call Graph " << Msg << "'...\n";
1052 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1053 if (PassDebugging < Details)
1056 AnalysisUsage analysisUsage;
1057 P->getAnalysisUsage(analysisUsage);
1058 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1061 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1062 if (PassDebugging < Details)
1065 AnalysisUsage analysisUsage;
1066 P->getAnalysisUsage(analysisUsage);
1067 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1070 void PMDataManager::dumpAnalysisUsage(const char *Msg, const Pass *P,
1071 const AnalysisUsage::VectorType &Set) const {
1072 assert(PassDebugging >= Details);
1075 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1076 for (unsigned i = 0; i != Set.size(); ++i) {
1078 cerr << " " << Set[i]->getPassName();
1083 /// Add RequiredPass into list of lower level passes required by pass P.
1084 /// RequiredPass is run on the fly by Pass Manager when P requests it
1085 /// through getAnalysis interface.
1086 /// This should be handled by specific pass manager.
1087 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1089 TPM->dumpArguments();
1093 // Module Level pass may required Function Level analysis info
1094 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1095 // to provide this on demand. In that case, in Pass manager terminology,
1096 // module level pass is requiring lower level analysis info managed by
1097 // lower level pass manager.
1099 // When Pass manager is not able to order required analysis info, Pass manager
1100 // checks whether any lower level manager will be able to provide this
1101 // analysis info on demand or not.
1103 cerr << "Unable to schedule '" << RequiredPass->getPassName();
1104 cerr << "' required by '" << P->getPassName() << "'\n";
1106 assert(0 && "Unable to schedule pass");
1110 PMDataManager::~PMDataManager() {
1111 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1112 E = PassVector.end(); I != E; ++I)
1116 //===----------------------------------------------------------------------===//
1117 // NOTE: Is this the right place to define this method ?
1118 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1119 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1120 return PM.findAnalysisPass(ID, dir);
1123 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1125 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1128 //===----------------------------------------------------------------------===//
1129 // BBPassManager implementation
1131 /// Execute all of the passes scheduled for execution by invoking
1132 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1133 /// the function, and if so, return true.
1134 bool BBPassManager::runOnFunction(Function &F) {
1135 if (F.isDeclaration())
1138 bool Changed = doInitialization(F);
1140 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1141 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1142 BasicBlockPass *BP = getContainedPass(Index);
1144 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getNameStart());
1145 dumpRequiredSet(BP);
1147 initializeAnalysisImpl(BP);
1150 // If the pass crashes, remember this.
1151 PassManagerPrettyStackEntry X(BP, *I);
1153 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1154 Changed |= BP->runOnBasicBlock(*I);
1155 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1159 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1161 dumpPreservedSet(BP);
1163 verifyPreservedAnalysis(BP);
1164 removeNotPreservedAnalysis(BP);
1165 recordAvailableAnalysis(BP);
1166 removeDeadPasses(BP, I->getNameStart(), ON_BASICBLOCK_MSG);
1169 return Changed |= doFinalization(F);
1172 // Implement doInitialization and doFinalization
1173 bool BBPassManager::doInitialization(Module &M) {
1174 bool Changed = false;
1176 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1177 Changed |= getContainedPass(Index)->doInitialization(M);
1182 bool BBPassManager::doFinalization(Module &M) {
1183 bool Changed = false;
1185 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1186 Changed |= getContainedPass(Index)->doFinalization(M);
1191 bool BBPassManager::doInitialization(Function &F) {
1192 bool Changed = false;
1194 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1195 BasicBlockPass *BP = getContainedPass(Index);
1196 Changed |= BP->doInitialization(F);
1202 bool BBPassManager::doFinalization(Function &F) {
1203 bool Changed = false;
1205 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1206 BasicBlockPass *BP = getContainedPass(Index);
1207 Changed |= BP->doFinalization(F);
1214 //===----------------------------------------------------------------------===//
1215 // FunctionPassManager implementation
1217 /// Create new Function pass manager
1218 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1219 FPM = new FunctionPassManagerImpl(0);
1220 // FPM is the top level manager.
1221 FPM->setTopLevelManager(FPM);
1223 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1224 FPM->setResolver(AR);
1229 FunctionPassManager::~FunctionPassManager() {
1233 /// add - Add a pass to the queue of passes to run. This passes
1234 /// ownership of the Pass to the PassManager. When the
1235 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1236 /// there is no need to delete the pass. (TODO delete passes.)
1237 /// This implies that all passes MUST be allocated with 'new'.
1238 void FunctionPassManager::add(Pass *P) {
1242 /// run - Execute all of the passes scheduled for execution. Keep
1243 /// track of whether any of the passes modifies the function, and if
1244 /// so, return true.
1246 bool FunctionPassManager::run(Function &F) {
1248 if (MP->materializeFunction(&F, &errstr)) {
1249 cerr << "Error reading bitcode file: " << errstr << "\n";
1256 /// doInitialization - Run all of the initializers for the function passes.
1258 bool FunctionPassManager::doInitialization() {
1259 return FPM->doInitialization(*MP->getModule());
1262 /// doFinalization - Run all of the finalizers for the function passes.
1264 bool FunctionPassManager::doFinalization() {
1265 return FPM->doFinalization(*MP->getModule());
1268 //===----------------------------------------------------------------------===//
1269 // FunctionPassManagerImpl implementation
1271 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1272 bool Changed = false;
1274 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1275 Changed |= getContainedManager(Index)->doInitialization(M);
1280 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1281 bool Changed = false;
1283 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1284 Changed |= getContainedManager(Index)->doFinalization(M);
1289 /// cleanup - After running all passes, clean up pass manager cache.
1290 void FPPassManager::cleanup() {
1291 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1292 FunctionPass *FP = getContainedPass(Index);
1293 AnalysisResolver *AR = FP->getResolver();
1294 assert(AR && "Analysis Resolver is not set");
1295 AR->clearAnalysisImpls();
1299 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1302 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1303 FPPassManager *FPPM = getContainedManager(Index);
1304 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1305 FPPM->getContainedPass(Index)->releaseMemory();
1311 // Execute all the passes managed by this top level manager.
1312 // Return true if any function is modified by a pass.
1313 bool FunctionPassManagerImpl::run(Function &F) {
1314 bool Changed = false;
1315 TimingInfo::createTheTimeInfo();
1320 initializeAllAnalysisInfo();
1321 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1322 Changed |= getContainedManager(Index)->runOnFunction(F);
1324 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1325 getContainedManager(Index)->cleanup();
1331 //===----------------------------------------------------------------------===//
1332 // FPPassManager implementation
1334 char FPPassManager::ID = 0;
1335 /// Print passes managed by this manager
1336 void FPPassManager::dumpPassStructure(unsigned Offset) {
1337 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1338 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1339 FunctionPass *FP = getContainedPass(Index);
1340 FP->dumpPassStructure(Offset + 1);
1341 dumpLastUses(FP, Offset+1);
1346 /// Execute all of the passes scheduled for execution by invoking
1347 /// runOnFunction method. Keep track of whether any of the passes modifies
1348 /// the function, and if so, return true.
1349 bool FPPassManager::runOnFunction(Function &F) {
1350 if (F.isDeclaration())
1353 bool Changed = false;
1355 // Collect inherited analysis from Module level pass manager.
1356 populateInheritedAnalysis(TPM->activeStack);
1358 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1359 FunctionPass *FP = getContainedPass(Index);
1361 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1362 dumpRequiredSet(FP);
1364 initializeAnalysisImpl(FP);
1367 PassManagerPrettyStackEntry X(FP, F);
1369 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1370 Changed |= FP->runOnFunction(F);
1371 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1375 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1376 dumpPreservedSet(FP);
1378 verifyPreservedAnalysis(FP);
1379 removeNotPreservedAnalysis(FP);
1380 recordAvailableAnalysis(FP);
1381 removeDeadPasses(FP, F.getNameStart(), ON_FUNCTION_MSG);
1383 // If dominator information is available then verify the info if requested.
1384 verifyDomInfo(*FP, F);
1389 bool FPPassManager::runOnModule(Module &M) {
1390 bool Changed = doInitialization(M);
1392 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1395 return Changed |= doFinalization(M);
1398 bool FPPassManager::doInitialization(Module &M) {
1399 bool Changed = false;
1401 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1402 Changed |= getContainedPass(Index)->doInitialization(M);
1407 bool FPPassManager::doFinalization(Module &M) {
1408 bool Changed = false;
1410 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1411 Changed |= getContainedPass(Index)->doFinalization(M);
1416 //===----------------------------------------------------------------------===//
1417 // MPPassManager implementation
1419 /// Execute all of the passes scheduled for execution by invoking
1420 /// runOnModule method. Keep track of whether any of the passes modifies
1421 /// the module, and if so, return true.
1423 MPPassManager::runOnModule(Module &M) {
1424 bool Changed = false;
1426 // Initialize on-the-fly passes
1427 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1428 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1430 FunctionPassManagerImpl *FPP = I->second;
1431 Changed |= FPP->doInitialization(M);
1434 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1435 ModulePass *MP = getContainedPass(Index);
1437 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1438 M.getModuleIdentifier().c_str());
1439 dumpRequiredSet(MP);
1441 initializeAnalysisImpl(MP);
1444 PassManagerPrettyStackEntry X(MP, M);
1445 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1446 Changed |= MP->runOnModule(M);
1447 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1451 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1452 M.getModuleIdentifier().c_str());
1453 dumpPreservedSet(MP);
1455 verifyPreservedAnalysis(MP);
1456 removeNotPreservedAnalysis(MP);
1457 recordAvailableAnalysis(MP);
1458 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1461 // Finalize on-the-fly passes
1462 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1463 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1465 FunctionPassManagerImpl *FPP = I->second;
1466 // We don't know when is the last time an on-the-fly pass is run,
1467 // so we need to releaseMemory / finalize here
1468 FPP->releaseMemoryOnTheFly();
1469 Changed |= FPP->doFinalization(M);
1474 /// Add RequiredPass into list of lower level passes required by pass P.
1475 /// RequiredPass is run on the fly by Pass Manager when P requests it
1476 /// through getAnalysis interface.
1477 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1478 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1479 "Unable to handle Pass that requires lower level Analysis pass");
1480 assert((P->getPotentialPassManagerType() <
1481 RequiredPass->getPotentialPassManagerType()) &&
1482 "Unable to handle Pass that requires lower level Analysis pass");
1484 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1486 FPP = new FunctionPassManagerImpl(0);
1487 // FPP is the top level manager.
1488 FPP->setTopLevelManager(FPP);
1490 OnTheFlyManagers[P] = FPP;
1492 FPP->add(RequiredPass);
1494 // Register P as the last user of RequiredPass.
1495 SmallVector<Pass *, 12> LU;
1496 LU.push_back(RequiredPass);
1497 FPP->setLastUser(LU, P);
1500 /// Return function pass corresponding to PassInfo PI, that is
1501 /// required by module pass MP. Instantiate analysis pass, by using
1502 /// its runOnFunction() for function F.
1503 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1504 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1505 assert(FPP && "Unable to find on the fly pass");
1507 FPP->releaseMemoryOnTheFly();
1509 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1513 //===----------------------------------------------------------------------===//
1514 // PassManagerImpl implementation
1516 /// run - Execute all of the passes scheduled for execution. Keep track of
1517 /// whether any of the passes modifies the module, and if so, return true.
1518 bool PassManagerImpl::run(Module &M) {
1519 bool Changed = false;
1520 TimingInfo::createTheTimeInfo();
1525 initializeAllAnalysisInfo();
1526 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1527 Changed |= getContainedManager(Index)->runOnModule(M);
1531 //===----------------------------------------------------------------------===//
1532 // PassManager implementation
1534 /// Create new pass manager
1535 PassManager::PassManager() {
1536 PM = new PassManagerImpl(0);
1537 // PM is the top level manager
1538 PM->setTopLevelManager(PM);
1541 PassManager::~PassManager() {
1545 /// add - Add a pass to the queue of passes to run. This passes ownership of
1546 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1547 /// will be destroyed as well, so there is no need to delete the pass. This
1548 /// implies that all passes MUST be allocated with 'new'.
1549 void PassManager::add(Pass *P) {
1553 /// run - Execute all of the passes scheduled for execution. Keep track of
1554 /// whether any of the passes modifies the module, and if so, return true.
1555 bool PassManager::run(Module &M) {
1559 //===----------------------------------------------------------------------===//
1560 // TimingInfo Class - This class is used to calculate information about the
1561 // amount of time each pass takes to execute. This only happens with
1562 // -time-passes is enabled on the command line.
1564 bool llvm::TimePassesIsEnabled = false;
1565 static cl::opt<bool,true>
1566 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1567 cl::desc("Time each pass, printing elapsed time for each on exit"));
1569 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1570 // a non null value (if the -time-passes option is enabled) or it leaves it
1571 // null. It may be called multiple times.
1572 void TimingInfo::createTheTimeInfo() {
1573 if (!TimePassesIsEnabled || TheTimeInfo) return;
1575 // Constructed the first time this is called, iff -time-passes is enabled.
1576 // This guarantees that the object will be constructed before static globals,
1577 // thus it will be destroyed before them.
1578 static ManagedStatic<TimingInfo> TTI;
1579 TheTimeInfo = &*TTI;
1582 /// If TimingInfo is enabled then start pass timer.
1583 void StartPassTimer(Pass *P) {
1585 TheTimeInfo->passStarted(P);
1588 /// If TimingInfo is enabled then stop pass timer.
1589 void StopPassTimer(Pass *P) {
1591 TheTimeInfo->passEnded(P);
1594 //===----------------------------------------------------------------------===//
1595 // PMStack implementation
1598 // Pop Pass Manager from the stack and clear its analysis info.
1599 void PMStack::pop() {
1601 PMDataManager *Top = this->top();
1602 Top->initializeAnalysisInfo();
1607 // Push PM on the stack and set its top level manager.
1608 void PMStack::push(PMDataManager *PM) {
1609 assert(PM && "Unable to push. Pass Manager expected");
1611 if (!this->empty()) {
1612 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1614 assert(TPM && "Unable to find top level manager");
1615 TPM->addIndirectPassManager(PM);
1616 PM->setTopLevelManager(TPM);
1622 // Dump content of the pass manager stack.
1623 void PMStack::dump() {
1624 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1625 E = S.end(); I != E; ++I)
1626 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1632 /// Find appropriate Module Pass Manager in the PM Stack and
1633 /// add self into that manager.
1634 void ModulePass::assignPassManager(PMStack &PMS,
1635 PassManagerType PreferredType) {
1636 // Find Module Pass Manager
1637 while(!PMS.empty()) {
1638 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1639 if (TopPMType == PreferredType)
1640 break; // We found desired pass manager
1641 else if (TopPMType > PMT_ModulePassManager)
1642 PMS.pop(); // Pop children pass managers
1646 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1647 PMS.top()->add(this);
1650 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1651 /// in the PM Stack and add self into that manager.
1652 void FunctionPass::assignPassManager(PMStack &PMS,
1653 PassManagerType PreferredType) {
1655 // Find Module Pass Manager
1656 while(!PMS.empty()) {
1657 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1662 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1664 // Create new Function Pass Manager
1666 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1667 PMDataManager *PMD = PMS.top();
1669 // [1] Create new Function Pass Manager
1670 FPP = new FPPassManager(PMD->getDepth() + 1);
1671 FPP->populateInheritedAnalysis(PMS);
1673 // [2] Set up new manager's top level manager
1674 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1675 TPM->addIndirectPassManager(FPP);
1677 // [3] Assign manager to manage this new manager. This may create
1678 // and push new managers into PMS
1679 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1681 // [4] Push new manager into PMS
1685 // Assign FPP as the manager of this pass.
1689 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1690 /// in the PM Stack and add self into that manager.
1691 void BasicBlockPass::assignPassManager(PMStack &PMS,
1692 PassManagerType PreferredType) {
1693 BBPassManager *BBP = NULL;
1695 // Basic Pass Manager is a leaf pass manager. It does not handle
1696 // any other pass manager.
1698 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1700 // If leaf manager is not Basic Block Pass manager then create new
1701 // basic Block Pass manager.
1704 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1705 PMDataManager *PMD = PMS.top();
1707 // [1] Create new Basic Block Manager
1708 BBP = new BBPassManager(PMD->getDepth() + 1);
1710 // [2] Set up new manager's top level manager
1711 // Basic Block Pass Manager does not live by itself
1712 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1713 TPM->addIndirectPassManager(BBP);
1715 // [3] Assign manager to manage this new manager. This may create
1716 // and push new managers into PMS
1717 BBP->assignPassManager(PMS);
1719 // [4] Push new manager into PMS
1723 // Assign BBP as the manager of this pass.
1727 PassManagerBase::~PassManagerBase() {}
1729 /*===-- C Bindings --------------------------------------------------------===*/
1731 LLVMPassManagerRef LLVMCreatePassManager() {
1732 return wrap(new PassManager());
1735 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1736 return wrap(new FunctionPassManager(unwrap(P)));
1739 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1740 return unwrap<PassManager>(PM)->run(*unwrap(M));
1743 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1744 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1747 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1748 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1751 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1752 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1755 void LLVMDisposePassManager(LLVMPassManagerRef PM) {