1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source 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"
26 // See PassManagers.h for Pass Manager infrastructure overview.
30 //===----------------------------------------------------------------------===//
31 // Pass debugging information. Often it is useful to find out what pass is
32 // running when a crash occurs in a utility. When this library is compiled with
33 // debugging on, a command line option (--debug-pass) is enabled that causes the
34 // pass name to be printed before it executes.
37 // Different debug levels that can be enabled...
39 None, Arguments, Structure, Executions, Details
42 static cl::opt<enum PassDebugLevel>
43 PassDebugging("debug-pass", cl::Hidden,
44 cl::desc("Print PassManager debugging information"),
46 clEnumVal(None , "disable debug output"),
47 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
48 clEnumVal(Structure , "print pass structure before run()"),
49 clEnumVal(Executions, "print pass name before it is executed"),
50 clEnumVal(Details , "print pass details when it is executed"),
52 } // End of llvm namespace
56 //===----------------------------------------------------------------------===//
59 /// BBPassManager manages BasicBlockPass. It batches all the
60 /// pass together and sequence them to process one basic block before
61 /// processing next basic block.
62 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
66 BBPassManager(int Depth) : PMDataManager(Depth) { }
68 /// Execute all of the passes scheduled for execution. Keep track of
69 /// whether any of the passes modifies the function, and if so, return true.
70 bool runOnFunction(Function &F);
72 /// Pass Manager itself does not invalidate any analysis info.
73 void getAnalysisUsage(AnalysisUsage &Info) const {
74 Info.setPreservesAll();
77 bool doInitialization(Module &M);
78 bool doInitialization(Function &F);
79 bool doFinalization(Module &M);
80 bool doFinalization(Function &F);
82 virtual const char *getPassName() const {
83 return "BasicBlock Pass Manager";
86 // Print passes managed by this manager
87 void dumpPassStructure(unsigned Offset) {
88 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
89 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
90 BasicBlockPass *BP = getContainedPass(Index);
91 BP->dumpPassStructure(Offset + 1);
92 dumpLastUses(BP, Offset+1);
96 BasicBlockPass *getContainedPass(unsigned N) {
97 assert ( N < PassVector.size() && "Pass number out of range!");
98 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
102 virtual PassManagerType getPassManagerType() const {
103 return PMT_BasicBlockPassManager;
111 //===----------------------------------------------------------------------===//
112 // FunctionPassManagerImpl
114 /// FunctionPassManagerImpl manages FPPassManagers
115 class FunctionPassManagerImpl : public Pass,
116 public PMDataManager,
117 public PMTopLevelManager {
120 FunctionPassManagerImpl(int Depth) : PMDataManager(Depth),
121 PMTopLevelManager(TLM_Function) { }
123 /// add - Add a pass to the queue of passes to run. This passes ownership of
124 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
125 /// will be destroyed as well, so there is no need to delete the pass. This
126 /// implies that all passes MUST be allocated with 'new'.
131 /// run - Execute all of the passes scheduled for execution. Keep track of
132 /// whether any of the passes modifies the module, and if so, return true.
133 bool run(Function &F);
135 /// doInitialization - Run all of the initializers for the function passes.
137 bool doInitialization(Module &M);
139 /// doFinalization - Run all of the initializers for the function passes.
141 bool doFinalization(Module &M);
143 /// Pass Manager itself does not invalidate any analysis info.
144 void getAnalysisUsage(AnalysisUsage &Info) const {
145 Info.setPreservesAll();
148 inline void addTopLevelPass(Pass *P) {
150 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
152 // P is a immutable pass and it will be managed by this
153 // top level manager. Set up analysis resolver to connect them.
154 AnalysisResolver *AR = new AnalysisResolver(*this);
156 initializeAnalysisImpl(P);
157 addImmutablePass(IP);
158 recordAvailableAnalysis(IP);
160 P->assignPassManager(activeStack);
165 FPPassManager *getContainedManager(unsigned N) {
166 assert ( N < PassManagers.size() && "Pass number out of range!");
167 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
173 //===----------------------------------------------------------------------===//
176 /// MPPassManager manages ModulePasses and function pass managers.
177 /// It batches all Module passes passes and function pass managers together and
178 /// sequence them to process one module.
179 class MPPassManager : public Pass, public PMDataManager {
182 MPPassManager(int Depth) : PMDataManager(Depth) { }
184 // Delete on the fly managers.
185 virtual ~MPPassManager() {
186 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
187 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
189 FunctionPassManagerImpl *FPP = I->second;
194 /// run - Execute all of the passes scheduled for execution. Keep track of
195 /// whether any of the passes modifies the module, and if so, return true.
196 bool runOnModule(Module &M);
198 /// Pass Manager itself does not invalidate any analysis info.
199 void getAnalysisUsage(AnalysisUsage &Info) const {
200 Info.setPreservesAll();
203 /// Add RequiredPass into list of lower level passes required by pass P.
204 /// RequiredPass is run on the fly by Pass Manager when P requests it
205 /// through getAnalysis interface.
206 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
208 /// Return function pass corresponding to PassInfo PI, that is
209 /// required by module pass MP. Instantiate analysis pass, by using
210 /// its runOnFunction() for function F.
211 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
213 virtual const char *getPassName() const {
214 return "Module Pass Manager";
217 // Print passes managed by this manager
218 void dumpPassStructure(unsigned Offset) {
219 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
220 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
221 ModulePass *MP = getContainedPass(Index);
222 MP->dumpPassStructure(Offset + 1);
223 if (FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP])
224 FPP->dumpPassStructure(Offset + 2);
225 dumpLastUses(MP, Offset+1);
229 ModulePass *getContainedPass(unsigned N) {
230 assert ( N < PassVector.size() && "Pass number out of range!");
231 ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
235 virtual PassManagerType getPassManagerType() const {
236 return PMT_ModulePassManager;
240 /// Collection of on the fly FPPassManagers. These managers manage
241 /// function passes that are required by module passes.
242 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
245 //===----------------------------------------------------------------------===//
248 /// PassManagerImpl manages MPPassManagers
249 class PassManagerImpl : public Pass,
250 public PMDataManager,
251 public PMTopLevelManager {
255 PassManagerImpl(int Depth) : PMDataManager(Depth),
256 PMTopLevelManager(TLM_Pass) { }
258 /// add - Add a pass to the queue of passes to run. This passes ownership of
259 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
260 /// will be destroyed as well, so there is no need to delete the pass. This
261 /// implies that all passes MUST be allocated with 'new'.
266 /// run - Execute all of the passes scheduled for execution. Keep track of
267 /// whether any of the passes modifies the module, and if so, return true.
270 /// Pass Manager itself does not invalidate any analysis info.
271 void getAnalysisUsage(AnalysisUsage &Info) const {
272 Info.setPreservesAll();
275 inline void addTopLevelPass(Pass *P) {
277 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
279 // P is a immutable pass and it will be managed by this
280 // top level manager. Set up analysis resolver to connect them.
281 AnalysisResolver *AR = new AnalysisResolver(*this);
283 initializeAnalysisImpl(P);
284 addImmutablePass(IP);
285 recordAvailableAnalysis(IP);
287 P->assignPassManager(activeStack);
292 MPPassManager *getContainedManager(unsigned N) {
293 assert ( N < PassManagers.size() && "Pass number out of range!");
294 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
300 } // End of llvm namespace
304 //===----------------------------------------------------------------------===//
305 // TimingInfo Class - This class is used to calculate information about the
306 // amount of time each pass takes to execute. This only happens when
307 // -time-passes is enabled on the command line.
310 class VISIBILITY_HIDDEN TimingInfo {
311 std::map<Pass*, Timer> TimingData;
315 // Use 'create' member to get this.
316 TimingInfo() : TG("... Pass execution timing report ...") {}
318 // TimingDtor - Print out information about timing information
320 // Delete all of the timers...
322 // TimerGroup is deleted next, printing the report.
325 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
326 // to a non null value (if the -time-passes option is enabled) or it leaves it
327 // null. It may be called multiple times.
328 static void createTheTimeInfo();
330 void passStarted(Pass *P) {
332 if (dynamic_cast<PMDataManager *>(P))
335 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
336 if (I == TimingData.end())
337 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
338 I->second.startTimer();
340 void passEnded(Pass *P) {
342 if (dynamic_cast<PMDataManager *>(P))
345 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
346 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
347 I->second.stopTimer();
351 static TimingInfo *TheTimeInfo;
353 } // End of anon namespace
355 //===----------------------------------------------------------------------===//
356 // PMTopLevelManager implementation
358 /// Initialize top level manager. Create first pass manager.
359 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
362 MPPassManager *MPP = new MPPassManager(1);
363 MPP->setTopLevelManager(this);
365 activeStack.push(MPP);
367 else if (t == TLM_Function) {
368 FPPassManager *FPP = new FPPassManager(1);
369 FPP->setTopLevelManager(this);
371 activeStack.push(FPP);
375 /// Set pass P as the last user of the given analysis passes.
376 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
379 for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
380 E = AnalysisPasses.end(); I != E; ++I) {
387 // If AP is the last user of other passes then make P last user of
389 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
390 LUE = LastUser.end(); LUI != LUE; ++LUI) {
391 if (LUI->second == AP)
392 LastUser[LUI->first] = P;
397 /// Collect passes whose last user is P
398 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
400 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
401 LUE = LastUser.end(); LUI != LUE; ++LUI)
402 if (LUI->second == P)
403 LastUses.push_back(LUI->first);
406 /// Schedule pass P for execution. Make sure that passes required by
407 /// P are run before P is run. Update analysis info maintained by
408 /// the manager. Remove dead passes. This is a recursive function.
409 void PMTopLevelManager::schedulePass(Pass *P) {
411 // TODO : Allocate function manager for this pass, other wise required set
412 // may be inserted into previous function manager
414 // If this Analysis is already requested by one of the previous pass
415 // and it is still available then do not insert new pass in the queue again.
416 if (findAnalysisPass(P->getPassInfo()))
419 // Give pass a chance to prepare the stage.
420 P->preparePassManager(activeStack);
422 AnalysisUsage AnUsage;
423 P->getAnalysisUsage(AnUsage);
424 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
425 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
426 E = RequiredSet.end(); I != E; ++I) {
428 Pass *AnalysisPass = findAnalysisPass(*I);
430 AnalysisPass = (*I)->createPass();
431 // Schedule this analysis run first only if it is not a lower level
432 // analysis pass. Lower level analsyis passes are run on the fly.
433 if (P->getPotentialPassManagerType () >=
434 AnalysisPass->getPotentialPassManagerType())
435 schedulePass(AnalysisPass);
441 // Now all required passes are available.
445 /// Find the pass that implements Analysis AID. Search immutable
446 /// passes and all pass managers. If desired pass is not found
447 /// then return NULL.
448 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
451 // Check pass managers
452 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
453 E = PassManagers.end(); P == NULL && I != E; ++I) {
454 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
455 assert(PMD && "This is not a PassManager");
456 P = PMD->findAnalysisPass(AID, false);
459 // Check other pass managers
460 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
461 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
462 P = (*I)->findAnalysisPass(AID, false);
464 for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
465 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
466 const PassInfo *PI = (*I)->getPassInfo();
470 // If Pass not found then check the interfaces implemented by Immutable Pass
472 const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
473 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
481 // Print passes managed by this top level manager.
482 void PMTopLevelManager::dumpPasses() const {
484 if (PassDebugging < Structure)
487 // Print out the immutable passes
488 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
489 ImmutablePasses[i]->dumpPassStructure(0);
492 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
493 E = PassManagers.end(); I != E; ++I)
494 (*I)->dumpPassStructure(1);
497 void PMTopLevelManager::dumpArguments() const {
499 if (PassDebugging < Arguments)
502 cerr << "Pass Arguments: ";
503 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
504 E = PassManagers.end(); I != E; ++I) {
505 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
506 assert(PMD && "This is not a PassManager");
507 PMD->dumpPassArguments();
512 void PMTopLevelManager::initializeAllAnalysisInfo() {
514 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
515 E = PassManagers.end(); I != E; ++I) {
516 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
517 assert(PMD && "This is not a PassManager");
518 PMD->initializeAnalysisInfo();
521 // Initailize other pass managers
522 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
523 E = IndirectPassManagers.end(); I != E; ++I)
524 (*I)->initializeAnalysisInfo();
528 PMTopLevelManager::~PMTopLevelManager() {
529 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
530 E = PassManagers.end(); I != E; ++I)
533 for (std::vector<ImmutablePass *>::iterator
534 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
537 PassManagers.clear();
540 //===----------------------------------------------------------------------===//
541 // PMDataManager implementation
543 /// Return true IFF pass P's required analysis set does not required new
545 bool PMDataManager::manageablePass(Pass *P) {
548 // If this pass is not preserving information that is required by a
549 // pass maintained by higher level pass manager then do not insert
550 // this pass into current manager. Use new manager. For example,
551 // For example, If FunctionPass F is not preserving ModulePass Info M1
552 // that is used by another ModulePass M2 then do not insert F in
553 // current function pass manager.
557 /// Augement AvailableAnalysis by adding analysis made available by pass P.
558 void PMDataManager::recordAvailableAnalysis(Pass *P) {
560 if (const PassInfo *PI = P->getPassInfo()) {
561 AvailableAnalysis[PI] = P;
563 //This pass is the current implementation of all of the interfaces it
564 //implements as well.
565 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
566 for (unsigned i = 0, e = II.size(); i != e; ++i)
567 AvailableAnalysis[II[i]] = P;
571 // Return true if P preserves high level analysis used by other
572 // passes managed by this manager
573 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
575 AnalysisUsage AnUsage;
576 P->getAnalysisUsage(AnUsage);
578 if (AnUsage.getPreservesAll())
581 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
582 for (std::vector<Pass *>::iterator I = HigherLevelAnalysis.begin(),
583 E = HigherLevelAnalysis.end(); I != E; ++I) {
585 if (!dynamic_cast<ImmutablePass*>(P1)
586 && std::find(PreservedSet.begin(), PreservedSet.end(), P1->getPassInfo()) ==
594 /// Remove Analyss not preserved by Pass P
595 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
596 AnalysisUsage AnUsage;
597 P->getAnalysisUsage(AnUsage);
599 if (AnUsage.getPreservesAll())
602 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
603 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
604 E = AvailableAnalysis.end(); I != E; ) {
605 std::map<AnalysisID, Pass*>::iterator Info = I++;
606 if (!dynamic_cast<ImmutablePass*>(Info->second)
607 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
609 // Remove this analysis
610 AvailableAnalysis.erase(Info);
613 // Check inherited analysis also. If P is not preserving analysis
614 // provided by parent manager then remove it here.
615 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
617 if (!InheritedAnalysis[Index])
620 for (std::map<AnalysisID, Pass*>::iterator
621 I = InheritedAnalysis[Index]->begin(),
622 E = InheritedAnalysis[Index]->end(); I != E; ) {
623 std::map<AnalysisID, Pass *>::iterator Info = I++;
624 if (!dynamic_cast<ImmutablePass*>(Info->second)
625 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
627 // Remove this analysis
628 InheritedAnalysis[Index]->erase(Info);
634 /// Remove analysis passes that are not used any longer
635 void PMDataManager::removeDeadPasses(Pass *P, std::string Msg,
636 enum PassDebuggingString DBG_STR) {
638 std::vector<Pass *> DeadPasses;
640 // If this is a on the fly manager then it does not have TPM.
644 TPM->collectLastUses(DeadPasses, P);
646 for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
647 E = DeadPasses.end(); I != E; ++I) {
649 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
651 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
652 (*I)->releaseMemory();
653 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
655 std::map<AnalysisID, Pass*>::iterator Pos =
656 AvailableAnalysis.find((*I)->getPassInfo());
658 // It is possible that pass is already removed from the AvailableAnalysis
659 if (Pos != AvailableAnalysis.end())
660 AvailableAnalysis.erase(Pos);
664 /// Add pass P into the PassVector. Update
665 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
666 void PMDataManager::add(Pass *P,
667 bool ProcessAnalysis) {
669 // This manager is going to manage pass P. Set up analysis resolver
671 AnalysisResolver *AR = new AnalysisResolver(*this);
674 // If a FunctionPass F is the last user of ModulePass info M
675 // then the F's manager, not F, records itself as a last user of M.
676 std::vector<Pass *> TransferLastUses;
678 if (ProcessAnalysis) {
680 // At the moment, this pass is the last user of all required passes.
681 std::vector<Pass *> LastUses;
682 SmallVector<Pass *, 8> RequiredPasses;
683 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
685 unsigned PDepth = this->getDepth();
687 collectRequiredAnalysis(RequiredPasses,
688 ReqAnalysisNotAvailable, P);
689 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
690 E = RequiredPasses.end(); I != E; ++I) {
691 Pass *PRequired = *I;
694 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
695 RDepth = DM.getDepth();
697 if (PDepth == RDepth)
698 LastUses.push_back(PRequired);
699 else if (PDepth > RDepth) {
700 // Let the parent claim responsibility of last use
701 TransferLastUses.push_back(PRequired);
702 // Keep track of higher level analysis used by this manager.
703 HigherLevelAnalysis.push_back(PRequired);
705 assert (0 && "Unable to accomodate Required Pass");
708 // Set P as P's last user until someone starts using P.
709 // However, if P is a Pass Manager then it does not need
710 // to record its last user.
711 if (!dynamic_cast<PMDataManager *>(P))
712 LastUses.push_back(P);
713 TPM->setLastUser(LastUses, P);
715 if (!TransferLastUses.empty()) {
716 Pass *My_PM = dynamic_cast<Pass *>(this);
717 TPM->setLastUser(TransferLastUses, My_PM);
718 TransferLastUses.clear();
721 // Now, take care of required analysises that are not available.
722 for (SmallVector<AnalysisID, 8>::iterator
723 I = ReqAnalysisNotAvailable.begin(),
724 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
725 Pass *AnalysisPass = (*I)->createPass();
726 this->addLowerLevelRequiredPass(P, AnalysisPass);
729 // Take a note of analysis required and made available by this pass.
730 // Remove the analysis not preserved by this pass
731 removeNotPreservedAnalysis(P);
732 recordAvailableAnalysis(P);
736 PassVector.push_back(P);
740 /// Populate RP with analysis pass that are required by
741 /// pass P and are available. Populate RP_NotAvail with analysis
742 /// pass that are required by pass P but are not available.
743 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
744 SmallVector<AnalysisID, 8> &RP_NotAvail,
746 AnalysisUsage AnUsage;
747 P->getAnalysisUsage(AnUsage);
748 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
749 for (std::vector<AnalysisID>::const_iterator
750 I = RequiredSet.begin(), E = RequiredSet.end();
753 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
754 RP.push_back(AnalysisPass);
756 RP_NotAvail.push_back(AID);
759 const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
760 for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
761 E = IDs.end(); I != E; ++I) {
763 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
764 RP.push_back(AnalysisPass);
766 RP_NotAvail.push_back(AID);
770 // All Required analyses should be available to the pass as it runs! Here
771 // we fill in the AnalysisImpls member of the pass so that it can
772 // successfully use the getAnalysis() method to retrieve the
773 // implementations it needs.
775 void PMDataManager::initializeAnalysisImpl(Pass *P) {
776 AnalysisUsage AnUsage;
777 P->getAnalysisUsage(AnUsage);
779 for (std::vector<const PassInfo *>::const_iterator
780 I = AnUsage.getRequiredSet().begin(),
781 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
782 Pass *Impl = findAnalysisPass(*I, true);
784 // This may be analysis pass that is initialized on the fly.
785 // If that is not the case then it will raise an assert when it is used.
787 AnalysisResolver *AR = P->getResolver();
788 AR->addAnalysisImplsPair(*I, Impl);
792 /// Find the pass that implements Analysis AID. If desired pass is not found
793 /// then return NULL.
794 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
796 // Check if AvailableAnalysis map has one entry.
797 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
799 if (I != AvailableAnalysis.end())
802 // Search Parents through TopLevelManager
804 return TPM->findAnalysisPass(AID);
809 // Print list of passes that are last used by P.
810 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
812 std::vector<Pass *> LUses;
814 // If this is a on the fly manager then it does not have TPM.
818 TPM->collectLastUses(LUses, P);
820 for (std::vector<Pass *>::iterator I = LUses.begin(),
821 E = LUses.end(); I != E; ++I) {
822 llvm::cerr << "--" << std::string(Offset*2, ' ');
823 (*I)->dumpPassStructure(0);
827 void PMDataManager::dumpPassArguments() const {
828 for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
829 E = PassVector.end(); I != E; ++I) {
830 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
831 PMD->dumpPassArguments();
833 if (const PassInfo *PI = (*I)->getPassInfo())
834 if (!PI->isAnalysisGroup())
835 cerr << " -" << PI->getPassArgument();
839 void PMDataManager:: dumpPassInfo(Pass *P, enum PassDebuggingString S1,
840 enum PassDebuggingString S2,
842 if (PassDebugging < Executions)
844 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
847 cerr << "Executing Pass '" << P->getPassName();
849 case MODIFICATION_MSG:
850 cerr << "' Made Modification '" << P->getPassName();
853 cerr << " Freeing Pass '" << P->getPassName();
859 case ON_BASICBLOCK_MSG:
860 cerr << "' on BasicBlock '" << Msg << "...\n";
862 case ON_FUNCTION_MSG:
863 cerr << "' on Function '" << Msg << "...\n";
866 cerr << "' on Module '" << Msg << "...\n";
869 cerr << "' on Loop " << Msg << "...\n";
872 cerr << "' on Call Graph " << Msg << "...\n";
879 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
880 const std::vector<AnalysisID> &Set)
882 if (PassDebugging >= Details && !Set.empty()) {
883 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
884 for (unsigned i = 0; i != Set.size(); ++i) {
886 cerr << " " << Set[i]->getPassName();
893 PMDataManager::~PMDataManager() {
895 for (std::vector<Pass *>::iterator I = PassVector.begin(),
896 E = PassVector.end(); I != E; ++I)
902 //===----------------------------------------------------------------------===//
903 // NOTE: Is this the right place to define this method ?
904 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
905 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
906 return PM.findAnalysisPass(ID, dir);
909 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
911 return PM.getOnTheFlyPass(P, AnalysisPI, F);
914 //===----------------------------------------------------------------------===//
915 // BBPassManager implementation
917 /// Execute all of the passes scheduled for execution by invoking
918 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
919 /// the function, and if so, return true.
921 BBPassManager::runOnFunction(Function &F) {
923 if (F.isDeclaration())
926 bool Changed = doInitialization(F);
928 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
929 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
930 BasicBlockPass *BP = getContainedPass(Index);
931 AnalysisUsage AnUsage;
932 BP->getAnalysisUsage(AnUsage);
934 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
935 dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
937 initializeAnalysisImpl(BP);
939 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
940 Changed |= BP->runOnBasicBlock(*I);
941 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
944 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
945 dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
947 removeNotPreservedAnalysis(BP);
948 recordAvailableAnalysis(BP);
949 removeDeadPasses(BP, (*I).getName(), ON_BASICBLOCK_MSG);
952 return Changed |= doFinalization(F);
955 // Implement doInitialization and doFinalization
956 inline bool BBPassManager::doInitialization(Module &M) {
957 bool Changed = false;
959 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
960 BasicBlockPass *BP = getContainedPass(Index);
961 Changed |= BP->doInitialization(M);
967 inline bool BBPassManager::doFinalization(Module &M) {
968 bool Changed = false;
970 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
971 BasicBlockPass *BP = getContainedPass(Index);
972 Changed |= BP->doFinalization(M);
978 inline bool BBPassManager::doInitialization(Function &F) {
979 bool Changed = false;
981 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
982 BasicBlockPass *BP = getContainedPass(Index);
983 Changed |= BP->doInitialization(F);
989 inline bool BBPassManager::doFinalization(Function &F) {
990 bool Changed = false;
992 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
993 BasicBlockPass *BP = getContainedPass(Index);
994 Changed |= BP->doFinalization(F);
1001 //===----------------------------------------------------------------------===//
1002 // FunctionPassManager implementation
1004 /// Create new Function pass manager
1005 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1006 FPM = new FunctionPassManagerImpl(0);
1007 // FPM is the top level manager.
1008 FPM->setTopLevelManager(FPM);
1010 PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
1011 AnalysisResolver *AR = new AnalysisResolver(*PMD);
1012 FPM->setResolver(AR);
1017 FunctionPassManager::~FunctionPassManager() {
1021 /// add - Add a pass to the queue of passes to run. This passes
1022 /// ownership of the Pass to the PassManager. When the
1023 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1024 /// there is no need to delete the pass. (TODO delete passes.)
1025 /// This implies that all passes MUST be allocated with 'new'.
1026 void FunctionPassManager::add(Pass *P) {
1030 /// run - Execute all of the passes scheduled for execution. Keep
1031 /// track of whether any of the passes modifies the function, and if
1032 /// so, return true.
1034 bool FunctionPassManager::run(Function &F) {
1036 if (MP->materializeFunction(&F, &errstr)) {
1037 cerr << "Error reading bytecode file: " << errstr << "\n";
1044 /// doInitialization - Run all of the initializers for the function passes.
1046 bool FunctionPassManager::doInitialization() {
1047 return FPM->doInitialization(*MP->getModule());
1050 /// doFinalization - Run all of the initializers for the function passes.
1052 bool FunctionPassManager::doFinalization() {
1053 return FPM->doFinalization(*MP->getModule());
1056 //===----------------------------------------------------------------------===//
1057 // FunctionPassManagerImpl implementation
1059 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1060 bool Changed = false;
1062 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1063 FPPassManager *FP = getContainedManager(Index);
1064 Changed |= FP->doInitialization(M);
1070 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1071 bool Changed = false;
1073 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1074 FPPassManager *FP = getContainedManager(Index);
1075 Changed |= FP->doFinalization(M);
1081 // Execute all the passes managed by this top level manager.
1082 // Return true if any function is modified by a pass.
1083 bool FunctionPassManagerImpl::run(Function &F) {
1085 bool Changed = false;
1087 TimingInfo::createTheTimeInfo();
1092 initializeAllAnalysisInfo();
1093 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1094 FPPassManager *FP = getContainedManager(Index);
1095 Changed |= FP->runOnFunction(F);
1100 //===----------------------------------------------------------------------===//
1101 // FPPassManager implementation
1103 /// Print passes managed by this manager
1104 void FPPassManager::dumpPassStructure(unsigned Offset) {
1105 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1106 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1107 FunctionPass *FP = getContainedPass(Index);
1108 FP->dumpPassStructure(Offset + 1);
1109 dumpLastUses(FP, Offset+1);
1114 /// Execute all of the passes scheduled for execution by invoking
1115 /// runOnFunction method. Keep track of whether any of the passes modifies
1116 /// the function, and if so, return true.
1117 bool FPPassManager::runOnFunction(Function &F) {
1119 bool Changed = false;
1121 if (F.isDeclaration())
1124 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1125 FunctionPass *FP = getContainedPass(Index);
1127 AnalysisUsage AnUsage;
1128 FP->getAnalysisUsage(AnUsage);
1130 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1131 dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1133 initializeAnalysisImpl(FP);
1135 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1136 Changed |= FP->runOnFunction(F);
1137 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1140 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1141 dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1143 removeNotPreservedAnalysis(FP);
1144 recordAvailableAnalysis(FP);
1145 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1150 bool FPPassManager::runOnModule(Module &M) {
1152 bool Changed = doInitialization(M);
1154 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1155 this->runOnFunction(*I);
1157 return Changed |= doFinalization(M);
1160 inline bool FPPassManager::doInitialization(Module &M) {
1161 bool Changed = false;
1163 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1164 FunctionPass *FP = getContainedPass(Index);
1165 Changed |= FP->doInitialization(M);
1171 inline bool FPPassManager::doFinalization(Module &M) {
1172 bool Changed = false;
1174 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1175 FunctionPass *FP = getContainedPass(Index);
1176 Changed |= FP->doFinalization(M);
1182 //===----------------------------------------------------------------------===//
1183 // MPPassManager implementation
1185 /// Execute all of the passes scheduled for execution by invoking
1186 /// runOnModule method. Keep track of whether any of the passes modifies
1187 /// the module, and if so, return true.
1189 MPPassManager::runOnModule(Module &M) {
1190 bool Changed = false;
1192 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1193 ModulePass *MP = getContainedPass(Index);
1195 AnalysisUsage AnUsage;
1196 MP->getAnalysisUsage(AnUsage);
1198 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1199 dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1201 initializeAnalysisImpl(MP);
1203 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1204 Changed |= MP->runOnModule(M);
1205 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1208 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1209 M.getModuleIdentifier());
1210 dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1212 removeNotPreservedAnalysis(MP);
1213 recordAvailableAnalysis(MP);
1214 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1219 /// Add RequiredPass into list of lower level passes required by pass P.
1220 /// RequiredPass is run on the fly by Pass Manager when P requests it
1221 /// through getAnalysis interface.
1222 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1224 assert (P->getPotentialPassManagerType() == PMT_ModulePassManager
1225 && "Unable to handle Pass that requires lower level Analysis pass");
1226 assert ((P->getPotentialPassManagerType() <
1227 RequiredPass->getPotentialPassManagerType())
1228 && "Unable to handle Pass that requires lower level Analysis pass");
1230 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1232 FPP = new FunctionPassManagerImpl(0);
1233 // FPP is the top level manager.
1234 FPP->setTopLevelManager(FPP);
1236 OnTheFlyManagers[P] = FPP;
1238 FPP->add(RequiredPass);
1240 // Register P as the last user of RequiredPass.
1241 std::vector<Pass *> LU;
1242 LU.push_back(RequiredPass);
1243 FPP->setLastUser(LU, P);
1246 /// Return function pass corresponding to PassInfo PI, that is
1247 /// required by module pass MP. Instantiate analysis pass, by using
1248 /// its runOnFunction() for function F.
1249 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI,
1251 AnalysisID AID = PI;
1252 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1253 assert (FPP && "Unable to find on the fly pass");
1256 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(AID);
1260 //===----------------------------------------------------------------------===//
1261 // PassManagerImpl implementation
1263 /// run - Execute all of the passes scheduled for execution. Keep track of
1264 /// whether any of the passes modifies the module, and if so, return true.
1265 bool PassManagerImpl::run(Module &M) {
1267 bool Changed = false;
1269 TimingInfo::createTheTimeInfo();
1274 initializeAllAnalysisInfo();
1275 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1276 MPPassManager *MP = getContainedManager(Index);
1277 Changed |= MP->runOnModule(M);
1282 //===----------------------------------------------------------------------===//
1283 // PassManager implementation
1285 /// Create new pass manager
1286 PassManager::PassManager() {
1287 PM = new PassManagerImpl(0);
1288 // PM is the top level manager
1289 PM->setTopLevelManager(PM);
1292 PassManager::~PassManager() {
1296 /// add - Add a pass to the queue of passes to run. This passes ownership of
1297 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1298 /// will be destroyed as well, so there is no need to delete the pass. This
1299 /// implies that all passes MUST be allocated with 'new'.
1301 PassManager::add(Pass *P) {
1305 /// run - Execute all of the passes scheduled for execution. Keep track of
1306 /// whether any of the passes modifies the module, and if so, return true.
1308 PassManager::run(Module &M) {
1312 //===----------------------------------------------------------------------===//
1313 // TimingInfo Class - This class is used to calculate information about the
1314 // amount of time each pass takes to execute. This only happens with
1315 // -time-passes is enabled on the command line.
1317 bool llvm::TimePassesIsEnabled = false;
1318 static cl::opt<bool,true>
1319 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1320 cl::desc("Time each pass, printing elapsed time for each on exit"));
1322 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1323 // a non null value (if the -time-passes option is enabled) or it leaves it
1324 // null. It may be called multiple times.
1325 void TimingInfo::createTheTimeInfo() {
1326 if (!TimePassesIsEnabled || TheTimeInfo) return;
1328 // Constructed the first time this is called, iff -time-passes is enabled.
1329 // This guarantees that the object will be constructed before static globals,
1330 // thus it will be destroyed before them.
1331 static ManagedStatic<TimingInfo> TTI;
1332 TheTimeInfo = &*TTI;
1335 /// If TimingInfo is enabled then start pass timer.
1336 void StartPassTimer(Pass *P) {
1338 TheTimeInfo->passStarted(P);
1341 /// If TimingInfo is enabled then stop pass timer.
1342 void StopPassTimer(Pass *P) {
1344 TheTimeInfo->passEnded(P);
1347 //===----------------------------------------------------------------------===//
1348 // PMStack implementation
1351 // Pop Pass Manager from the stack and clear its analysis info.
1352 void PMStack::pop() {
1354 PMDataManager *Top = this->top();
1355 Top->initializeAnalysisInfo();
1360 // Push PM on the stack and set its top level manager.
1361 void PMStack::push(Pass *P) {
1363 PMDataManager *Top = NULL;
1364 PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1365 assert (PM && "Unable to push. Pass Manager expected");
1367 if (this->empty()) {
1372 PMTopLevelManager *TPM = Top->getTopLevelManager();
1374 assert (TPM && "Unable to find top level manager");
1375 TPM->addIndirectPassManager(PM);
1376 PM->setTopLevelManager(TPM);
1379 AnalysisResolver *AR = new AnalysisResolver(*Top);
1385 // Dump content of the pass manager stack.
1386 void PMStack::dump() {
1387 for(std::deque<PMDataManager *>::iterator I = S.begin(),
1388 E = S.end(); I != E; ++I) {
1389 Pass *P = dynamic_cast<Pass *>(*I);
1390 printf ("%s ", P->getPassName());
1396 /// Find appropriate Module Pass Manager in the PM Stack and
1397 /// add self into that manager.
1398 void ModulePass::assignPassManager(PMStack &PMS,
1399 PassManagerType PreferredType) {
1401 // Find Module Pass Manager
1402 while(!PMS.empty()) {
1403 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1404 if (TopPMType == PreferredType)
1405 break; // We found desired pass manager
1406 else if (TopPMType > PMT_ModulePassManager)
1407 PMS.pop(); // Pop children pass managers
1412 PMS.top()->add(this);
1415 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1416 /// in the PM Stack and add self into that manager.
1417 void FunctionPass::assignPassManager(PMStack &PMS,
1418 PassManagerType PreferredType) {
1420 // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1421 while(!PMS.empty()) {
1422 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1427 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1429 // Create new Function Pass Manager
1431 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1432 PMDataManager *PMD = PMS.top();
1434 // [1] Create new Function Pass Manager
1435 FPP = new FPPassManager(PMD->getDepth() + 1);
1437 // [2] Set up new manager's top level manager
1438 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1439 TPM->addIndirectPassManager(FPP);
1441 // [3] Assign manager to manage this new manager. This may create
1442 // and push new managers into PMS
1443 Pass *P = dynamic_cast<Pass *>(FPP);
1445 // If Call Graph Pass Manager is active then use it to manage
1446 // this new Function Pass manager.
1447 if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1448 P->assignPassManager(PMS, PMT_CallGraphPassManager);
1450 P->assignPassManager(PMS);
1452 // [4] Push new manager into PMS
1456 // Assign FPP as the manager of this pass.
1460 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1461 /// in the PM Stack and add self into that manager.
1462 void BasicBlockPass::assignPassManager(PMStack &PMS,
1463 PassManagerType PreferredType) {
1465 BBPassManager *BBP = NULL;
1467 // Basic Pass Manager is a leaf pass manager. It does not handle
1468 // any other pass manager.
1470 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1473 // If leaf manager is not Basic Block Pass manager then create new
1474 // basic Block Pass manager.
1477 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1478 PMDataManager *PMD = PMS.top();
1480 // [1] Create new Basic Block Manager
1481 BBP = new BBPassManager(PMD->getDepth() + 1);
1483 // [2] Set up new manager's top level manager
1484 // Basic Block Pass Manager does not live by itself
1485 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1486 TPM->addIndirectPassManager(BBP);
1488 // [3] Assign manager to manage this new manager. This may create
1489 // and push new managers into PMS
1490 Pass *P = dynamic_cast<Pass *>(BBP);
1491 P->assignPassManager(PMS);
1493 // [4] Push new manager into PMS
1497 // Assign BBP as the manager of this pass.