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"
25 // See PassManagers.h for Pass Manager infrastructure overview.
29 //===----------------------------------------------------------------------===//
30 // Pass debugging information. Often it is useful to find out what pass is
31 // running when a crash occurs in a utility. When this library is compiled with
32 // debugging on, a command line option (--debug-pass) is enabled that causes the
33 // pass name to be printed before it executes.
36 // Different debug levels that can be enabled...
38 None, Arguments, Structure, Executions, Details
41 static cl::opt<enum PassDebugLevel>
42 PassDebugging("debug-pass", cl::Hidden,
43 cl::desc("Print PassManager debugging information"),
45 clEnumVal(None , "disable debug output"),
46 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
47 clEnumVal(Structure , "print pass structure before run()"),
48 clEnumVal(Executions, "print pass name before it is executed"),
49 clEnumVal(Details , "print pass details when it is executed"),
51 } // End of llvm namespace
55 //===----------------------------------------------------------------------===//
58 /// BBPassManager manages BasicBlockPass. It batches all the
59 /// pass together and sequence them to process one basic block before
60 /// processing next basic block.
61 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
65 BBPassManager(int Depth) : PMDataManager(Depth) { }
67 /// Execute all of the passes scheduled for execution. Keep track of
68 /// whether any of the passes modifies the function, and if so, return true.
69 bool runOnFunction(Function &F);
71 /// Pass Manager itself does not invalidate any analysis info.
72 void getAnalysisUsage(AnalysisUsage &Info) const {
73 Info.setPreservesAll();
76 bool doInitialization(Module &M);
77 bool doInitialization(Function &F);
78 bool doFinalization(Module &M);
79 bool doFinalization(Function &F);
81 virtual const char *getPassName() const {
82 return "BasicBlock Pass Manager";
85 // Print passes managed by this manager
86 void dumpPassStructure(unsigned Offset) {
87 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
88 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
89 BasicBlockPass *BP = getContainedPass(Index);
90 BP->dumpPassStructure(Offset + 1);
91 dumpLastUses(BP, Offset+1);
95 BasicBlockPass *getContainedPass(unsigned N) {
96 assert ( N < PassVector.size() && "Pass number out of range!");
97 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
101 virtual PassManagerType getPassManagerType() {
102 return PMT_BasicBlockPassManager;
110 //===----------------------------------------------------------------------===//
111 // FunctionPassManagerImpl
113 /// FunctionPassManagerImpl manages FPPassManagers
114 class FunctionPassManagerImpl : public Pass,
115 public PMDataManager,
116 public PMTopLevelManager {
119 FunctionPassManagerImpl(int Depth) : PMDataManager(Depth),
120 PMTopLevelManager(TLM_Function) { }
122 /// add - Add a pass to the queue of passes to run. This passes ownership of
123 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
124 /// will be destroyed as well, so there is no need to delete the pass. This
125 /// implies that all passes MUST be allocated with 'new'.
130 /// run - Execute all of the passes scheduled for execution. Keep track of
131 /// whether any of the passes modifies the module, and if so, return true.
132 bool run(Function &F);
134 /// doInitialization - Run all of the initializers for the function passes.
136 bool doInitialization(Module &M);
138 /// doFinalization - Run all of the initializers for the function passes.
140 bool doFinalization(Module &M);
142 /// Pass Manager itself does not invalidate any analysis info.
143 void getAnalysisUsage(AnalysisUsage &Info) const {
144 Info.setPreservesAll();
147 inline void addTopLevelPass(Pass *P) {
149 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
151 // P is a immutable pass and it will be managed by this
152 // top level manager. Set up analysis resolver to connect them.
153 AnalysisResolver *AR = new AnalysisResolver(*this);
155 initializeAnalysisImpl(P);
156 addImmutablePass(IP);
157 recordAvailableAnalysis(IP);
159 P->assignPassManager(activeStack);
160 activeStack.handleLastUserOverflow();
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 /// run - Execute all of the passes scheduled for execution. Keep track of
185 /// whether any of the passes modifies the module, and if so, return true.
186 bool runOnModule(Module &M);
188 /// Pass Manager itself does not invalidate any analysis info.
189 void getAnalysisUsage(AnalysisUsage &Info) const {
190 Info.setPreservesAll();
193 virtual const char *getPassName() const {
194 return "Module Pass Manager";
197 // Print passes managed by this manager
198 void dumpPassStructure(unsigned Offset) {
199 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
200 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
201 ModulePass *MP = getContainedPass(Index);
202 MP->dumpPassStructure(Offset + 1);
203 dumpLastUses(MP, Offset+1);
207 ModulePass *getContainedPass(unsigned N) {
208 assert ( N < PassVector.size() && "Pass number out of range!");
209 ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
213 virtual PassManagerType getPassManagerType() { return PMT_ModulePassManager; }
216 //===----------------------------------------------------------------------===//
219 /// PassManagerImpl manages MPPassManagers
220 class PassManagerImpl : public Pass,
221 public PMDataManager,
222 public PMTopLevelManager {
226 PassManagerImpl(int Depth) : PMDataManager(Depth),
227 PMTopLevelManager(TLM_Pass) { }
229 /// add - Add a pass to the queue of passes to run. This passes ownership of
230 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
231 /// will be destroyed as well, so there is no need to delete the pass. This
232 /// implies that all passes MUST be allocated with 'new'.
237 /// run - Execute all of the passes scheduled for execution. Keep track of
238 /// whether any of the passes modifies the module, and if so, return true.
241 /// Pass Manager itself does not invalidate any analysis info.
242 void getAnalysisUsage(AnalysisUsage &Info) const {
243 Info.setPreservesAll();
246 inline void addTopLevelPass(Pass *P) {
248 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
250 // P is a immutable pass and it will be managed by this
251 // top level manager. Set up analysis resolver to connect them.
252 AnalysisResolver *AR = new AnalysisResolver(*this);
254 initializeAnalysisImpl(P);
255 addImmutablePass(IP);
256 recordAvailableAnalysis(IP);
258 P->assignPassManager(activeStack);
259 activeStack.handleLastUserOverflow();
264 MPPassManager *getContainedManager(unsigned N) {
265 assert ( N < PassManagers.size() && "Pass number out of range!");
266 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
272 } // End of llvm namespace
276 //===----------------------------------------------------------------------===//
277 // TimingInfo Class - This class is used to calculate information about the
278 // amount of time each pass takes to execute. This only happens when
279 // -time-passes is enabled on the command line.
282 class VISIBILITY_HIDDEN TimingInfo {
283 std::map<Pass*, Timer> TimingData;
287 // Use 'create' member to get this.
288 TimingInfo() : TG("... Pass execution timing report ...") {}
290 // TimingDtor - Print out information about timing information
292 // Delete all of the timers...
294 // TimerGroup is deleted next, printing the report.
297 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
298 // to a non null value (if the -time-passes option is enabled) or it leaves it
299 // null. It may be called multiple times.
300 static void createTheTimeInfo();
302 void passStarted(Pass *P) {
304 if (dynamic_cast<PMDataManager *>(P))
307 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
308 if (I == TimingData.end())
309 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
310 I->second.startTimer();
312 void passEnded(Pass *P) {
314 if (dynamic_cast<PMDataManager *>(P))
317 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
318 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
319 I->second.stopTimer();
323 static TimingInfo *TheTimeInfo;
325 } // End of anon namespace
327 //===----------------------------------------------------------------------===//
328 // PMTopLevelManager implementation
330 /// Initialize top level manager. Create first pass manager.
331 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
334 MPPassManager *MPP = new MPPassManager(1);
335 MPP->setTopLevelManager(this);
337 activeStack.push(MPP);
339 else if (t == TLM_Function) {
340 FPPassManager *FPP = new FPPassManager(1);
341 FPP->setTopLevelManager(this);
343 activeStack.push(FPP);
347 /// Set pass P as the last user of the given analysis passes.
348 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
351 for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
352 E = AnalysisPasses.end(); I != E; ++I) {
355 // If AP is the last user of other passes then make P last user of
357 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
358 LUE = LastUser.end(); LUI != LUE; ++LUI) {
359 if (LUI->second == AP)
360 LastUser[LUI->first] = P;
365 /// Collect passes whose last user is P
366 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
368 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
369 LUE = LastUser.end(); LUI != LUE; ++LUI)
370 if (LUI->second == P)
371 LastUses.push_back(LUI->first);
374 /// Schedule pass P for execution. Make sure that passes required by
375 /// P are run before P is run. Update analysis info maintained by
376 /// the manager. Remove dead passes. This is a recursive function.
377 void PMTopLevelManager::schedulePass(Pass *P) {
379 // TODO : Allocate function manager for this pass, other wise required set
380 // may be inserted into previous function manager
382 // If this Analysis is already requested by one of the previous pass
383 // and it is still available then do not insert new pass in the queue again.
384 if (findAnalysisPass(P->getPassInfo()))
387 AnalysisUsage AnUsage;
388 P->getAnalysisUsage(AnUsage);
389 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
390 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
391 E = RequiredSet.end(); I != E; ++I) {
393 Pass *AnalysisPass = findAnalysisPass(*I);
395 // Schedule this analysis run first.
396 AnalysisPass = (*I)->createPass();
397 schedulePass(AnalysisPass);
401 // Now all required passes are available.
405 /// Find the pass that implements Analysis AID. Search immutable
406 /// passes and all pass managers. If desired pass is not found
407 /// then return NULL.
408 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
411 // Check pass managers
412 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
413 E = PassManagers.end(); P == NULL && I != E; ++I) {
414 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
415 assert(PMD && "This is not a PassManager");
416 P = PMD->findAnalysisPass(AID, false);
419 // Check other pass managers
420 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
421 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
422 P = (*I)->findAnalysisPass(AID, false);
424 for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
425 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
426 const PassInfo *PI = (*I)->getPassInfo();
430 // If Pass not found then check the interfaces implemented by Immutable Pass
432 const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
433 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
441 // Print passes managed by this top level manager.
442 void PMTopLevelManager::dumpPasses() const {
444 if (PassDebugging < Structure)
447 // Print out the immutable passes
448 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
449 ImmutablePasses[i]->dumpPassStructure(0);
452 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
453 E = PassManagers.end(); I != E; ++I)
454 (*I)->dumpPassStructure(1);
457 void PMTopLevelManager::dumpArguments() const {
459 if (PassDebugging < Arguments)
462 cerr << "Pass Arguments: ";
463 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
464 E = PassManagers.end(); I != E; ++I) {
465 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
466 assert(PMD && "This is not a PassManager");
467 PMD->dumpPassArguments();
472 void PMTopLevelManager::initializeAllAnalysisInfo() {
474 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
475 E = PassManagers.end(); I != E; ++I) {
476 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
477 assert(PMD && "This is not a PassManager");
478 PMD->initializeAnalysisInfo();
481 // Initailize other pass managers
482 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
483 E = IndirectPassManagers.end(); I != E; ++I)
484 (*I)->initializeAnalysisInfo();
488 PMTopLevelManager::~PMTopLevelManager() {
489 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
490 E = PassManagers.end(); I != E; ++I)
493 for (std::vector<ImmutablePass *>::iterator
494 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
497 PassManagers.clear();
500 //===----------------------------------------------------------------------===//
501 // PMDataManager implementation
503 /// Return true IFF pass P's required analysis set does not required new
505 bool PMDataManager::manageablePass(Pass *P) {
508 // If this pass is not preserving information that is required by a
509 // pass maintained by higher level pass manager then do not insert
510 // this pass into current manager. Use new manager. For example,
511 // For example, If FunctionPass F is not preserving ModulePass Info M1
512 // that is used by another ModulePass M2 then do not insert F in
513 // current function pass manager.
517 /// Augement AvailableAnalysis by adding analysis made available by pass P.
518 void PMDataManager::recordAvailableAnalysis(Pass *P) {
520 if (const PassInfo *PI = P->getPassInfo()) {
521 AvailableAnalysis[PI] = P;
523 //This pass is the current implementation of all of the interfaces it
524 //implements as well.
525 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
526 for (unsigned i = 0, e = II.size(); i != e; ++i)
527 AvailableAnalysis[II[i]] = P;
531 /// Remove Analyss not preserved by Pass P
532 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
533 AnalysisUsage AnUsage;
534 P->getAnalysisUsage(AnUsage);
536 if (AnUsage.getPreservesAll())
539 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
540 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
541 E = AvailableAnalysis.end(); I != E; ) {
542 std::map<AnalysisID, Pass*>::iterator Info = I++;
543 if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
544 PreservedSet.end()) {
545 // Remove this analysis
546 if (!dynamic_cast<ImmutablePass*>(Info->second))
547 AvailableAnalysis.erase(Info);
552 /// Remove analysis passes that are not used any longer
553 void PMDataManager::removeDeadPasses(Pass *P, std::string &Msg) {
555 std::vector<Pass *> DeadPasses;
556 TPM->collectLastUses(DeadPasses, P);
558 for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
559 E = DeadPasses.end(); I != E; ++I) {
561 std::string Msg1 = " Freeing Pass '";
562 dumpPassInfo(*I, Msg1, Msg);
564 if (TheTimeInfo) TheTimeInfo->passStarted(P);
565 (*I)->releaseMemory();
566 if (TheTimeInfo) TheTimeInfo->passEnded(P);
568 std::map<AnalysisID, Pass*>::iterator Pos =
569 AvailableAnalysis.find((*I)->getPassInfo());
571 // It is possible that pass is already removed from the AvailableAnalysis
572 if (Pos != AvailableAnalysis.end())
573 AvailableAnalysis.erase(Pos);
577 /// Add pass P into the PassVector. Update
578 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
579 void PMDataManager::add(Pass *P,
580 bool ProcessAnalysis) {
582 // This manager is going to manage pass P. Set up analysis resolver
584 AnalysisResolver *AR = new AnalysisResolver(*this);
587 if (ProcessAnalysis) {
589 // At the moment, this pass is the last user of all required passes.
590 std::vector<Pass *> LastUses;
591 std::vector<Pass *> RequiredPasses;
592 unsigned PDepth = this->getDepth();
594 collectRequiredAnalysisPasses(RequiredPasses, P);
595 for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
596 E = RequiredPasses.end(); I != E; ++I) {
597 Pass *PRequired = *I;
600 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
601 RDepth = DM.getDepth();
603 if (PDepth == RDepth)
604 LastUses.push_back(PRequired);
605 else if (PDepth > RDepth) {
606 // Let the parent claim responsibility of last use
607 TransferLastUses.push_back(PRequired);
609 // Note : This feature is not yet implemented
611 "Unable to handle Pass that requires lower level Analysis pass");
615 // Set P as P's last user until someone starts using P.
616 // However, if P is a Pass Manager then it does not need
617 // to record its last user.
618 if (!dynamic_cast<PMDataManager *>(P))
619 LastUses.push_back(P);
620 TPM->setLastUser(LastUses, P);
622 // Take a note of analysis required and made available by this pass.
623 // Remove the analysis not preserved by this pass
624 removeNotPreservedAnalysis(P);
625 recordAvailableAnalysis(P);
629 PassVector.push_back(P);
632 /// Populate RequiredPasses with the analysis pass that are required by
634 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
636 AnalysisUsage AnUsage;
637 P->getAnalysisUsage(AnUsage);
638 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
639 for (std::vector<AnalysisID>::const_iterator
640 I = RequiredSet.begin(), E = RequiredSet.end();
642 Pass *AnalysisPass = findAnalysisPass(*I, true);
643 assert (AnalysisPass && "Analysis pass is not available");
644 RP.push_back(AnalysisPass);
647 const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
648 for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
649 E = IDs.end(); I != E; ++I) {
650 Pass *AnalysisPass = findAnalysisPass(*I, true);
651 assert (AnalysisPass && "Analysis pass is not available");
652 RP.push_back(AnalysisPass);
656 // All Required analyses should be available to the pass as it runs! Here
657 // we fill in the AnalysisImpls member of the pass so that it can
658 // successfully use the getAnalysis() method to retrieve the
659 // implementations it needs.
661 void PMDataManager::initializeAnalysisImpl(Pass *P) {
662 AnalysisUsage AnUsage;
663 P->getAnalysisUsage(AnUsage);
665 for (std::vector<const PassInfo *>::const_iterator
666 I = AnUsage.getRequiredSet().begin(),
667 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
668 Pass *Impl = findAnalysisPass(*I, true);
670 assert(0 && "Analysis used but not available!");
671 AnalysisResolver *AR = P->getResolver();
672 AR->addAnalysisImplsPair(*I, Impl);
676 /// Find the pass that implements Analysis AID. If desired pass is not found
677 /// then return NULL.
678 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
680 // Check if AvailableAnalysis map has one entry.
681 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
683 if (I != AvailableAnalysis.end())
686 // Search Parents through TopLevelManager
688 return TPM->findAnalysisPass(AID);
693 // Print list of passes that are last used by P.
694 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
696 std::vector<Pass *> LUses;
698 assert (TPM && "Top Level Manager is missing");
699 TPM->collectLastUses(LUses, P);
701 for (std::vector<Pass *>::iterator I = LUses.begin(),
702 E = LUses.end(); I != E; ++I) {
703 llvm::cerr << "--" << std::string(Offset*2, ' ');
704 (*I)->dumpPassStructure(0);
708 void PMDataManager::dumpPassArguments() const {
709 for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
710 E = PassVector.end(); I != E; ++I) {
711 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
712 PMD->dumpPassArguments();
714 if (const PassInfo *PI = (*I)->getPassInfo())
715 if (!PI->isAnalysisGroup())
716 cerr << " -" << PI->getPassArgument();
720 void PMDataManager:: dumpPassInfo(Pass *P, std::string &Msg1,
721 std::string &Msg2) const {
722 if (PassDebugging < Executions)
724 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
726 cerr << P->getPassName();
730 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
731 const std::vector<AnalysisID> &Set)
733 if (PassDebugging >= Details && !Set.empty()) {
734 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
735 for (unsigned i = 0; i != Set.size(); ++i) {
737 cerr << " " << Set[i]->getPassName();
744 PMDataManager::~PMDataManager() {
746 for (std::vector<Pass *>::iterator I = PassVector.begin(),
747 E = PassVector.end(); I != E; ++I)
753 //===----------------------------------------------------------------------===//
754 // NOTE: Is this the right place to define this method ?
755 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
756 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
757 return PM.findAnalysisPass(ID, dir);
760 //===----------------------------------------------------------------------===//
761 // BBPassManager implementation
763 /// Execute all of the passes scheduled for execution by invoking
764 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
765 /// the function, and if so, return true.
767 BBPassManager::runOnFunction(Function &F) {
769 if (F.isDeclaration())
772 bool Changed = doInitialization(F);
774 std::string Msg1 = "Executing Pass '";
775 std::string Msg3 = "' Made Modification '";
777 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
778 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
779 BasicBlockPass *BP = getContainedPass(Index);
780 AnalysisUsage AnUsage;
781 BP->getAnalysisUsage(AnUsage);
783 std::string Msg2 = "' on BasicBlock '" + (*I).getName() + "'...\n";
784 dumpPassInfo(BP, Msg1, Msg2);
785 dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
787 initializeAnalysisImpl(BP);
789 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
790 Changed |= BP->runOnBasicBlock(*I);
791 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
794 dumpPassInfo(BP, Msg3, Msg2);
795 dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
797 removeNotPreservedAnalysis(BP);
798 recordAvailableAnalysis(BP);
799 removeDeadPasses(BP, Msg2);
801 return Changed |= doFinalization(F);
804 // Implement doInitialization and doFinalization
805 inline bool BBPassManager::doInitialization(Module &M) {
806 bool Changed = false;
808 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
809 BasicBlockPass *BP = getContainedPass(Index);
810 Changed |= BP->doInitialization(M);
816 inline bool BBPassManager::doFinalization(Module &M) {
817 bool Changed = false;
819 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
820 BasicBlockPass *BP = getContainedPass(Index);
821 Changed |= BP->doFinalization(M);
827 inline bool BBPassManager::doInitialization(Function &F) {
828 bool Changed = false;
830 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
831 BasicBlockPass *BP = getContainedPass(Index);
832 Changed |= BP->doInitialization(F);
838 inline bool BBPassManager::doFinalization(Function &F) {
839 bool Changed = false;
841 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
842 BasicBlockPass *BP = getContainedPass(Index);
843 Changed |= BP->doFinalization(F);
850 //===----------------------------------------------------------------------===//
851 // FunctionPassManager implementation
853 /// Create new Function pass manager
854 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
855 FPM = new FunctionPassManagerImpl(0);
856 // FPM is the top level manager.
857 FPM->setTopLevelManager(FPM);
859 PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
860 AnalysisResolver *AR = new AnalysisResolver(*PMD);
861 FPM->setResolver(AR);
866 FunctionPassManager::~FunctionPassManager() {
870 /// add - Add a pass to the queue of passes to run. This passes
871 /// ownership of the Pass to the PassManager. When the
872 /// PassManager_X is destroyed, the pass will be destroyed as well, so
873 /// there is no need to delete the pass. (TODO delete passes.)
874 /// This implies that all passes MUST be allocated with 'new'.
875 void FunctionPassManager::add(Pass *P) {
879 /// run - Execute all of the passes scheduled for execution. Keep
880 /// track of whether any of the passes modifies the function, and if
883 bool FunctionPassManager::run(Function &F) {
885 if (MP->materializeFunction(&F, &errstr)) {
886 cerr << "Error reading bytecode file: " << errstr << "\n";
893 /// doInitialization - Run all of the initializers for the function passes.
895 bool FunctionPassManager::doInitialization() {
896 return FPM->doInitialization(*MP->getModule());
899 /// doFinalization - Run all of the initializers for the function passes.
901 bool FunctionPassManager::doFinalization() {
902 return FPM->doFinalization(*MP->getModule());
905 //===----------------------------------------------------------------------===//
906 // FunctionPassManagerImpl implementation
908 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
909 bool Changed = false;
911 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
912 FPPassManager *FP = getContainedManager(Index);
913 Changed |= FP->doInitialization(M);
919 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
920 bool Changed = false;
922 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
923 FPPassManager *FP = getContainedManager(Index);
924 Changed |= FP->doFinalization(M);
930 // Execute all the passes managed by this top level manager.
931 // Return true if any function is modified by a pass.
932 bool FunctionPassManagerImpl::run(Function &F) {
934 bool Changed = false;
936 TimingInfo::createTheTimeInfo();
941 initializeAllAnalysisInfo();
942 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
943 FPPassManager *FP = getContainedManager(Index);
944 Changed |= FP->runOnFunction(F);
949 //===----------------------------------------------------------------------===//
950 // FPPassManager implementation
952 /// Print passes managed by this manager
953 void FPPassManager::dumpPassStructure(unsigned Offset) {
954 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
955 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
956 FunctionPass *FP = getContainedPass(Index);
957 FP->dumpPassStructure(Offset + 1);
958 dumpLastUses(FP, Offset+1);
963 /// Execute all of the passes scheduled for execution by invoking
964 /// runOnFunction method. Keep track of whether any of the passes modifies
965 /// the function, and if so, return true.
966 bool FPPassManager::runOnFunction(Function &F) {
968 bool Changed = false;
970 if (F.isDeclaration())
973 std::string Msg1 = "Executing Pass '";
974 std::string Msg3 = "' Made Modification '";
976 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
977 FunctionPass *FP = getContainedPass(Index);
979 AnalysisUsage AnUsage;
980 FP->getAnalysisUsage(AnUsage);
982 std::string Msg2 = "' on Function '" + F.getName() + "'...\n";
983 dumpPassInfo(FP, Msg1, Msg2);
984 dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
986 initializeAnalysisImpl(FP);
988 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
989 Changed |= FP->runOnFunction(F);
990 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
993 dumpPassInfo(FP, Msg3, Msg2);
994 dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
996 removeNotPreservedAnalysis(FP);
997 recordAvailableAnalysis(FP);
998 removeDeadPasses(FP, Msg2);
1003 bool FPPassManager::runOnModule(Module &M) {
1005 bool Changed = doInitialization(M);
1007 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1008 this->runOnFunction(*I);
1010 return Changed |= doFinalization(M);
1013 inline bool FPPassManager::doInitialization(Module &M) {
1014 bool Changed = false;
1016 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1017 FunctionPass *FP = getContainedPass(Index);
1018 Changed |= FP->doInitialization(M);
1024 inline bool FPPassManager::doFinalization(Module &M) {
1025 bool Changed = false;
1027 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1028 FunctionPass *FP = getContainedPass(Index);
1029 Changed |= FP->doFinalization(M);
1035 //===----------------------------------------------------------------------===//
1036 // MPPassManager implementation
1038 /// Execute all of the passes scheduled for execution by invoking
1039 /// runOnModule method. Keep track of whether any of the passes modifies
1040 /// the module, and if so, return true.
1042 MPPassManager::runOnModule(Module &M) {
1043 bool Changed = false;
1045 std::string Msg1 = "Executing Pass '";
1046 std::string Msg3 = "' Made Modification '";
1048 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1049 ModulePass *MP = getContainedPass(Index);
1051 AnalysisUsage AnUsage;
1052 MP->getAnalysisUsage(AnUsage);
1054 std::string Msg2 = "' on Module '" + M.getModuleIdentifier() + "'...\n";
1055 dumpPassInfo(MP, Msg1, Msg2);
1056 dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1058 initializeAnalysisImpl(MP);
1060 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1061 Changed |= MP->runOnModule(M);
1062 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1065 dumpPassInfo(MP, Msg3, Msg2);
1066 dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1068 removeNotPreservedAnalysis(MP);
1069 recordAvailableAnalysis(MP);
1070 removeDeadPasses(MP, Msg2);
1075 //===----------------------------------------------------------------------===//
1076 // PassManagerImpl implementation
1078 /// run - Execute all of the passes scheduled for execution. Keep track of
1079 /// whether any of the passes modifies the module, and if so, return true.
1080 bool PassManagerImpl::run(Module &M) {
1082 bool Changed = false;
1084 TimingInfo::createTheTimeInfo();
1089 initializeAllAnalysisInfo();
1090 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1091 MPPassManager *MP = getContainedManager(Index);
1092 Changed |= MP->runOnModule(M);
1097 //===----------------------------------------------------------------------===//
1098 // PassManager implementation
1100 /// Create new pass manager
1101 PassManager::PassManager() {
1102 PM = new PassManagerImpl(0);
1103 // PM is the top level manager
1104 PM->setTopLevelManager(PM);
1107 PassManager::~PassManager() {
1111 /// add - Add a pass to the queue of passes to run. This passes ownership of
1112 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1113 /// will be destroyed as well, so there is no need to delete the pass. This
1114 /// implies that all passes MUST be allocated with 'new'.
1116 PassManager::add(Pass *P) {
1120 /// run - Execute all of the passes scheduled for execution. Keep track of
1121 /// whether any of the passes modifies the module, and if so, return true.
1123 PassManager::run(Module &M) {
1127 //===----------------------------------------------------------------------===//
1128 // TimingInfo Class - This class is used to calculate information about the
1129 // amount of time each pass takes to execute. This only happens with
1130 // -time-passes is enabled on the command line.
1132 bool llvm::TimePassesIsEnabled = false;
1133 static cl::opt<bool,true>
1134 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1135 cl::desc("Time each pass, printing elapsed time for each on exit"));
1137 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1138 // a non null value (if the -time-passes option is enabled) or it leaves it
1139 // null. It may be called multiple times.
1140 void TimingInfo::createTheTimeInfo() {
1141 if (!TimePassesIsEnabled || TheTimeInfo) return;
1143 // Constructed the first time this is called, iff -time-passes is enabled.
1144 // This guarantees that the object will be constructed before static globals,
1145 // thus it will be destroyed before them.
1146 static ManagedStatic<TimingInfo> TTI;
1147 TheTimeInfo = &*TTI;
1150 /// If TimingInfo is enabled then start pass timer.
1151 void StartPassTimer(Pass *P) {
1153 TheTimeInfo->passStarted(P);
1156 /// If TimingInfo is enabled then stop pass timer.
1157 void StopPassTimer(Pass *P) {
1159 TheTimeInfo->passEnded(P);
1162 //===----------------------------------------------------------------------===//
1163 // PMStack implementation
1166 // Pop Pass Manager from the stack and clear its analysis info.
1167 void PMStack::pop() {
1169 PMDataManager *Top = this->top();
1170 Top->initializeAnalysisInfo();
1175 // Push PM on the stack and set its top level manager.
1176 void PMStack::push(Pass *P) {
1178 PMDataManager *Top = NULL;
1179 PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1180 assert (PM && "Unable to push. Pass Manager expected");
1182 if (this->empty()) {
1187 PMTopLevelManager *TPM = Top->getTopLevelManager();
1189 assert (TPM && "Unable to find top level manager");
1190 TPM->addIndirectPassManager(PM);
1191 PM->setTopLevelManager(TPM);
1194 AnalysisResolver *AR = new AnalysisResolver(*Top);
1200 // Dump content of the pass manager stack.
1201 void PMStack::dump() {
1202 for(std::deque<PMDataManager *>::iterator I = S.begin(),
1203 E = S.end(); I != E; ++I) {
1204 Pass *P = dynamic_cast<Pass *>(*I);
1205 printf ("%s ", P->getPassName());
1211 // Walk Pass Manager stack and set LastUse markers if any
1212 // manager is transfering this priviledge to its parent manager
1213 void PMStack::handleLastUserOverflow() {
1215 for(PMStack::iterator I = this->begin(), E = this->end(); I != E;) {
1217 PMDataManager *Child = *I++;
1219 PMDataManager *Parent = *I++;
1220 PMTopLevelManager *TPM = Parent->getTopLevelManager();
1221 std::vector<Pass *> &TLU = Child->getTransferredLastUses();
1223 Pass *P = dynamic_cast<Pass *>(Parent);
1224 TPM->setLastUser(TLU, P);
1231 /// Find appropriate Module Pass Manager in the PM Stack and
1232 /// add self into that manager.
1233 void ModulePass::assignPassManager(PMStack &PMS,
1234 PassManagerType PreferredType) {
1236 // Find Module Pass Manager
1237 while(!PMS.empty()) {
1238 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1239 if (TopPMType == PreferredType)
1240 break; // We found desired pass manager
1241 else if (TopPMType > PMT_ModulePassManager)
1242 PMS.pop(); // Pop children pass managers
1247 PMS.top()->add(this);
1250 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1251 /// in the PM Stack and add self into that manager.
1252 void FunctionPass::assignPassManager(PMStack &PMS,
1253 PassManagerType PreferredType) {
1255 // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1256 while(!PMS.empty()) {
1257 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1262 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1264 // Create new Function Pass Manager
1266 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1267 PMDataManager *PMD = PMS.top();
1269 // [1] Create new Function Pass Manager
1270 FPP = new FPPassManager(PMD->getDepth() + 1);
1272 // [2] Set up new manager's top level manager
1273 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1274 TPM->addIndirectPassManager(FPP);
1276 // [3] Assign manager to manage this new manager. This may create
1277 // and push new managers into PMS
1278 Pass *P = dynamic_cast<Pass *>(FPP);
1280 // If Call Graph Pass Manager is active then use it to manage
1281 // this new Function Pass manager.
1282 if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1283 P->assignPassManager(PMS, PMT_CallGraphPassManager);
1285 P->assignPassManager(PMS);
1287 // [4] Push new manager into PMS
1291 // Assign FPP as the manager of this pass.
1295 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1296 /// in the PM Stack and add self into that manager.
1297 void BasicBlockPass::assignPassManager(PMStack &PMS,
1298 PassManagerType PreferredType) {
1300 BBPassManager *BBP = NULL;
1302 // Basic Pass Manager is a leaf pass manager. It does not handle
1303 // any other pass manager.
1305 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1308 // If leaf manager is not Basic Block Pass manager then create new
1309 // basic Block Pass manager.
1312 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1313 PMDataManager *PMD = PMS.top();
1315 // [1] Create new Basic Block Manager
1316 BBP = new BBPassManager(PMD->getDepth() + 1);
1318 // [2] Set up new manager's top level manager
1319 // Basic Block Pass Manager does not live by itself
1320 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1321 TPM->addIndirectPassManager(BBP);
1323 // [3] Assign manager to manage this new manager. This may create
1324 // and push new managers into PMS
1325 Pass *P = dynamic_cast<Pass *>(BBP);
1326 P->assignPassManager(PMS);
1328 // [4] Push new manager into PMS
1332 // Assign BBP as the manager of this pass.