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/Analysis/Dominators.h"
23 #include "llvm-c/Core.h"
30 // See PassManagers.h for Pass Manager infrastructure overview.
34 //===----------------------------------------------------------------------===//
35 // Pass debugging information. Often it is useful to find out what pass is
36 // running when a crash occurs in a utility. When this library is compiled with
37 // debugging on, a command line option (--debug-pass) is enabled that causes the
38 // pass name to be printed before it executes.
41 // Different debug levels that can be enabled...
43 None, Arguments, Structure, Executions, Details
46 bool VerifyDomInfo = false;
47 static cl::opt<bool,true>
48 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
49 cl::desc("Verify dominator info (time consuming)"));
51 static cl::opt<enum PassDebugLevel>
52 PassDebugging("debug-pass", cl::Hidden,
53 cl::desc("Print PassManager debugging information"),
55 clEnumVal(None , "disable debug output"),
56 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
57 clEnumVal(Structure , "print pass structure before run()"),
58 clEnumVal(Executions, "print pass name before it is executed"),
59 clEnumVal(Details , "print pass details when it is executed"),
61 } // End of llvm namespace
65 //===----------------------------------------------------------------------===//
68 /// BBPassManager manages BasicBlockPass. It batches all the
69 /// pass together and sequence them to process one basic block before
70 /// processing next basic block.
71 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
76 explicit BBPassManager(int Depth)
77 : PMDataManager(Depth), FunctionPass(&ID) {}
79 /// Execute all of the passes scheduled for execution. Keep track of
80 /// whether any of the passes modifies the function, and if so, return true.
81 bool runOnFunction(Function &F);
83 /// Pass Manager itself does not invalidate any analysis info.
84 void getAnalysisUsage(AnalysisUsage &Info) const {
85 Info.setPreservesAll();
88 bool doInitialization(Module &M);
89 bool doInitialization(Function &F);
90 bool doFinalization(Module &M);
91 bool doFinalization(Function &F);
93 virtual const char *getPassName() const {
94 return "BasicBlock Pass Manager";
97 // Print passes managed by this manager
98 void dumpPassStructure(unsigned Offset) {
99 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
100 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
101 BasicBlockPass *BP = getContainedPass(Index);
102 BP->dumpPassStructure(Offset + 1);
103 dumpLastUses(BP, Offset+1);
107 BasicBlockPass *getContainedPass(unsigned N) {
108 assert ( N < PassVector.size() && "Pass number out of range!");
109 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
113 virtual PassManagerType getPassManagerType() const {
114 return PMT_BasicBlockPassManager;
118 char BBPassManager::ID = 0;
123 //===----------------------------------------------------------------------===//
124 // FunctionPassManagerImpl
126 /// FunctionPassManagerImpl manages FPPassManagers
127 class FunctionPassManagerImpl : public Pass,
128 public PMDataManager,
129 public PMTopLevelManager {
132 explicit FunctionPassManagerImpl(int Depth) :
133 Pass(&ID), PMDataManager(Depth),
134 PMTopLevelManager(TLM_Function) { }
136 /// add - Add a pass to the queue of passes to run. This passes ownership of
137 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
138 /// will be destroyed as well, so there is no need to delete the pass. This
139 /// implies that all passes MUST be allocated with 'new'.
144 /// run - Execute all of the passes scheduled for execution. Keep track of
145 /// whether any of the passes modifies the module, and if so, return true.
146 bool run(Function &F);
148 /// doInitialization - Run all of the initializers for the function passes.
150 bool doInitialization(Module &M);
152 /// doFinalization - Run all of the finalizers for the function passes.
154 bool doFinalization(Module &M);
156 /// Pass Manager itself does not invalidate any analysis info.
157 void getAnalysisUsage(AnalysisUsage &Info) const {
158 Info.setPreservesAll();
161 inline void addTopLevelPass(Pass *P) {
163 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
165 // P is a immutable pass and it will be managed by this
166 // top level manager. Set up analysis resolver to connect them.
167 AnalysisResolver *AR = new AnalysisResolver(*this);
169 initializeAnalysisImpl(P);
170 addImmutablePass(IP);
171 recordAvailableAnalysis(IP);
173 P->assignPassManager(activeStack);
178 FPPassManager *getContainedManager(unsigned N) {
179 assert ( N < PassManagers.size() && "Pass number out of range!");
180 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
185 char FunctionPassManagerImpl::ID = 0;
186 //===----------------------------------------------------------------------===//
189 /// MPPassManager manages ModulePasses and function pass managers.
190 /// It batches all Module passes and function pass managers together and
191 /// sequences them to process one module.
192 class MPPassManager : public Pass, public PMDataManager {
196 explicit MPPassManager(int Depth) :
197 Pass(&ID), PMDataManager(Depth) { }
199 // Delete on the fly managers.
200 virtual ~MPPassManager() {
201 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
202 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
204 FunctionPassManagerImpl *FPP = I->second;
209 /// run - Execute all of the passes scheduled for execution. Keep track of
210 /// whether any of the passes modifies the module, and if so, return true.
211 bool runOnModule(Module &M);
213 /// Pass Manager itself does not invalidate any analysis info.
214 void getAnalysisUsage(AnalysisUsage &Info) const {
215 Info.setPreservesAll();
218 /// Add RequiredPass into list of lower level passes required by pass P.
219 /// RequiredPass is run on the fly by Pass Manager when P requests it
220 /// through getAnalysis interface.
221 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
223 /// Return function pass corresponding to PassInfo PI, that is
224 /// required by module pass MP. Instantiate analysis pass, by using
225 /// its runOnFunction() for function F.
226 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
228 virtual const char *getPassName() const {
229 return "Module Pass Manager";
232 // Print passes managed by this manager
233 void dumpPassStructure(unsigned Offset) {
234 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
235 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
236 ModulePass *MP = getContainedPass(Index);
237 MP->dumpPassStructure(Offset + 1);
238 if (FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP])
239 FPP->dumpPassStructure(Offset + 2);
240 dumpLastUses(MP, Offset+1);
244 ModulePass *getContainedPass(unsigned N) {
245 assert ( N < PassVector.size() && "Pass number out of range!");
246 ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
250 virtual PassManagerType getPassManagerType() const {
251 return PMT_ModulePassManager;
255 /// Collection of on the fly FPPassManagers. These managers manage
256 /// function passes that are required by module passes.
257 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
260 char MPPassManager::ID = 0;
261 //===----------------------------------------------------------------------===//
265 /// PassManagerImpl manages MPPassManagers
266 class PassManagerImpl : public Pass,
267 public PMDataManager,
268 public PMTopLevelManager {
272 explicit PassManagerImpl(int Depth) :
273 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
275 /// add - Add a pass to the queue of passes to run. This passes ownership of
276 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
277 /// will be destroyed as well, so there is no need to delete the pass. This
278 /// implies that all passes MUST be allocated with 'new'.
283 /// run - Execute all of the passes scheduled for execution. Keep track of
284 /// whether any of the passes modifies the module, and if so, return true.
287 /// Pass Manager itself does not invalidate any analysis info.
288 void getAnalysisUsage(AnalysisUsage &Info) const {
289 Info.setPreservesAll();
292 inline void addTopLevelPass(Pass *P) {
294 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
296 // P is a immutable pass and it will be managed by this
297 // top level manager. Set up analysis resolver to connect them.
298 AnalysisResolver *AR = new AnalysisResolver(*this);
300 initializeAnalysisImpl(P);
301 addImmutablePass(IP);
302 recordAvailableAnalysis(IP);
304 P->assignPassManager(activeStack);
309 MPPassManager *getContainedManager(unsigned N) {
310 assert ( N < PassManagers.size() && "Pass number out of range!");
311 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
317 char PassManagerImpl::ID = 0;
318 } // End of llvm namespace
322 //===----------------------------------------------------------------------===//
323 // TimingInfo Class - This class is used to calculate information about the
324 // amount of time each pass takes to execute. This only happens when
325 // -time-passes is enabled on the command line.
328 class VISIBILITY_HIDDEN TimingInfo {
329 std::map<Pass*, Timer> TimingData;
333 // Use 'create' member to get this.
334 TimingInfo() : TG("... Pass execution timing report ...") {}
336 // TimingDtor - Print out information about timing information
338 // Delete all of the timers...
340 // TimerGroup is deleted next, printing the report.
343 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
344 // to a non null value (if the -time-passes option is enabled) or it leaves it
345 // null. It may be called multiple times.
346 static void createTheTimeInfo();
348 void passStarted(Pass *P) {
350 if (dynamic_cast<PMDataManager *>(P))
353 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
354 if (I == TimingData.end())
355 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
356 I->second.startTimer();
358 void passEnded(Pass *P) {
360 if (dynamic_cast<PMDataManager *>(P))
363 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
364 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
365 I->second.stopTimer();
369 } // End of anon namespace
371 static TimingInfo *TheTimeInfo;
373 //===----------------------------------------------------------------------===//
374 // PMTopLevelManager implementation
376 /// Initialize top level manager. Create first pass manager.
377 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
380 MPPassManager *MPP = new MPPassManager(1);
381 MPP->setTopLevelManager(this);
383 activeStack.push(MPP);
385 else if (t == TLM_Function) {
386 FPPassManager *FPP = new FPPassManager(1);
387 FPP->setTopLevelManager(this);
389 activeStack.push(FPP);
393 /// Set pass P as the last user of the given analysis passes.
394 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
397 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
398 E = AnalysisPasses.end(); I != E; ++I) {
405 // If AP is the last user of other passes then make P last user of
407 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
408 LUE = LastUser.end(); LUI != LUE; ++LUI) {
409 if (LUI->second == AP)
410 // DenseMap iterator is not invalidated here because
411 // this is just updating exisitng entry.
412 LastUser[LUI->first] = P;
417 /// Collect passes whose last user is P
418 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
420 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
421 InversedLastUser.find(P);
422 if (DMI == InversedLastUser.end())
425 SmallPtrSet<Pass *, 8> &LU = DMI->second;
426 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
427 E = LU.end(); I != E; ++I) {
428 LastUses.push_back(*I);
433 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
434 AnalysisUsage *AnUsage = NULL;
435 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
436 if (DMI != AnUsageMap.end())
437 AnUsage = DMI->second;
439 AnUsage = new AnalysisUsage();
440 P->getAnalysisUsage(*AnUsage);
441 AnUsageMap[P] = AnUsage;
446 /// Schedule pass P for execution. Make sure that passes required by
447 /// P are run before P is run. Update analysis info maintained by
448 /// the manager. Remove dead passes. This is a recursive function.
449 void PMTopLevelManager::schedulePass(Pass *P) {
451 // TODO : Allocate function manager for this pass, other wise required set
452 // may be inserted into previous function manager
454 // Give pass a chance to prepare the stage.
455 P->preparePassManager(activeStack);
457 // If P is an analysis pass and it is available then do not
458 // generate the analysis again. Stale analysis info should not be
459 // available at this point.
460 if (P->getPassInfo() &&
461 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
466 AnalysisUsage *AnUsage = findAnalysisUsage(P);
468 bool checkAnalysis = true;
469 while (checkAnalysis) {
470 checkAnalysis = false;
472 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
473 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
474 E = RequiredSet.end(); I != E; ++I) {
476 Pass *AnalysisPass = findAnalysisPass(*I);
478 AnalysisPass = (*I)->createPass();
479 if (P->getPotentialPassManagerType () ==
480 AnalysisPass->getPotentialPassManagerType())
481 // Schedule analysis pass that is managed by the same pass manager.
482 schedulePass(AnalysisPass);
483 else if (P->getPotentialPassManagerType () >
484 AnalysisPass->getPotentialPassManagerType()) {
485 // Schedule analysis pass that is managed by a new manager.
486 schedulePass(AnalysisPass);
487 // Recheck analysis passes to ensure that required analysises that
488 // are already checked are still available.
489 checkAnalysis = true;
492 // Do not schedule this analysis. Lower level analsyis
493 // passes are run on the fly.
499 // Now all required passes are available.
503 /// Find the pass that implements Analysis AID. Search immutable
504 /// passes and all pass managers. If desired pass is not found
505 /// then return NULL.
506 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
509 // Check pass managers
510 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
511 E = PassManagers.end(); P == NULL && I != E; ++I) {
512 PMDataManager *PMD = *I;
513 P = PMD->findAnalysisPass(AID, false);
516 // Check other pass managers
517 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
518 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
519 P = (*I)->findAnalysisPass(AID, false);
521 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
522 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
523 const PassInfo *PI = (*I)->getPassInfo();
527 // If Pass not found then check the interfaces implemented by Immutable Pass
529 const std::vector<const PassInfo*> &ImmPI =
530 PI->getInterfacesImplemented();
531 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
539 // Print passes managed by this top level manager.
540 void PMTopLevelManager::dumpPasses() const {
542 if (PassDebugging < Structure)
545 // Print out the immutable passes
546 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
547 ImmutablePasses[i]->dumpPassStructure(0);
550 // Every class that derives from PMDataManager also derives from Pass
551 // (sometimes indirectly), but there's no inheritance relationship
552 // between PMDataManager and Pass, so we have to dynamic_cast to get
553 // from a PMDataManager* to a Pass*.
554 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
555 E = PassManagers.end(); I != E; ++I)
556 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
559 void PMTopLevelManager::dumpArguments() const {
561 if (PassDebugging < Arguments)
564 cerr << "Pass Arguments: ";
565 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
566 E = PassManagers.end(); I != E; ++I) {
567 PMDataManager *PMD = *I;
568 PMD->dumpPassArguments();
573 void PMTopLevelManager::initializeAllAnalysisInfo() {
575 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
576 E = PassManagers.end(); I != E; ++I) {
577 PMDataManager *PMD = *I;
578 PMD->initializeAnalysisInfo();
581 // Initailize other pass managers
582 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
583 E = IndirectPassManagers.end(); I != E; ++I)
584 (*I)->initializeAnalysisInfo();
586 for(DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
587 DME = LastUser.end(); DMI != DME; ++DMI) {
588 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
589 InversedLastUser.find(DMI->second);
590 if (InvDMI != InversedLastUser.end()) {
591 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
592 L.insert(DMI->first);
594 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
595 InversedLastUser[DMI->second] = L;
601 PMTopLevelManager::~PMTopLevelManager() {
602 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
603 E = PassManagers.end(); I != E; ++I)
606 for (SmallVector<ImmutablePass *, 8>::iterator
607 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
610 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
611 DME = AnUsageMap.end(); DMI != DME; ++DMI) {
612 AnalysisUsage *AU = DMI->second;
618 //===----------------------------------------------------------------------===//
619 // PMDataManager implementation
621 /// Augement AvailableAnalysis by adding analysis made available by pass P.
622 void PMDataManager::recordAvailableAnalysis(Pass *P) {
624 if (const PassInfo *PI = P->getPassInfo()) {
625 AvailableAnalysis[PI] = P;
627 //This pass is the current implementation of all of the interfaces it
628 //implements as well.
629 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
630 for (unsigned i = 0, e = II.size(); i != e; ++i)
631 AvailableAnalysis[II[i]] = P;
635 // Return true if P preserves high level analysis used by other
636 // passes managed by this manager
637 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
639 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
641 if (AnUsage->getPreservesAll())
644 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
645 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
646 E = HigherLevelAnalysis.end(); I != E; ++I) {
648 if (!dynamic_cast<ImmutablePass*>(P1) &&
649 std::find(PreservedSet.begin(), PreservedSet.end(),
650 P1->getPassInfo()) ==
658 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
659 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
660 // Don't do this unless assertions are enabled.
664 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
665 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
667 // Verify preserved analysis
668 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
669 E = PreservedSet.end(); I != E; ++I) {
671 if (Pass *AP = findAnalysisPass(AID, true))
672 AP->verifyAnalysis();
676 /// verifyDomInfo - Verify dominator information if it is available.
677 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
679 if (!VerifyDomInfo || !P.getResolver())
682 DominatorTree *DT = P.getAnalysisToUpdate<DominatorTree>();
686 DominatorTree OtherDT;
687 OtherDT.getBase().recalculate(F);
688 if (DT->compare(OtherDT)) {
689 cerr << "Dominator Information for " << F.getNameStart() << "\n";
690 cerr << "Pass '" << P.getPassName() << "'\n";
691 cerr << "----- Valid -----\n";
693 cerr << "----- Invalid -----\n";
695 assert (0 && "Invalid dominator info");
698 DominanceFrontier *DF = P.getAnalysisToUpdate<DominanceFrontier>();
702 DominanceFrontier OtherDF;
703 std::vector<BasicBlock*> DTRoots = DT->getRoots();
704 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
705 if (DF->compare(OtherDF)) {
706 cerr << "Dominator Information for " << F.getNameStart() << "\n";
707 cerr << "Pass '" << P.getPassName() << "'\n";
708 cerr << "----- Valid -----\n";
710 cerr << "----- Invalid -----\n";
712 assert (0 && "Invalid dominator info");
716 /// Remove Analysis not preserved by Pass P
717 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
718 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
719 if (AnUsage->getPreservesAll())
722 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
723 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
724 E = AvailableAnalysis.end(); I != E; ) {
725 std::map<AnalysisID, Pass*>::iterator Info = I++;
726 if (!dynamic_cast<ImmutablePass*>(Info->second)
727 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
728 PreservedSet.end()) {
729 // Remove this analysis
730 if (PassDebugging >= Details) {
731 Pass *S = Info->second;
732 cerr << " -- '" << P->getPassName() << "' is not preserving '";
733 cerr << S->getPassName() << "'\n";
735 AvailableAnalysis.erase(Info);
739 // Check inherited analysis also. If P is not preserving analysis
740 // provided by parent manager then remove it here.
741 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
743 if (!InheritedAnalysis[Index])
746 for (std::map<AnalysisID, Pass*>::iterator
747 I = InheritedAnalysis[Index]->begin(),
748 E = InheritedAnalysis[Index]->end(); I != E; ) {
749 std::map<AnalysisID, Pass *>::iterator Info = I++;
750 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
751 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
753 // Remove this analysis
754 InheritedAnalysis[Index]->erase(Info);
759 /// Remove analysis passes that are not used any longer
760 void PMDataManager::removeDeadPasses(Pass *P, const char *Msg,
761 enum PassDebuggingString DBG_STR) {
763 SmallVector<Pass *, 12> DeadPasses;
765 // If this is a on the fly manager then it does not have TPM.
769 TPM->collectLastUses(DeadPasses, P);
771 if (PassDebugging >= Details && !DeadPasses.empty()) {
772 cerr << " -*- '" << P->getPassName();
773 cerr << "' is the last user of following pass instances.";
774 cerr << " Free these instances\n";
777 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
778 E = DeadPasses.end(); I != E; ++I) {
780 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
782 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
783 (*I)->releaseMemory();
784 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
785 if (const PassInfo *PI = (*I)->getPassInfo()) {
786 std::map<AnalysisID, Pass*>::iterator Pos =
787 AvailableAnalysis.find(PI);
789 // It is possible that pass is already removed from the AvailableAnalysis
790 if (Pos != AvailableAnalysis.end())
791 AvailableAnalysis.erase(Pos);
793 // Remove all interfaces this pass implements, for which it is also
794 // listed as the available implementation.
795 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
796 for (unsigned i = 0, e = II.size(); i != e; ++i) {
797 Pos = AvailableAnalysis.find(II[i]);
798 if (Pos != AvailableAnalysis.end() && Pos->second == *I)
799 AvailableAnalysis.erase(Pos);
805 /// Add pass P into the PassVector. Update
806 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
807 void PMDataManager::add(Pass *P,
808 bool ProcessAnalysis) {
810 // This manager is going to manage pass P. Set up analysis resolver
812 AnalysisResolver *AR = new AnalysisResolver(*this);
815 // If a FunctionPass F is the last user of ModulePass info M
816 // then the F's manager, not F, records itself as a last user of M.
817 SmallVector<Pass *, 12> TransferLastUses;
819 if (ProcessAnalysis) {
821 // At the moment, this pass is the last user of all required passes.
822 SmallVector<Pass *, 12> LastUses;
823 SmallVector<Pass *, 8> RequiredPasses;
824 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
826 unsigned PDepth = this->getDepth();
828 collectRequiredAnalysis(RequiredPasses,
829 ReqAnalysisNotAvailable, P);
830 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
831 E = RequiredPasses.end(); I != E; ++I) {
832 Pass *PRequired = *I;
835 assert (PRequired->getResolver() && "Analysis Resolver is not set");
836 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
837 RDepth = DM.getDepth();
839 if (PDepth == RDepth)
840 LastUses.push_back(PRequired);
841 else if (PDepth > RDepth) {
842 // Let the parent claim responsibility of last use
843 TransferLastUses.push_back(PRequired);
844 // Keep track of higher level analysis used by this manager.
845 HigherLevelAnalysis.push_back(PRequired);
847 assert (0 && "Unable to accomodate Required Pass");
850 // Set P as P's last user until someone starts using P.
851 // However, if P is a Pass Manager then it does not need
852 // to record its last user.
853 if (!dynamic_cast<PMDataManager *>(P))
854 LastUses.push_back(P);
855 TPM->setLastUser(LastUses, P);
857 if (!TransferLastUses.empty()) {
858 Pass *My_PM = dynamic_cast<Pass *>(this);
859 TPM->setLastUser(TransferLastUses, My_PM);
860 TransferLastUses.clear();
863 // Now, take care of required analysises that are not available.
864 for (SmallVector<AnalysisID, 8>::iterator
865 I = ReqAnalysisNotAvailable.begin(),
866 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
867 Pass *AnalysisPass = (*I)->createPass();
868 this->addLowerLevelRequiredPass(P, AnalysisPass);
871 // Take a note of analysis required and made available by this pass.
872 // Remove the analysis not preserved by this pass
873 removeNotPreservedAnalysis(P);
874 recordAvailableAnalysis(P);
878 PassVector.push_back(P);
882 /// Populate RP with analysis pass that are required by
883 /// pass P and are available. Populate RP_NotAvail with analysis
884 /// pass that are required by pass P but are not available.
885 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
886 SmallVector<AnalysisID, 8> &RP_NotAvail,
888 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
889 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
890 for (AnalysisUsage::VectorType::const_iterator
891 I = RequiredSet.begin(), E = RequiredSet.end();
894 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
895 RP.push_back(AnalysisPass);
897 RP_NotAvail.push_back(AID);
900 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
901 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
902 E = IDs.end(); I != E; ++I) {
904 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
905 RP.push_back(AnalysisPass);
907 RP_NotAvail.push_back(AID);
911 // All Required analyses should be available to the pass as it runs! Here
912 // we fill in the AnalysisImpls member of the pass so that it can
913 // successfully use the getAnalysis() method to retrieve the
914 // implementations it needs.
916 void PMDataManager::initializeAnalysisImpl(Pass *P) {
917 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
919 for (AnalysisUsage::VectorType::const_iterator
920 I = AnUsage->getRequiredSet().begin(),
921 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
922 Pass *Impl = findAnalysisPass(*I, true);
924 // This may be analysis pass that is initialized on the fly.
925 // If that is not the case then it will raise an assert when it is used.
927 AnalysisResolver *AR = P->getResolver();
928 assert (AR && "Analysis Resolver is not set");
929 AR->addAnalysisImplsPair(*I, Impl);
933 /// Find the pass that implements Analysis AID. If desired pass is not found
934 /// then return NULL.
935 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
937 // Check if AvailableAnalysis map has one entry.
938 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
940 if (I != AvailableAnalysis.end())
943 // Search Parents through TopLevelManager
945 return TPM->findAnalysisPass(AID);
950 // Print list of passes that are last used by P.
951 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
953 SmallVector<Pass *, 12> LUses;
955 // If this is a on the fly manager then it does not have TPM.
959 TPM->collectLastUses(LUses, P);
961 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
962 E = LUses.end(); I != E; ++I) {
963 llvm::cerr << "--" << std::string(Offset*2, ' ');
964 (*I)->dumpPassStructure(0);
968 void PMDataManager::dumpPassArguments() const {
969 for(SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
970 E = PassVector.end(); I != E; ++I) {
971 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
972 PMD->dumpPassArguments();
974 if (const PassInfo *PI = (*I)->getPassInfo())
975 if (!PI->isAnalysisGroup())
976 cerr << " -" << PI->getPassArgument();
980 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
981 enum PassDebuggingString S2,
983 if (PassDebugging < Executions)
985 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
988 cerr << "Executing Pass '" << P->getPassName();
990 case MODIFICATION_MSG:
991 cerr << "Made Modification '" << P->getPassName();
994 cerr << " Freeing Pass '" << P->getPassName();
1000 case ON_BASICBLOCK_MSG:
1001 cerr << "' on BasicBlock '" << Msg << "'...\n";
1003 case ON_FUNCTION_MSG:
1004 cerr << "' on Function '" << Msg << "'...\n";
1007 cerr << "' on Module '" << Msg << "'...\n";
1010 cerr << "' on Loop " << Msg << "'...\n";
1013 cerr << "' on Call Graph " << Msg << "'...\n";
1020 void PMDataManager::dumpRequiredSet(const Pass *P)
1022 if (PassDebugging < Details)
1025 AnalysisUsage analysisUsage;
1026 P->getAnalysisUsage(analysisUsage);
1027 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1030 void PMDataManager::dumpPreservedSet(const Pass *P)
1032 if (PassDebugging < Details)
1035 AnalysisUsage analysisUsage;
1036 P->getAnalysisUsage(analysisUsage);
1037 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1040 void PMDataManager::dumpAnalysisUsage(const char *Msg, const Pass *P,
1041 const AnalysisUsage::VectorType &Set)
1043 assert(PassDebugging >= Details);
1046 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1047 for (unsigned i = 0; i != Set.size(); ++i) {
1049 cerr << " " << Set[i]->getPassName();
1054 /// Add RequiredPass into list of lower level passes required by pass P.
1055 /// RequiredPass is run on the fly by Pass Manager when P requests it
1056 /// through getAnalysis interface.
1057 /// This should be handled by specific pass manager.
1058 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1060 TPM->dumpArguments();
1064 // Module Level pass may required Function Level analysis info
1065 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1066 // to provide this on demand. In that case, in Pass manager terminology,
1067 // module level pass is requiring lower level analysis info managed by
1068 // lower level pass manager.
1070 // When Pass manager is not able to order required analysis info, Pass manager
1071 // checks whether any lower level manager will be able to provide this
1072 // analysis info on demand or not.
1074 cerr << "Unable to schedule '" << RequiredPass->getPassName();
1075 cerr << "' required by '" << P->getPassName() << "'\n";
1077 assert (0 && "Unable to schedule pass");
1081 PMDataManager::~PMDataManager() {
1083 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1084 E = PassVector.end(); I != E; ++I)
1089 //===----------------------------------------------------------------------===//
1090 // NOTE: Is this the right place to define this method ?
1091 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
1092 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
1093 return PM.findAnalysisPass(ID, dir);
1096 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1098 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1101 //===----------------------------------------------------------------------===//
1102 // BBPassManager implementation
1104 /// Execute all of the passes scheduled for execution by invoking
1105 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1106 /// the function, and if so, return true.
1108 BBPassManager::runOnFunction(Function &F) {
1110 if (F.isDeclaration())
1113 bool Changed = doInitialization(F);
1115 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1116 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1117 BasicBlockPass *BP = getContainedPass(Index);
1119 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getNameStart());
1120 dumpRequiredSet(BP);
1122 initializeAnalysisImpl(BP);
1124 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1125 Changed |= BP->runOnBasicBlock(*I);
1126 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1129 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1131 dumpPreservedSet(BP);
1133 verifyPreservedAnalysis(BP);
1134 removeNotPreservedAnalysis(BP);
1135 recordAvailableAnalysis(BP);
1136 removeDeadPasses(BP, I->getNameStart(), ON_BASICBLOCK_MSG);
1139 return Changed |= doFinalization(F);
1142 // Implement doInitialization and doFinalization
1143 inline bool BBPassManager::doInitialization(Module &M) {
1144 bool Changed = false;
1146 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1147 BasicBlockPass *BP = getContainedPass(Index);
1148 Changed |= BP->doInitialization(M);
1154 inline bool BBPassManager::doFinalization(Module &M) {
1155 bool Changed = false;
1157 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1158 BasicBlockPass *BP = getContainedPass(Index);
1159 Changed |= BP->doFinalization(M);
1165 inline bool BBPassManager::doInitialization(Function &F) {
1166 bool Changed = false;
1168 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1169 BasicBlockPass *BP = getContainedPass(Index);
1170 Changed |= BP->doInitialization(F);
1176 inline bool BBPassManager::doFinalization(Function &F) {
1177 bool Changed = false;
1179 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1180 BasicBlockPass *BP = getContainedPass(Index);
1181 Changed |= BP->doFinalization(F);
1188 //===----------------------------------------------------------------------===//
1189 // FunctionPassManager implementation
1191 /// Create new Function pass manager
1192 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1193 FPM = new FunctionPassManagerImpl(0);
1194 // FPM is the top level manager.
1195 FPM->setTopLevelManager(FPM);
1197 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1198 FPM->setResolver(AR);
1203 FunctionPassManager::~FunctionPassManager() {
1207 /// add - Add a pass to the queue of passes to run. This passes
1208 /// ownership of the Pass to the PassManager. When the
1209 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1210 /// there is no need to delete the pass. (TODO delete passes.)
1211 /// This implies that all passes MUST be allocated with 'new'.
1212 void FunctionPassManager::add(Pass *P) {
1216 /// run - Execute all of the passes scheduled for execution. Keep
1217 /// track of whether any of the passes modifies the function, and if
1218 /// so, return true.
1220 bool FunctionPassManager::run(Function &F) {
1222 if (MP->materializeFunction(&F, &errstr)) {
1223 cerr << "Error reading bitcode file: " << errstr << "\n";
1230 /// doInitialization - Run all of the initializers for the function passes.
1232 bool FunctionPassManager::doInitialization() {
1233 return FPM->doInitialization(*MP->getModule());
1236 /// doFinalization - Run all of the finalizers for the function passes.
1238 bool FunctionPassManager::doFinalization() {
1239 return FPM->doFinalization(*MP->getModule());
1242 //===----------------------------------------------------------------------===//
1243 // FunctionPassManagerImpl implementation
1245 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1246 bool Changed = false;
1248 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1249 FPPassManager *FP = getContainedManager(Index);
1250 Changed |= FP->doInitialization(M);
1256 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1257 bool Changed = false;
1259 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1260 FPPassManager *FP = getContainedManager(Index);
1261 Changed |= FP->doFinalization(M);
1267 // Execute all the passes managed by this top level manager.
1268 // Return true if any function is modified by a pass.
1269 bool FunctionPassManagerImpl::run(Function &F) {
1271 bool Changed = false;
1273 TimingInfo::createTheTimeInfo();
1278 initializeAllAnalysisInfo();
1279 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1280 FPPassManager *FP = getContainedManager(Index);
1281 Changed |= FP->runOnFunction(F);
1286 //===----------------------------------------------------------------------===//
1287 // FPPassManager implementation
1289 char FPPassManager::ID = 0;
1290 /// Print passes managed by this manager
1291 void FPPassManager::dumpPassStructure(unsigned Offset) {
1292 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1293 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1294 FunctionPass *FP = getContainedPass(Index);
1295 FP->dumpPassStructure(Offset + 1);
1296 dumpLastUses(FP, Offset+1);
1301 /// Execute all of the passes scheduled for execution by invoking
1302 /// runOnFunction method. Keep track of whether any of the passes modifies
1303 /// the function, and if so, return true.
1304 bool FPPassManager::runOnFunction(Function &F) {
1306 bool Changed = false;
1308 if (F.isDeclaration())
1311 // Collect inherited analysis from Module level pass manager.
1312 populateInheritedAnalysis(TPM->activeStack);
1314 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1315 FunctionPass *FP = getContainedPass(Index);
1317 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1318 dumpRequiredSet(FP);
1320 initializeAnalysisImpl(FP);
1322 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1323 Changed |= FP->runOnFunction(F);
1324 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1327 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1328 dumpPreservedSet(FP);
1330 verifyPreservedAnalysis(FP);
1331 removeNotPreservedAnalysis(FP);
1332 recordAvailableAnalysis(FP);
1333 removeDeadPasses(FP, F.getNameStart(), ON_FUNCTION_MSG);
1335 // If dominator information is available then verify the info if requested.
1336 verifyDomInfo(*FP, F);
1341 bool FPPassManager::runOnModule(Module &M) {
1343 bool Changed = doInitialization(M);
1345 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1346 this->runOnFunction(*I);
1348 return Changed |= doFinalization(M);
1351 inline bool FPPassManager::doInitialization(Module &M) {
1352 bool Changed = false;
1354 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1355 FunctionPass *FP = getContainedPass(Index);
1356 Changed |= FP->doInitialization(M);
1362 inline bool FPPassManager::doFinalization(Module &M) {
1363 bool Changed = false;
1365 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1366 FunctionPass *FP = getContainedPass(Index);
1367 Changed |= FP->doFinalization(M);
1373 //===----------------------------------------------------------------------===//
1374 // MPPassManager implementation
1376 /// Execute all of the passes scheduled for execution by invoking
1377 /// runOnModule method. Keep track of whether any of the passes modifies
1378 /// the module, and if so, return true.
1380 MPPassManager::runOnModule(Module &M) {
1381 bool Changed = false;
1383 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1384 ModulePass *MP = getContainedPass(Index);
1386 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1387 M.getModuleIdentifier().c_str());
1388 dumpRequiredSet(MP);
1390 initializeAnalysisImpl(MP);
1392 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1393 Changed |= MP->runOnModule(M);
1394 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1397 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1398 M.getModuleIdentifier().c_str());
1399 dumpPreservedSet(MP);
1401 verifyPreservedAnalysis(MP);
1402 removeNotPreservedAnalysis(MP);
1403 recordAvailableAnalysis(MP);
1404 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1409 /// Add RequiredPass into list of lower level passes required by pass P.
1410 /// RequiredPass is run on the fly by Pass Manager when P requests it
1411 /// through getAnalysis interface.
1412 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1414 assert (P->getPotentialPassManagerType() == PMT_ModulePassManager
1415 && "Unable to handle Pass that requires lower level Analysis pass");
1416 assert ((P->getPotentialPassManagerType() <
1417 RequiredPass->getPotentialPassManagerType())
1418 && "Unable to handle Pass that requires lower level Analysis pass");
1420 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1422 FPP = new FunctionPassManagerImpl(0);
1423 // FPP is the top level manager.
1424 FPP->setTopLevelManager(FPP);
1426 OnTheFlyManagers[P] = FPP;
1428 FPP->add(RequiredPass);
1430 // Register P as the last user of RequiredPass.
1431 SmallVector<Pass *, 12> LU;
1432 LU.push_back(RequiredPass);
1433 FPP->setLastUser(LU, P);
1436 /// Return function pass corresponding to PassInfo PI, that is
1437 /// required by module pass MP. Instantiate analysis pass, by using
1438 /// its runOnFunction() for function F.
1439 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI,
1441 AnalysisID AID = PI;
1442 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1443 assert (FPP && "Unable to find on the fly pass");
1446 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(AID);
1450 //===----------------------------------------------------------------------===//
1451 // PassManagerImpl implementation
1453 /// run - Execute all of the passes scheduled for execution. Keep track of
1454 /// whether any of the passes modifies the module, and if so, return true.
1455 bool PassManagerImpl::run(Module &M) {
1457 bool Changed = false;
1459 TimingInfo::createTheTimeInfo();
1464 initializeAllAnalysisInfo();
1465 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1466 MPPassManager *MP = getContainedManager(Index);
1467 Changed |= MP->runOnModule(M);
1472 //===----------------------------------------------------------------------===//
1473 // PassManager implementation
1475 /// Create new pass manager
1476 PassManager::PassManager() {
1477 PM = new PassManagerImpl(0);
1478 // PM is the top level manager
1479 PM->setTopLevelManager(PM);
1482 PassManager::~PassManager() {
1486 /// add - Add a pass to the queue of passes to run. This passes ownership of
1487 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1488 /// will be destroyed as well, so there is no need to delete the pass. This
1489 /// implies that all passes MUST be allocated with 'new'.
1491 PassManager::add(Pass *P) {
1495 /// run - Execute all of the passes scheduled for execution. Keep track of
1496 /// whether any of the passes modifies the module, and if so, return true.
1498 PassManager::run(Module &M) {
1502 //===----------------------------------------------------------------------===//
1503 // TimingInfo Class - This class is used to calculate information about the
1504 // amount of time each pass takes to execute. This only happens with
1505 // -time-passes is enabled on the command line.
1507 bool llvm::TimePassesIsEnabled = false;
1508 static cl::opt<bool,true>
1509 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1510 cl::desc("Time each pass, printing elapsed time for each on exit"));
1512 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1513 // a non null value (if the -time-passes option is enabled) or it leaves it
1514 // null. It may be called multiple times.
1515 void TimingInfo::createTheTimeInfo() {
1516 if (!TimePassesIsEnabled || TheTimeInfo) return;
1518 // Constructed the first time this is called, iff -time-passes is enabled.
1519 // This guarantees that the object will be constructed before static globals,
1520 // thus it will be destroyed before them.
1521 static ManagedStatic<TimingInfo> TTI;
1522 TheTimeInfo = &*TTI;
1525 /// If TimingInfo is enabled then start pass timer.
1526 void StartPassTimer(Pass *P) {
1528 TheTimeInfo->passStarted(P);
1531 /// If TimingInfo is enabled then stop pass timer.
1532 void StopPassTimer(Pass *P) {
1534 TheTimeInfo->passEnded(P);
1537 //===----------------------------------------------------------------------===//
1538 // PMStack implementation
1541 // Pop Pass Manager from the stack and clear its analysis info.
1542 void PMStack::pop() {
1544 PMDataManager *Top = this->top();
1545 Top->initializeAnalysisInfo();
1550 // Push PM on the stack and set its top level manager.
1551 void PMStack::push(PMDataManager *PM) {
1553 PMDataManager *Top = NULL;
1554 assert (PM && "Unable to push. Pass Manager expected");
1556 if (this->empty()) {
1561 PMTopLevelManager *TPM = Top->getTopLevelManager();
1563 assert (TPM && "Unable to find top level manager");
1564 TPM->addIndirectPassManager(PM);
1565 PM->setTopLevelManager(TPM);
1571 // Dump content of the pass manager stack.
1572 void PMStack::dump() {
1573 for(std::deque<PMDataManager *>::iterator I = S.begin(),
1574 E = S.end(); I != E; ++I) {
1575 Pass *P = dynamic_cast<Pass *>(*I);
1576 printf("%s ", P->getPassName());
1582 /// Find appropriate Module Pass Manager in the PM Stack and
1583 /// add self into that manager.
1584 void ModulePass::assignPassManager(PMStack &PMS,
1585 PassManagerType PreferredType) {
1587 // Find Module Pass Manager
1588 while(!PMS.empty()) {
1589 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1590 if (TopPMType == PreferredType)
1591 break; // We found desired pass manager
1592 else if (TopPMType > PMT_ModulePassManager)
1593 PMS.pop(); // Pop children pass managers
1597 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1598 PMS.top()->add(this);
1601 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1602 /// in the PM Stack and add self into that manager.
1603 void FunctionPass::assignPassManager(PMStack &PMS,
1604 PassManagerType PreferredType) {
1606 // Find Module Pass Manager
1607 while(!PMS.empty()) {
1608 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1613 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1615 // Create new Function Pass Manager
1617 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1618 PMDataManager *PMD = PMS.top();
1620 // [1] Create new Function Pass Manager
1621 FPP = new FPPassManager(PMD->getDepth() + 1);
1622 FPP->populateInheritedAnalysis(PMS);
1624 // [2] Set up new manager's top level manager
1625 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1626 TPM->addIndirectPassManager(FPP);
1628 // [3] Assign manager to manage this new manager. This may create
1629 // and push new managers into PMS
1630 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1632 // [4] Push new manager into PMS
1636 // Assign FPP as the manager of this pass.
1640 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1641 /// in the PM Stack and add self into that manager.
1642 void BasicBlockPass::assignPassManager(PMStack &PMS,
1643 PassManagerType PreferredType) {
1645 BBPassManager *BBP = NULL;
1647 // Basic Pass Manager is a leaf pass manager. It does not handle
1648 // any other pass manager.
1650 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1652 // If leaf manager is not Basic Block Pass manager then create new
1653 // basic Block Pass manager.
1656 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1657 PMDataManager *PMD = PMS.top();
1659 // [1] Create new Basic Block Manager
1660 BBP = new BBPassManager(PMD->getDepth() + 1);
1662 // [2] Set up new manager's top level manager
1663 // Basic Block Pass Manager does not live by itself
1664 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1665 TPM->addIndirectPassManager(BBP);
1667 // [3] Assign manager to manage this new manager. This may create
1668 // and push new managers into PMS
1669 BBP->assignPassManager(PMS);
1671 // [4] Push new manager into PMS
1675 // Assign BBP as the manager of this pass.
1679 PassManagerBase::~PassManagerBase() {}
1681 /*===-- C Bindings --------------------------------------------------------===*/
1683 LLVMPassManagerRef LLVMCreatePassManager() {
1684 return wrap(new PassManager());
1687 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1688 return wrap(new FunctionPassManager(unwrap(P)));
1691 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1692 return unwrap<PassManager>(PM)->run(*unwrap(M));
1695 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1696 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1699 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1700 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1703 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1704 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1707 void LLVMDisposePassManager(LLVMPassManagerRef PM) {