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);
161 activeStack.handleLastUserOverflow();
166 FPPassManager *getContainedManager(unsigned N) {
167 assert ( N < PassManagers.size() && "Pass number out of range!");
168 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
174 //===----------------------------------------------------------------------===//
177 /// MPPassManager manages ModulePasses and function pass managers.
178 /// It batches all Module passes passes and function pass managers together and
179 /// sequence them to process one module.
180 class MPPassManager : public Pass, public PMDataManager {
183 MPPassManager(int Depth) : PMDataManager(Depth) { }
185 /// run - Execute all of the passes scheduled for execution. Keep track of
186 /// whether any of the passes modifies the module, and if so, return true.
187 bool runOnModule(Module &M);
189 /// Pass Manager itself does not invalidate any analysis info.
190 void getAnalysisUsage(AnalysisUsage &Info) const {
191 Info.setPreservesAll();
194 virtual const char *getPassName() const {
195 return "Module Pass Manager";
198 // Print passes managed by this manager
199 void dumpPassStructure(unsigned Offset) {
200 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
201 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
202 ModulePass *MP = getContainedPass(Index);
203 MP->dumpPassStructure(Offset + 1);
204 dumpLastUses(MP, Offset+1);
208 ModulePass *getContainedPass(unsigned N) {
209 assert ( N < PassVector.size() && "Pass number out of range!");
210 ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
214 virtual PassManagerType getPassManagerType() const {
215 return PMT_ModulePassManager;
219 //===----------------------------------------------------------------------===//
222 /// PassManagerImpl manages MPPassManagers
223 class PassManagerImpl : public Pass,
224 public PMDataManager,
225 public PMTopLevelManager {
229 PassManagerImpl(int Depth) : PMDataManager(Depth),
230 PMTopLevelManager(TLM_Pass) { }
232 /// add - Add a pass to the queue of passes to run. This passes ownership of
233 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
234 /// will be destroyed as well, so there is no need to delete the pass. This
235 /// implies that all passes MUST be allocated with 'new'.
240 /// run - Execute all of the passes scheduled for execution. Keep track of
241 /// whether any of the passes modifies the module, and if so, return true.
244 /// Pass Manager itself does not invalidate any analysis info.
245 void getAnalysisUsage(AnalysisUsage &Info) const {
246 Info.setPreservesAll();
249 inline void addTopLevelPass(Pass *P) {
251 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
253 // P is a immutable pass and it will be managed by this
254 // top level manager. Set up analysis resolver to connect them.
255 AnalysisResolver *AR = new AnalysisResolver(*this);
257 initializeAnalysisImpl(P);
258 addImmutablePass(IP);
259 recordAvailableAnalysis(IP);
261 P->assignPassManager(activeStack);
262 activeStack.handleLastUserOverflow();
267 MPPassManager *getContainedManager(unsigned N) {
268 assert ( N < PassManagers.size() && "Pass number out of range!");
269 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
275 } // End of llvm namespace
279 //===----------------------------------------------------------------------===//
280 // TimingInfo Class - This class is used to calculate information about the
281 // amount of time each pass takes to execute. This only happens when
282 // -time-passes is enabled on the command line.
285 class VISIBILITY_HIDDEN TimingInfo {
286 std::map<Pass*, Timer> TimingData;
290 // Use 'create' member to get this.
291 TimingInfo() : TG("... Pass execution timing report ...") {}
293 // TimingDtor - Print out information about timing information
295 // Delete all of the timers...
297 // TimerGroup is deleted next, printing the report.
300 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
301 // to a non null value (if the -time-passes option is enabled) or it leaves it
302 // null. It may be called multiple times.
303 static void createTheTimeInfo();
305 void passStarted(Pass *P) {
307 if (dynamic_cast<PMDataManager *>(P))
310 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
311 if (I == TimingData.end())
312 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
313 I->second.startTimer();
315 void passEnded(Pass *P) {
317 if (dynamic_cast<PMDataManager *>(P))
320 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
321 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
322 I->second.stopTimer();
326 static TimingInfo *TheTimeInfo;
328 } // End of anon namespace
330 //===----------------------------------------------------------------------===//
331 // PMTopLevelManager implementation
333 /// Initialize top level manager. Create first pass manager.
334 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
337 MPPassManager *MPP = new MPPassManager(1);
338 MPP->setTopLevelManager(this);
340 activeStack.push(MPP);
342 else if (t == TLM_Function) {
343 FPPassManager *FPP = new FPPassManager(1);
344 FPP->setTopLevelManager(this);
346 activeStack.push(FPP);
350 /// Set pass P as the last user of the given analysis passes.
351 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
354 for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
355 E = AnalysisPasses.end(); I != E; ++I) {
358 // If AP is the last user of other passes then make P last user of
360 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
361 LUE = LastUser.end(); LUI != LUE; ++LUI) {
362 if (LUI->second == AP)
363 LastUser[LUI->first] = P;
368 /// Collect passes whose last user is P
369 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
371 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
372 LUE = LastUser.end(); LUI != LUE; ++LUI)
373 if (LUI->second == P)
374 LastUses.push_back(LUI->first);
377 /// Schedule pass P for execution. Make sure that passes required by
378 /// P are run before P is run. Update analysis info maintained by
379 /// the manager. Remove dead passes. This is a recursive function.
380 void PMTopLevelManager::schedulePass(Pass *P) {
382 // TODO : Allocate function manager for this pass, other wise required set
383 // may be inserted into previous function manager
385 // If this Analysis is already requested by one of the previous pass
386 // and it is still available then do not insert new pass in the queue again.
387 if (findAnalysisPass(P->getPassInfo()))
390 AnalysisUsage AnUsage;
391 P->getAnalysisUsage(AnUsage);
392 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
393 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
394 E = RequiredSet.end(); I != E; ++I) {
396 Pass *AnalysisPass = findAnalysisPass(*I);
398 // Schedule this analysis run first.
399 AnalysisPass = (*I)->createPass();
400 schedulePass(AnalysisPass);
404 // Now all required passes are available.
408 /// Find the pass that implements Analysis AID. Search immutable
409 /// passes and all pass managers. If desired pass is not found
410 /// then return NULL.
411 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
414 // Check pass managers
415 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
416 E = PassManagers.end(); P == NULL && I != E; ++I) {
417 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
418 assert(PMD && "This is not a PassManager");
419 P = PMD->findAnalysisPass(AID, false);
422 // Check other pass managers
423 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
424 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
425 P = (*I)->findAnalysisPass(AID, false);
427 for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
428 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
429 const PassInfo *PI = (*I)->getPassInfo();
433 // If Pass not found then check the interfaces implemented by Immutable Pass
435 const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
436 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
444 // Print passes managed by this top level manager.
445 void PMTopLevelManager::dumpPasses() const {
447 if (PassDebugging < Structure)
450 // Print out the immutable passes
451 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
452 ImmutablePasses[i]->dumpPassStructure(0);
455 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
456 E = PassManagers.end(); I != E; ++I)
457 (*I)->dumpPassStructure(1);
460 void PMTopLevelManager::dumpArguments() const {
462 if (PassDebugging < Arguments)
465 cerr << "Pass Arguments: ";
466 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
467 E = PassManagers.end(); I != E; ++I) {
468 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
469 assert(PMD && "This is not a PassManager");
470 PMD->dumpPassArguments();
475 void PMTopLevelManager::initializeAllAnalysisInfo() {
477 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
478 E = PassManagers.end(); I != E; ++I) {
479 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
480 assert(PMD && "This is not a PassManager");
481 PMD->initializeAnalysisInfo();
484 // Initailize other pass managers
485 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
486 E = IndirectPassManagers.end(); I != E; ++I)
487 (*I)->initializeAnalysisInfo();
491 PMTopLevelManager::~PMTopLevelManager() {
492 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
493 E = PassManagers.end(); I != E; ++I)
496 for (std::vector<ImmutablePass *>::iterator
497 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
500 PassManagers.clear();
503 //===----------------------------------------------------------------------===//
504 // PMDataManager implementation
506 /// Return true IFF pass P's required analysis set does not required new
508 bool PMDataManager::manageablePass(Pass *P) {
511 // If this pass is not preserving information that is required by a
512 // pass maintained by higher level pass manager then do not insert
513 // this pass into current manager. Use new manager. For example,
514 // For example, If FunctionPass F is not preserving ModulePass Info M1
515 // that is used by another ModulePass M2 then do not insert F in
516 // current function pass manager.
520 /// Augement AvailableAnalysis by adding analysis made available by pass P.
521 void PMDataManager::recordAvailableAnalysis(Pass *P) {
523 if (const PassInfo *PI = P->getPassInfo()) {
524 AvailableAnalysis[PI] = P;
526 //This pass is the current implementation of all of the interfaces it
527 //implements as well.
528 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
529 for (unsigned i = 0, e = II.size(); i != e; ++i)
530 AvailableAnalysis[II[i]] = P;
534 /// Remove Analyss not preserved by Pass P
535 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
536 AnalysisUsage AnUsage;
537 P->getAnalysisUsage(AnUsage);
539 if (AnUsage.getPreservesAll())
542 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
543 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
544 E = AvailableAnalysis.end(); I != E; ) {
545 std::map<AnalysisID, Pass*>::iterator Info = I++;
546 if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
547 PreservedSet.end()) {
548 // Remove this analysis
549 if (!dynamic_cast<ImmutablePass*>(Info->second))
550 AvailableAnalysis.erase(Info);
555 /// Remove analysis passes that are not used any longer
556 void PMDataManager::removeDeadPasses(Pass *P, std::string &Msg) {
558 std::vector<Pass *> DeadPasses;
559 TPM->collectLastUses(DeadPasses, P);
561 for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
562 E = DeadPasses.end(); I != E; ++I) {
564 std::string Msg1 = " Freeing Pass '";
565 dumpPassInfo(*I, Msg1, Msg);
567 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
568 (*I)->releaseMemory();
569 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
571 std::map<AnalysisID, Pass*>::iterator Pos =
572 AvailableAnalysis.find((*I)->getPassInfo());
574 // It is possible that pass is already removed from the AvailableAnalysis
575 if (Pos != AvailableAnalysis.end())
576 AvailableAnalysis.erase(Pos);
580 /// Add pass P into the PassVector. Update
581 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
582 void PMDataManager::add(Pass *P,
583 bool ProcessAnalysis) {
585 // This manager is going to manage pass P. Set up analysis resolver
587 AnalysisResolver *AR = new AnalysisResolver(*this);
590 if (ProcessAnalysis) {
592 // At the moment, this pass is the last user of all required passes.
593 std::vector<Pass *> LastUses;
594 std::vector<Pass *> RequiredPasses;
595 unsigned PDepth = this->getDepth();
597 collectRequiredAnalysisPasses(RequiredPasses, P);
598 for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
599 E = RequiredPasses.end(); I != E; ++I) {
600 Pass *PRequired = *I;
603 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
604 RDepth = DM.getDepth();
606 if (PDepth == RDepth)
607 LastUses.push_back(PRequired);
608 else if (PDepth > RDepth) {
609 // Let the parent claim responsibility of last use
610 TransferLastUses.push_back(PRequired);
612 // Note : This feature is not yet implemented
614 "Unable to handle Pass that requires lower level Analysis pass");
618 // Set P as P's last user until someone starts using P.
619 // However, if P is a Pass Manager then it does not need
620 // to record its last user.
621 if (!dynamic_cast<PMDataManager *>(P))
622 LastUses.push_back(P);
623 TPM->setLastUser(LastUses, P);
625 // Take a note of analysis required and made available by this pass.
626 // Remove the analysis not preserved by this pass
627 removeNotPreservedAnalysis(P);
628 recordAvailableAnalysis(P);
632 PassVector.push_back(P);
635 /// Populate RequiredPasses with the analysis pass that are required by
637 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
639 AnalysisUsage AnUsage;
640 P->getAnalysisUsage(AnUsage);
641 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
642 for (std::vector<AnalysisID>::const_iterator
643 I = RequiredSet.begin(), E = RequiredSet.end();
645 Pass *AnalysisPass = findAnalysisPass(*I, true);
646 assert (AnalysisPass && "Analysis pass is not available");
647 RP.push_back(AnalysisPass);
650 const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
651 for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
652 E = IDs.end(); I != E; ++I) {
653 Pass *AnalysisPass = findAnalysisPass(*I, true);
654 assert (AnalysisPass && "Analysis pass is not available");
655 RP.push_back(AnalysisPass);
659 // All Required analyses should be available to the pass as it runs! Here
660 // we fill in the AnalysisImpls member of the pass so that it can
661 // successfully use the getAnalysis() method to retrieve the
662 // implementations it needs.
664 void PMDataManager::initializeAnalysisImpl(Pass *P) {
665 AnalysisUsage AnUsage;
666 P->getAnalysisUsage(AnUsage);
668 for (std::vector<const PassInfo *>::const_iterator
669 I = AnUsage.getRequiredSet().begin(),
670 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
671 Pass *Impl = findAnalysisPass(*I, true);
673 assert(0 && "Analysis used but not available!");
674 AnalysisResolver *AR = P->getResolver();
675 AR->addAnalysisImplsPair(*I, Impl);
679 /// Find the pass that implements Analysis AID. If desired pass is not found
680 /// then return NULL.
681 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
683 // Check if AvailableAnalysis map has one entry.
684 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
686 if (I != AvailableAnalysis.end())
689 // Search Parents through TopLevelManager
691 return TPM->findAnalysisPass(AID);
696 // Print list of passes that are last used by P.
697 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
699 std::vector<Pass *> LUses;
701 assert (TPM && "Top Level Manager is missing");
702 TPM->collectLastUses(LUses, P);
704 for (std::vector<Pass *>::iterator I = LUses.begin(),
705 E = LUses.end(); I != E; ++I) {
706 llvm::cerr << "--" << std::string(Offset*2, ' ');
707 (*I)->dumpPassStructure(0);
711 void PMDataManager::dumpPassArguments() const {
712 for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
713 E = PassVector.end(); I != E; ++I) {
714 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
715 PMD->dumpPassArguments();
717 if (const PassInfo *PI = (*I)->getPassInfo())
718 if (!PI->isAnalysisGroup())
719 cerr << " -" << PI->getPassArgument();
723 void PMDataManager:: dumpPassInfo(Pass *P, std::string &Msg1,
724 std::string &Msg2) const {
725 if (PassDebugging < Executions)
727 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
729 cerr << P->getPassName();
733 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
734 const std::vector<AnalysisID> &Set)
736 if (PassDebugging >= Details && !Set.empty()) {
737 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
738 for (unsigned i = 0; i != Set.size(); ++i) {
740 cerr << " " << Set[i]->getPassName();
747 PMDataManager::~PMDataManager() {
749 for (std::vector<Pass *>::iterator I = PassVector.begin(),
750 E = PassVector.end(); I != E; ++I)
756 //===----------------------------------------------------------------------===//
757 // NOTE: Is this the right place to define this method ?
758 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
759 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
760 return PM.findAnalysisPass(ID, dir);
763 //===----------------------------------------------------------------------===//
764 // BBPassManager implementation
766 /// Execute all of the passes scheduled for execution by invoking
767 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
768 /// the function, and if so, return true.
770 BBPassManager::runOnFunction(Function &F) {
772 if (F.isDeclaration())
775 bool Changed = doInitialization(F);
777 std::string Msg1 = "Executing Pass '";
778 std::string Msg3 = "' Made Modification '";
780 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
781 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
782 BasicBlockPass *BP = getContainedPass(Index);
783 AnalysisUsage AnUsage;
784 BP->getAnalysisUsage(AnUsage);
786 std::string Msg2 = "' on BasicBlock '" + (*I).getName() + "'...\n";
787 dumpPassInfo(BP, Msg1, Msg2);
788 dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
790 initializeAnalysisImpl(BP);
792 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
793 Changed |= BP->runOnBasicBlock(*I);
794 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
797 dumpPassInfo(BP, Msg3, Msg2);
798 dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
800 removeNotPreservedAnalysis(BP);
801 recordAvailableAnalysis(BP);
802 removeDeadPasses(BP, Msg2);
804 return Changed |= doFinalization(F);
807 // Implement doInitialization and doFinalization
808 inline bool BBPassManager::doInitialization(Module &M) {
809 bool Changed = false;
811 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
812 BasicBlockPass *BP = getContainedPass(Index);
813 Changed |= BP->doInitialization(M);
819 inline bool BBPassManager::doFinalization(Module &M) {
820 bool Changed = false;
822 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
823 BasicBlockPass *BP = getContainedPass(Index);
824 Changed |= BP->doFinalization(M);
830 inline bool BBPassManager::doInitialization(Function &F) {
831 bool Changed = false;
833 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
834 BasicBlockPass *BP = getContainedPass(Index);
835 Changed |= BP->doInitialization(F);
841 inline bool BBPassManager::doFinalization(Function &F) {
842 bool Changed = false;
844 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
845 BasicBlockPass *BP = getContainedPass(Index);
846 Changed |= BP->doFinalization(F);
853 //===----------------------------------------------------------------------===//
854 // FunctionPassManager implementation
856 /// Create new Function pass manager
857 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
858 FPM = new FunctionPassManagerImpl(0);
859 // FPM is the top level manager.
860 FPM->setTopLevelManager(FPM);
862 PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
863 AnalysisResolver *AR = new AnalysisResolver(*PMD);
864 FPM->setResolver(AR);
869 FunctionPassManager::~FunctionPassManager() {
873 /// add - Add a pass to the queue of passes to run. This passes
874 /// ownership of the Pass to the PassManager. When the
875 /// PassManager_X is destroyed, the pass will be destroyed as well, so
876 /// there is no need to delete the pass. (TODO delete passes.)
877 /// This implies that all passes MUST be allocated with 'new'.
878 void FunctionPassManager::add(Pass *P) {
882 /// run - Execute all of the passes scheduled for execution. Keep
883 /// track of whether any of the passes modifies the function, and if
886 bool FunctionPassManager::run(Function &F) {
888 if (MP->materializeFunction(&F, &errstr)) {
889 cerr << "Error reading bytecode file: " << errstr << "\n";
896 /// doInitialization - Run all of the initializers for the function passes.
898 bool FunctionPassManager::doInitialization() {
899 return FPM->doInitialization(*MP->getModule());
902 /// doFinalization - Run all of the initializers for the function passes.
904 bool FunctionPassManager::doFinalization() {
905 return FPM->doFinalization(*MP->getModule());
908 //===----------------------------------------------------------------------===//
909 // FunctionPassManagerImpl implementation
911 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
912 bool Changed = false;
914 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
915 FPPassManager *FP = getContainedManager(Index);
916 Changed |= FP->doInitialization(M);
922 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
923 bool Changed = false;
925 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
926 FPPassManager *FP = getContainedManager(Index);
927 Changed |= FP->doFinalization(M);
933 // Execute all the passes managed by this top level manager.
934 // Return true if any function is modified by a pass.
935 bool FunctionPassManagerImpl::run(Function &F) {
937 bool Changed = false;
939 TimingInfo::createTheTimeInfo();
944 initializeAllAnalysisInfo();
945 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
946 FPPassManager *FP = getContainedManager(Index);
947 Changed |= FP->runOnFunction(F);
952 //===----------------------------------------------------------------------===//
953 // FPPassManager implementation
955 /// Print passes managed by this manager
956 void FPPassManager::dumpPassStructure(unsigned Offset) {
957 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
958 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
959 FunctionPass *FP = getContainedPass(Index);
960 FP->dumpPassStructure(Offset + 1);
961 dumpLastUses(FP, Offset+1);
966 /// Execute all of the passes scheduled for execution by invoking
967 /// runOnFunction method. Keep track of whether any of the passes modifies
968 /// the function, and if so, return true.
969 bool FPPassManager::runOnFunction(Function &F) {
971 bool Changed = false;
973 if (F.isDeclaration())
976 std::string Msg1 = "Executing Pass '";
977 std::string Msg3 = "' Made Modification '";
979 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
980 FunctionPass *FP = getContainedPass(Index);
982 AnalysisUsage AnUsage;
983 FP->getAnalysisUsage(AnUsage);
985 std::string Msg2 = "' on Function '" + F.getName() + "'...\n";
986 dumpPassInfo(FP, Msg1, Msg2);
987 dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
989 initializeAnalysisImpl(FP);
991 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
992 Changed |= FP->runOnFunction(F);
993 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
996 dumpPassInfo(FP, Msg3, Msg2);
997 dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
999 removeNotPreservedAnalysis(FP);
1000 recordAvailableAnalysis(FP);
1001 removeDeadPasses(FP, Msg2);
1006 bool FPPassManager::runOnModule(Module &M) {
1008 bool Changed = doInitialization(M);
1010 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1011 this->runOnFunction(*I);
1013 return Changed |= doFinalization(M);
1016 inline bool FPPassManager::doInitialization(Module &M) {
1017 bool Changed = false;
1019 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1020 FunctionPass *FP = getContainedPass(Index);
1021 Changed |= FP->doInitialization(M);
1027 inline bool FPPassManager::doFinalization(Module &M) {
1028 bool Changed = false;
1030 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1031 FunctionPass *FP = getContainedPass(Index);
1032 Changed |= FP->doFinalization(M);
1038 //===----------------------------------------------------------------------===//
1039 // MPPassManager implementation
1041 /// Execute all of the passes scheduled for execution by invoking
1042 /// runOnModule method. Keep track of whether any of the passes modifies
1043 /// the module, and if so, return true.
1045 MPPassManager::runOnModule(Module &M) {
1046 bool Changed = false;
1048 std::string Msg1 = "Executing Pass '";
1049 std::string Msg3 = "' Made Modification '";
1051 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1052 ModulePass *MP = getContainedPass(Index);
1054 AnalysisUsage AnUsage;
1055 MP->getAnalysisUsage(AnUsage);
1057 std::string Msg2 = "' on Module '" + M.getModuleIdentifier() + "'...\n";
1058 dumpPassInfo(MP, Msg1, Msg2);
1059 dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1061 initializeAnalysisImpl(MP);
1063 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1064 Changed |= MP->runOnModule(M);
1065 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1068 dumpPassInfo(MP, Msg3, Msg2);
1069 dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1071 removeNotPreservedAnalysis(MP);
1072 recordAvailableAnalysis(MP);
1073 removeDeadPasses(MP, Msg2);
1078 //===----------------------------------------------------------------------===//
1079 // PassManagerImpl implementation
1081 /// run - Execute all of the passes scheduled for execution. Keep track of
1082 /// whether any of the passes modifies the module, and if so, return true.
1083 bool PassManagerImpl::run(Module &M) {
1085 bool Changed = false;
1087 TimingInfo::createTheTimeInfo();
1092 initializeAllAnalysisInfo();
1093 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1094 MPPassManager *MP = getContainedManager(Index);
1095 Changed |= MP->runOnModule(M);
1100 //===----------------------------------------------------------------------===//
1101 // PassManager implementation
1103 /// Create new pass manager
1104 PassManager::PassManager() {
1105 PM = new PassManagerImpl(0);
1106 // PM is the top level manager
1107 PM->setTopLevelManager(PM);
1110 PassManager::~PassManager() {
1114 /// add - Add a pass to the queue of passes to run. This passes ownership of
1115 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1116 /// will be destroyed as well, so there is no need to delete the pass. This
1117 /// implies that all passes MUST be allocated with 'new'.
1119 PassManager::add(Pass *P) {
1123 /// run - Execute all of the passes scheduled for execution. Keep track of
1124 /// whether any of the passes modifies the module, and if so, return true.
1126 PassManager::run(Module &M) {
1130 //===----------------------------------------------------------------------===//
1131 // TimingInfo Class - This class is used to calculate information about the
1132 // amount of time each pass takes to execute. This only happens with
1133 // -time-passes is enabled on the command line.
1135 bool llvm::TimePassesIsEnabled = false;
1136 static cl::opt<bool,true>
1137 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1138 cl::desc("Time each pass, printing elapsed time for each on exit"));
1140 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1141 // a non null value (if the -time-passes option is enabled) or it leaves it
1142 // null. It may be called multiple times.
1143 void TimingInfo::createTheTimeInfo() {
1144 if (!TimePassesIsEnabled || TheTimeInfo) return;
1146 // Constructed the first time this is called, iff -time-passes is enabled.
1147 // This guarantees that the object will be constructed before static globals,
1148 // thus it will be destroyed before them.
1149 static ManagedStatic<TimingInfo> TTI;
1150 TheTimeInfo = &*TTI;
1153 /// If TimingInfo is enabled then start pass timer.
1154 void StartPassTimer(Pass *P) {
1156 TheTimeInfo->passStarted(P);
1159 /// If TimingInfo is enabled then stop pass timer.
1160 void StopPassTimer(Pass *P) {
1162 TheTimeInfo->passEnded(P);
1165 //===----------------------------------------------------------------------===//
1166 // PMStack implementation
1169 // Pop Pass Manager from the stack and clear its analysis info.
1170 void PMStack::pop() {
1172 PMDataManager *Top = this->top();
1173 Top->initializeAnalysisInfo();
1178 // Push PM on the stack and set its top level manager.
1179 void PMStack::push(Pass *P) {
1181 PMDataManager *Top = NULL;
1182 PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1183 assert (PM && "Unable to push. Pass Manager expected");
1185 if (this->empty()) {
1190 PMTopLevelManager *TPM = Top->getTopLevelManager();
1192 assert (TPM && "Unable to find top level manager");
1193 TPM->addIndirectPassManager(PM);
1194 PM->setTopLevelManager(TPM);
1197 AnalysisResolver *AR = new AnalysisResolver(*Top);
1203 // Dump content of the pass manager stack.
1204 void PMStack::dump() {
1205 for(std::deque<PMDataManager *>::iterator I = S.begin(),
1206 E = S.end(); I != E; ++I) {
1207 Pass *P = dynamic_cast<Pass *>(*I);
1208 printf ("%s ", P->getPassName());
1214 // Walk Pass Manager stack and set LastUse markers if any
1215 // manager is transfering this priviledge to its parent manager
1216 void PMStack::handleLastUserOverflow() {
1218 for(PMStack::iterator I = this->begin(), E = this->end(); I != E;) {
1220 PMDataManager *Child = *I++;
1222 PMDataManager *Parent = *I++;
1223 PMTopLevelManager *TPM = Parent->getTopLevelManager();
1224 std::vector<Pass *> &TLU = Child->getTransferredLastUses();
1226 Pass *P = dynamic_cast<Pass *>(Parent);
1227 TPM->setLastUser(TLU, P);
1234 /// Find appropriate Module Pass Manager in the PM Stack and
1235 /// add self into that manager.
1236 void ModulePass::assignPassManager(PMStack &PMS,
1237 PassManagerType PreferredType) {
1239 // Find Module Pass Manager
1240 while(!PMS.empty()) {
1241 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1242 if (TopPMType == PreferredType)
1243 break; // We found desired pass manager
1244 else if (TopPMType > PMT_ModulePassManager)
1245 PMS.pop(); // Pop children pass managers
1250 PMS.top()->add(this);
1253 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1254 /// in the PM Stack and add self into that manager.
1255 void FunctionPass::assignPassManager(PMStack &PMS,
1256 PassManagerType PreferredType) {
1258 // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1259 while(!PMS.empty()) {
1260 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1265 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1267 // Create new Function Pass Manager
1269 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1270 PMDataManager *PMD = PMS.top();
1272 // [1] Create new Function Pass Manager
1273 FPP = new FPPassManager(PMD->getDepth() + 1);
1275 // [2] Set up new manager's top level manager
1276 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1277 TPM->addIndirectPassManager(FPP);
1279 // [3] Assign manager to manage this new manager. This may create
1280 // and push new managers into PMS
1281 Pass *P = dynamic_cast<Pass *>(FPP);
1283 // If Call Graph Pass Manager is active then use it to manage
1284 // this new Function Pass manager.
1285 if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1286 P->assignPassManager(PMS, PMT_CallGraphPassManager);
1288 P->assignPassManager(PMS);
1290 // [4] Push new manager into PMS
1294 // Assign FPP as the manager of this pass.
1298 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1299 /// in the PM Stack and add self into that manager.
1300 void BasicBlockPass::assignPassManager(PMStack &PMS,
1301 PassManagerType PreferredType) {
1303 BBPassManager *BBP = NULL;
1305 // Basic Pass Manager is a leaf pass manager. It does not handle
1306 // any other pass manager.
1308 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1311 // If leaf manager is not Basic Block Pass manager then create new
1312 // basic Block Pass manager.
1315 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1316 PMDataManager *PMD = PMS.top();
1318 // [1] Create new Basic Block Manager
1319 BBP = new BBPassManager(PMD->getDepth() + 1);
1321 // [2] Set up new manager's top level manager
1322 // Basic Block Pass Manager does not live by itself
1323 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1324 TPM->addIndirectPassManager(BBP);
1326 // [3] Assign manager to manage this new manager. This may create
1327 // and push new managers into PMS
1328 Pass *P = dynamic_cast<Pass *>(BBP);
1329 P->assignPassManager(PMS);
1331 // [4] Push new manager into PMS
1335 // Assign BBP as the manager of this pass.