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 /// 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 /// Add RequiredPass into list of lower level passes required by pass P.
194 /// RequiredPass is run on the fly by Pass Manager when P requests it
195 /// through getAnalysis interface.
196 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
198 virtual const char *getPassName() const {
199 return "Module Pass Manager";
202 // Print passes managed by this manager
203 void dumpPassStructure(unsigned Offset) {
204 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
205 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
206 ModulePass *MP = getContainedPass(Index);
207 MP->dumpPassStructure(Offset + 1);
208 dumpLastUses(MP, Offset+1);
212 ModulePass *getContainedPass(unsigned N) {
213 assert ( N < PassVector.size() && "Pass number out of range!");
214 ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
218 virtual PassManagerType getPassManagerType() const {
219 return PMT_ModulePassManager;
223 //===----------------------------------------------------------------------===//
226 /// PassManagerImpl manages MPPassManagers
227 class PassManagerImpl : public Pass,
228 public PMDataManager,
229 public PMTopLevelManager {
233 PassManagerImpl(int Depth) : PMDataManager(Depth),
234 PMTopLevelManager(TLM_Pass) { }
236 /// add - Add a pass to the queue of passes to run. This passes ownership of
237 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
238 /// will be destroyed as well, so there is no need to delete the pass. This
239 /// implies that all passes MUST be allocated with 'new'.
244 /// run - Execute all of the passes scheduled for execution. Keep track of
245 /// whether any of the passes modifies the module, and if so, return true.
248 /// Pass Manager itself does not invalidate any analysis info.
249 void getAnalysisUsage(AnalysisUsage &Info) const {
250 Info.setPreservesAll();
253 inline void addTopLevelPass(Pass *P) {
255 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
257 // P is a immutable pass and it will be managed by this
258 // top level manager. Set up analysis resolver to connect them.
259 AnalysisResolver *AR = new AnalysisResolver(*this);
261 initializeAnalysisImpl(P);
262 addImmutablePass(IP);
263 recordAvailableAnalysis(IP);
265 P->assignPassManager(activeStack);
270 MPPassManager *getContainedManager(unsigned N) {
271 assert ( N < PassManagers.size() && "Pass number out of range!");
272 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
278 } // End of llvm namespace
282 //===----------------------------------------------------------------------===//
283 // TimingInfo Class - This class is used to calculate information about the
284 // amount of time each pass takes to execute. This only happens when
285 // -time-passes is enabled on the command line.
288 class VISIBILITY_HIDDEN TimingInfo {
289 std::map<Pass*, Timer> TimingData;
293 // Use 'create' member to get this.
294 TimingInfo() : TG("... Pass execution timing report ...") {}
296 // TimingDtor - Print out information about timing information
298 // Delete all of the timers...
300 // TimerGroup is deleted next, printing the report.
303 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
304 // to a non null value (if the -time-passes option is enabled) or it leaves it
305 // null. It may be called multiple times.
306 static void createTheTimeInfo();
308 void passStarted(Pass *P) {
310 if (dynamic_cast<PMDataManager *>(P))
313 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
314 if (I == TimingData.end())
315 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
316 I->second.startTimer();
318 void passEnded(Pass *P) {
320 if (dynamic_cast<PMDataManager *>(P))
323 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
324 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
325 I->second.stopTimer();
329 static TimingInfo *TheTimeInfo;
331 } // End of anon namespace
333 //===----------------------------------------------------------------------===//
334 // PMTopLevelManager implementation
336 /// Initialize top level manager. Create first pass manager.
337 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
340 MPPassManager *MPP = new MPPassManager(1);
341 MPP->setTopLevelManager(this);
343 activeStack.push(MPP);
345 else if (t == TLM_Function) {
346 FPPassManager *FPP = new FPPassManager(1);
347 FPP->setTopLevelManager(this);
349 activeStack.push(FPP);
353 /// Set pass P as the last user of the given analysis passes.
354 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
357 for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
358 E = AnalysisPasses.end(); I != E; ++I) {
365 // If AP is the last user of other passes then make P last user of
367 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
368 LUE = LastUser.end(); LUI != LUE; ++LUI) {
369 if (LUI->second == AP)
370 LastUser[LUI->first] = P;
375 /// Collect passes whose last user is P
376 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
378 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
379 LUE = LastUser.end(); LUI != LUE; ++LUI)
380 if (LUI->second == P)
381 LastUses.push_back(LUI->first);
384 /// Schedule pass P for execution. Make sure that passes required by
385 /// P are run before P is run. Update analysis info maintained by
386 /// the manager. Remove dead passes. This is a recursive function.
387 void PMTopLevelManager::schedulePass(Pass *P) {
389 // TODO : Allocate function manager for this pass, other wise required set
390 // may be inserted into previous function manager
392 // If this Analysis is already requested by one of the previous pass
393 // and it is still available then do not insert new pass in the queue again.
394 if (findAnalysisPass(P->getPassInfo()))
397 // Give pass a chance to prepare the stage.
398 P->preparePassManager(activeStack);
400 AnalysisUsage AnUsage;
401 P->getAnalysisUsage(AnUsage);
402 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
403 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
404 E = RequiredSet.end(); I != E; ++I) {
406 Pass *AnalysisPass = findAnalysisPass(*I);
408 AnalysisPass = (*I)->createPass();
409 // Schedule this analysis run first only if it is not a lower level
410 // analysis pass. Lower level analsyis passes are run on the fly.
411 if (P->getPotentialPassManagerType () >=
412 AnalysisPass->getPotentialPassManagerType())
413 schedulePass(AnalysisPass);
419 // Now all required passes are available.
423 /// Find the pass that implements Analysis AID. Search immutable
424 /// passes and all pass managers. If desired pass is not found
425 /// then return NULL.
426 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
429 // Check pass managers
430 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
431 E = PassManagers.end(); P == NULL && I != E; ++I) {
432 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
433 assert(PMD && "This is not a PassManager");
434 P = PMD->findAnalysisPass(AID, false);
437 // Check other pass managers
438 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
439 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
440 P = (*I)->findAnalysisPass(AID, false);
442 for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
443 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
444 const PassInfo *PI = (*I)->getPassInfo();
448 // If Pass not found then check the interfaces implemented by Immutable Pass
450 const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
451 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
459 // Print passes managed by this top level manager.
460 void PMTopLevelManager::dumpPasses() const {
462 if (PassDebugging < Structure)
465 // Print out the immutable passes
466 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
467 ImmutablePasses[i]->dumpPassStructure(0);
470 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
471 E = PassManagers.end(); I != E; ++I)
472 (*I)->dumpPassStructure(1);
475 void PMTopLevelManager::dumpArguments() const {
477 if (PassDebugging < Arguments)
480 cerr << "Pass Arguments: ";
481 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
482 E = PassManagers.end(); I != E; ++I) {
483 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
484 assert(PMD && "This is not a PassManager");
485 PMD->dumpPassArguments();
490 void PMTopLevelManager::initializeAllAnalysisInfo() {
492 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
493 E = PassManagers.end(); I != E; ++I) {
494 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
495 assert(PMD && "This is not a PassManager");
496 PMD->initializeAnalysisInfo();
499 // Initailize other pass managers
500 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
501 E = IndirectPassManagers.end(); I != E; ++I)
502 (*I)->initializeAnalysisInfo();
506 PMTopLevelManager::~PMTopLevelManager() {
507 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
508 E = PassManagers.end(); I != E; ++I)
511 for (std::vector<ImmutablePass *>::iterator
512 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
515 PassManagers.clear();
518 //===----------------------------------------------------------------------===//
519 // PMDataManager implementation
521 /// Return true IFF pass P's required analysis set does not required new
523 bool PMDataManager::manageablePass(Pass *P) {
526 // If this pass is not preserving information that is required by a
527 // pass maintained by higher level pass manager then do not insert
528 // this pass into current manager. Use new manager. For example,
529 // For example, If FunctionPass F is not preserving ModulePass Info M1
530 // that is used by another ModulePass M2 then do not insert F in
531 // current function pass manager.
535 /// Augement AvailableAnalysis by adding analysis made available by pass P.
536 void PMDataManager::recordAvailableAnalysis(Pass *P) {
538 if (const PassInfo *PI = P->getPassInfo()) {
539 AvailableAnalysis[PI] = P;
541 //This pass is the current implementation of all of the interfaces it
542 //implements as well.
543 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
544 for (unsigned i = 0, e = II.size(); i != e; ++i)
545 AvailableAnalysis[II[i]] = P;
549 // Return true if P preserves high level analysis used by other
550 // passes managed by this manager
551 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
553 AnalysisUsage AnUsage;
554 P->getAnalysisUsage(AnUsage);
556 if (AnUsage.getPreservesAll())
559 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
560 for (std::vector<Pass *>::iterator I = HigherLevelAnalysis.begin(),
561 E = HigherLevelAnalysis.end(); I != E; ++I) {
563 if (!dynamic_cast<ImmutablePass*>(P1)
564 && std::find(PreservedSet.begin(), PreservedSet.end(), P1->getPassInfo()) ==
572 /// Remove Analyss not preserved by Pass P
573 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
574 AnalysisUsage AnUsage;
575 P->getAnalysisUsage(AnUsage);
577 if (AnUsage.getPreservesAll())
580 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
581 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
582 E = AvailableAnalysis.end(); I != E; ) {
583 std::map<AnalysisID, Pass*>::iterator Info = I++;
584 if (!dynamic_cast<ImmutablePass*>(Info->second)
585 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
587 // Remove this analysis
588 AvailableAnalysis.erase(Info);
591 // Check inherited analysis also. If P is not preserving analysis
592 // provided by parent manager then remove it here.
593 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
595 if (!InheritedAnalysis[Index])
598 for (std::map<AnalysisID, Pass*>::iterator
599 I = InheritedAnalysis[Index]->begin(),
600 E = InheritedAnalysis[Index]->end(); I != E; ) {
601 std::map<AnalysisID, Pass *>::iterator Info = I++;
602 if (!dynamic_cast<ImmutablePass*>(Info->second)
603 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
605 // Remove this analysis
606 InheritedAnalysis[Index]->erase(Info);
612 /// Remove analysis passes that are not used any longer
613 void PMDataManager::removeDeadPasses(Pass *P, std::string Msg,
614 enum PassDebuggingString DBG_STR) {
616 std::vector<Pass *> DeadPasses;
617 TPM->collectLastUses(DeadPasses, P);
619 for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
620 E = DeadPasses.end(); I != E; ++I) {
622 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
624 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
625 (*I)->releaseMemory();
626 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
628 std::map<AnalysisID, Pass*>::iterator Pos =
629 AvailableAnalysis.find((*I)->getPassInfo());
631 // It is possible that pass is already removed from the AvailableAnalysis
632 if (Pos != AvailableAnalysis.end())
633 AvailableAnalysis.erase(Pos);
637 /// Add pass P into the PassVector. Update
638 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
639 void PMDataManager::add(Pass *P,
640 bool ProcessAnalysis) {
642 // This manager is going to manage pass P. Set up analysis resolver
644 AnalysisResolver *AR = new AnalysisResolver(*this);
647 // If a FunctionPass F is the last user of ModulePass info M
648 // then the F's manager, not F, records itself as a last user of M.
649 std::vector<Pass *> TransferLastUses;
651 if (ProcessAnalysis) {
653 // At the moment, this pass is the last user of all required passes.
654 std::vector<Pass *> LastUses;
655 SmallVector<Pass *, 8> RequiredPasses;
656 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
658 unsigned PDepth = this->getDepth();
660 collectRequiredAnalysis(RequiredPasses,
661 ReqAnalysisNotAvailable, P);
662 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
663 E = RequiredPasses.end(); I != E; ++I) {
664 Pass *PRequired = *I;
667 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
668 RDepth = DM.getDepth();
670 if (PDepth == RDepth)
671 LastUses.push_back(PRequired);
672 else if (PDepth > RDepth) {
673 // Let the parent claim responsibility of last use
674 TransferLastUses.push_back(PRequired);
675 // Keep track of higher level analysis used by this manager.
676 HigherLevelAnalysis.push_back(PRequired);
678 assert (0 && "Unable to accomodate Required Pass");
681 // Now, take care of required analysises that are not available.
682 for (SmallVector<AnalysisID, 8>::iterator
683 I = ReqAnalysisNotAvailable.begin(),
684 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
685 Pass *AnalysisPass = (*I)->createPass();
686 this->addLowerLevelRequiredPass(P, AnalysisPass);
689 // Set P as P's last user until someone starts using P.
690 // However, if P is a Pass Manager then it does not need
691 // to record its last user.
692 if (!dynamic_cast<PMDataManager *>(P))
693 LastUses.push_back(P);
694 TPM->setLastUser(LastUses, P);
696 if (!TransferLastUses.empty()) {
697 Pass *My_PM = dynamic_cast<Pass *>(this);
698 TPM->setLastUser(TransferLastUses, My_PM);
699 TransferLastUses.clear();
702 // Take a note of analysis required and made available by this pass.
703 // Remove the analysis not preserved by this pass
704 removeNotPreservedAnalysis(P);
705 recordAvailableAnalysis(P);
709 PassVector.push_back(P);
713 /// Populate RP with analysis pass that are required by
714 /// pass P and are available. Populate RP_NotAvail with analysis
715 /// pass that are required by pass P but are not available.
716 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
717 SmallVector<AnalysisID, 8> &RP_NotAvail,
719 AnalysisUsage AnUsage;
720 P->getAnalysisUsage(AnUsage);
721 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
722 for (std::vector<AnalysisID>::const_iterator
723 I = RequiredSet.begin(), E = RequiredSet.end();
726 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
727 RP.push_back(AnalysisPass);
729 RP_NotAvail.push_back(AID);
732 const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
733 for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
734 E = IDs.end(); I != E; ++I) {
736 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
737 RP.push_back(AnalysisPass);
739 RP_NotAvail.push_back(AID);
743 // All Required analyses should be available to the pass as it runs! Here
744 // we fill in the AnalysisImpls member of the pass so that it can
745 // successfully use the getAnalysis() method to retrieve the
746 // implementations it needs.
748 void PMDataManager::initializeAnalysisImpl(Pass *P) {
749 AnalysisUsage AnUsage;
750 P->getAnalysisUsage(AnUsage);
752 for (std::vector<const PassInfo *>::const_iterator
753 I = AnUsage.getRequiredSet().begin(),
754 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
755 Pass *Impl = findAnalysisPass(*I, true);
757 assert(0 && "Analysis used but not available!");
758 AnalysisResolver *AR = P->getResolver();
759 AR->addAnalysisImplsPair(*I, Impl);
763 /// Find the pass that implements Analysis AID. If desired pass is not found
764 /// then return NULL.
765 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
767 // Check if AvailableAnalysis map has one entry.
768 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
770 if (I != AvailableAnalysis.end())
773 // Search Parents through TopLevelManager
775 return TPM->findAnalysisPass(AID);
780 // Print list of passes that are last used by P.
781 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
783 std::vector<Pass *> LUses;
785 assert (TPM && "Top Level Manager is missing");
786 TPM->collectLastUses(LUses, P);
788 for (std::vector<Pass *>::iterator I = LUses.begin(),
789 E = LUses.end(); I != E; ++I) {
790 llvm::cerr << "--" << std::string(Offset*2, ' ');
791 (*I)->dumpPassStructure(0);
795 void PMDataManager::dumpPassArguments() const {
796 for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
797 E = PassVector.end(); I != E; ++I) {
798 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
799 PMD->dumpPassArguments();
801 if (const PassInfo *PI = (*I)->getPassInfo())
802 if (!PI->isAnalysisGroup())
803 cerr << " -" << PI->getPassArgument();
807 void PMDataManager:: dumpPassInfo(Pass *P, enum PassDebuggingString S1,
808 enum PassDebuggingString S2,
810 if (PassDebugging < Executions)
812 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
815 cerr << "Executing Pass '" << P->getPassName();
817 case MODIFICATION_MSG:
818 cerr << "' Made Modification '" << P->getPassName();
821 cerr << " Freeing Pass '" << P->getPassName();
827 case ON_BASICBLOCK_MSG:
828 cerr << "' on BasicBlock '" << Msg << "...\n";
830 case ON_FUNCTION_MSG:
831 cerr << "' on Function '" << Msg << "...\n";
834 cerr << "' on Module '" << Msg << "...\n";
837 cerr << "' on Loop " << Msg << "...\n";
840 cerr << "' on Call Graph " << Msg << "...\n";
847 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
848 const std::vector<AnalysisID> &Set)
850 if (PassDebugging >= Details && !Set.empty()) {
851 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
852 for (unsigned i = 0; i != Set.size(); ++i) {
854 cerr << " " << Set[i]->getPassName();
861 PMDataManager::~PMDataManager() {
863 for (std::vector<Pass *>::iterator I = PassVector.begin(),
864 E = PassVector.end(); I != E; ++I)
870 //===----------------------------------------------------------------------===//
871 // NOTE: Is this the right place to define this method ?
872 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
873 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
874 return PM.findAnalysisPass(ID, dir);
877 //===----------------------------------------------------------------------===//
878 // BBPassManager implementation
880 /// Execute all of the passes scheduled for execution by invoking
881 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
882 /// the function, and if so, return true.
884 BBPassManager::runOnFunction(Function &F) {
886 if (F.isDeclaration())
889 bool Changed = doInitialization(F);
891 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
892 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
893 BasicBlockPass *BP = getContainedPass(Index);
894 AnalysisUsage AnUsage;
895 BP->getAnalysisUsage(AnUsage);
897 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
898 dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
900 initializeAnalysisImpl(BP);
902 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
903 Changed |= BP->runOnBasicBlock(*I);
904 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
907 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
908 dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
910 removeNotPreservedAnalysis(BP);
911 recordAvailableAnalysis(BP);
912 removeDeadPasses(BP, (*I).getName(), ON_BASICBLOCK_MSG);
915 return Changed |= doFinalization(F);
918 // Implement doInitialization and doFinalization
919 inline bool BBPassManager::doInitialization(Module &M) {
920 bool Changed = false;
922 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
923 BasicBlockPass *BP = getContainedPass(Index);
924 Changed |= BP->doInitialization(M);
930 inline bool BBPassManager::doFinalization(Module &M) {
931 bool Changed = false;
933 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
934 BasicBlockPass *BP = getContainedPass(Index);
935 Changed |= BP->doFinalization(M);
941 inline bool BBPassManager::doInitialization(Function &F) {
942 bool Changed = false;
944 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
945 BasicBlockPass *BP = getContainedPass(Index);
946 Changed |= BP->doInitialization(F);
952 inline bool BBPassManager::doFinalization(Function &F) {
953 bool Changed = false;
955 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
956 BasicBlockPass *BP = getContainedPass(Index);
957 Changed |= BP->doFinalization(F);
964 //===----------------------------------------------------------------------===//
965 // FunctionPassManager implementation
967 /// Create new Function pass manager
968 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
969 FPM = new FunctionPassManagerImpl(0);
970 // FPM is the top level manager.
971 FPM->setTopLevelManager(FPM);
973 PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
974 AnalysisResolver *AR = new AnalysisResolver(*PMD);
975 FPM->setResolver(AR);
980 FunctionPassManager::~FunctionPassManager() {
984 /// add - Add a pass to the queue of passes to run. This passes
985 /// ownership of the Pass to the PassManager. When the
986 /// PassManager_X is destroyed, the pass will be destroyed as well, so
987 /// there is no need to delete the pass. (TODO delete passes.)
988 /// This implies that all passes MUST be allocated with 'new'.
989 void FunctionPassManager::add(Pass *P) {
993 /// run - Execute all of the passes scheduled for execution. Keep
994 /// track of whether any of the passes modifies the function, and if
997 bool FunctionPassManager::run(Function &F) {
999 if (MP->materializeFunction(&F, &errstr)) {
1000 cerr << "Error reading bytecode file: " << errstr << "\n";
1007 /// doInitialization - Run all of the initializers for the function passes.
1009 bool FunctionPassManager::doInitialization() {
1010 return FPM->doInitialization(*MP->getModule());
1013 /// doFinalization - Run all of the initializers for the function passes.
1015 bool FunctionPassManager::doFinalization() {
1016 return FPM->doFinalization(*MP->getModule());
1019 //===----------------------------------------------------------------------===//
1020 // FunctionPassManagerImpl implementation
1022 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1023 bool Changed = false;
1025 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1026 FPPassManager *FP = getContainedManager(Index);
1027 Changed |= FP->doInitialization(M);
1033 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1034 bool Changed = false;
1036 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1037 FPPassManager *FP = getContainedManager(Index);
1038 Changed |= FP->doFinalization(M);
1044 // Execute all the passes managed by this top level manager.
1045 // Return true if any function is modified by a pass.
1046 bool FunctionPassManagerImpl::run(Function &F) {
1048 bool Changed = false;
1050 TimingInfo::createTheTimeInfo();
1055 initializeAllAnalysisInfo();
1056 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1057 FPPassManager *FP = getContainedManager(Index);
1058 Changed |= FP->runOnFunction(F);
1063 //===----------------------------------------------------------------------===//
1064 // FPPassManager implementation
1066 /// Print passes managed by this manager
1067 void FPPassManager::dumpPassStructure(unsigned Offset) {
1068 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1069 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1070 FunctionPass *FP = getContainedPass(Index);
1071 FP->dumpPassStructure(Offset + 1);
1072 dumpLastUses(FP, Offset+1);
1077 /// Execute all of the passes scheduled for execution by invoking
1078 /// runOnFunction method. Keep track of whether any of the passes modifies
1079 /// the function, and if so, return true.
1080 bool FPPassManager::runOnFunction(Function &F) {
1082 bool Changed = false;
1084 if (F.isDeclaration())
1087 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1088 FunctionPass *FP = getContainedPass(Index);
1090 AnalysisUsage AnUsage;
1091 FP->getAnalysisUsage(AnUsage);
1093 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1094 dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1096 initializeAnalysisImpl(FP);
1098 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1099 Changed |= FP->runOnFunction(F);
1100 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1103 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1104 dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1106 removeNotPreservedAnalysis(FP);
1107 recordAvailableAnalysis(FP);
1108 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1113 bool FPPassManager::runOnModule(Module &M) {
1115 bool Changed = doInitialization(M);
1117 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1118 this->runOnFunction(*I);
1120 return Changed |= doFinalization(M);
1123 inline bool FPPassManager::doInitialization(Module &M) {
1124 bool Changed = false;
1126 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1127 FunctionPass *FP = getContainedPass(Index);
1128 Changed |= FP->doInitialization(M);
1134 inline bool FPPassManager::doFinalization(Module &M) {
1135 bool Changed = false;
1137 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1138 FunctionPass *FP = getContainedPass(Index);
1139 Changed |= FP->doFinalization(M);
1145 //===----------------------------------------------------------------------===//
1146 // MPPassManager implementation
1148 /// Execute all of the passes scheduled for execution by invoking
1149 /// runOnModule method. Keep track of whether any of the passes modifies
1150 /// the module, and if so, return true.
1152 MPPassManager::runOnModule(Module &M) {
1153 bool Changed = false;
1155 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1156 ModulePass *MP = getContainedPass(Index);
1158 AnalysisUsage AnUsage;
1159 MP->getAnalysisUsage(AnUsage);
1161 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1162 dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1164 initializeAnalysisImpl(MP);
1166 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1167 Changed |= MP->runOnModule(M);
1168 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1171 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1172 M.getModuleIdentifier());
1173 dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1175 removeNotPreservedAnalysis(MP);
1176 recordAvailableAnalysis(MP);
1177 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1182 /// Add RequiredPass into list of lower level passes required by pass P.
1183 /// RequiredPass is run on the fly by Pass Manager when P requests it
1184 /// through getAnalysis interface.
1185 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1187 assert (P->getPotentialPassManagerType() == PMT_ModulePassManager
1188 && "Unable to handle Pass that requires lower level Analysis pass");
1189 assert ((P->getPotentialPassManagerType() <
1190 RequiredPass->getPotentialPassManagerType())
1191 && "Unable to handle Pass that requires lower level Analysis pass");
1194 "Unable to handle Pass that requires lower level Analysis pass");
1197 //===----------------------------------------------------------------------===//
1198 // PassManagerImpl implementation
1200 /// run - Execute all of the passes scheduled for execution. Keep track of
1201 /// whether any of the passes modifies the module, and if so, return true.
1202 bool PassManagerImpl::run(Module &M) {
1204 bool Changed = false;
1206 TimingInfo::createTheTimeInfo();
1211 initializeAllAnalysisInfo();
1212 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1213 MPPassManager *MP = getContainedManager(Index);
1214 Changed |= MP->runOnModule(M);
1219 //===----------------------------------------------------------------------===//
1220 // PassManager implementation
1222 /// Create new pass manager
1223 PassManager::PassManager() {
1224 PM = new PassManagerImpl(0);
1225 // PM is the top level manager
1226 PM->setTopLevelManager(PM);
1229 PassManager::~PassManager() {
1233 /// add - Add a pass to the queue of passes to run. This passes ownership of
1234 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1235 /// will be destroyed as well, so there is no need to delete the pass. This
1236 /// implies that all passes MUST be allocated with 'new'.
1238 PassManager::add(Pass *P) {
1242 /// run - Execute all of the passes scheduled for execution. Keep track of
1243 /// whether any of the passes modifies the module, and if so, return true.
1245 PassManager::run(Module &M) {
1249 //===----------------------------------------------------------------------===//
1250 // TimingInfo Class - This class is used to calculate information about the
1251 // amount of time each pass takes to execute. This only happens with
1252 // -time-passes is enabled on the command line.
1254 bool llvm::TimePassesIsEnabled = false;
1255 static cl::opt<bool,true>
1256 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1257 cl::desc("Time each pass, printing elapsed time for each on exit"));
1259 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1260 // a non null value (if the -time-passes option is enabled) or it leaves it
1261 // null. It may be called multiple times.
1262 void TimingInfo::createTheTimeInfo() {
1263 if (!TimePassesIsEnabled || TheTimeInfo) return;
1265 // Constructed the first time this is called, iff -time-passes is enabled.
1266 // This guarantees that the object will be constructed before static globals,
1267 // thus it will be destroyed before them.
1268 static ManagedStatic<TimingInfo> TTI;
1269 TheTimeInfo = &*TTI;
1272 /// If TimingInfo is enabled then start pass timer.
1273 void StartPassTimer(Pass *P) {
1275 TheTimeInfo->passStarted(P);
1278 /// If TimingInfo is enabled then stop pass timer.
1279 void StopPassTimer(Pass *P) {
1281 TheTimeInfo->passEnded(P);
1284 //===----------------------------------------------------------------------===//
1285 // PMStack implementation
1288 // Pop Pass Manager from the stack and clear its analysis info.
1289 void PMStack::pop() {
1291 PMDataManager *Top = this->top();
1292 Top->initializeAnalysisInfo();
1297 // Push PM on the stack and set its top level manager.
1298 void PMStack::push(Pass *P) {
1300 PMDataManager *Top = NULL;
1301 PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1302 assert (PM && "Unable to push. Pass Manager expected");
1304 if (this->empty()) {
1309 PMTopLevelManager *TPM = Top->getTopLevelManager();
1311 assert (TPM && "Unable to find top level manager");
1312 TPM->addIndirectPassManager(PM);
1313 PM->setTopLevelManager(TPM);
1316 AnalysisResolver *AR = new AnalysisResolver(*Top);
1322 // Dump content of the pass manager stack.
1323 void PMStack::dump() {
1324 for(std::deque<PMDataManager *>::iterator I = S.begin(),
1325 E = S.end(); I != E; ++I) {
1326 Pass *P = dynamic_cast<Pass *>(*I);
1327 printf ("%s ", P->getPassName());
1333 /// Find appropriate Module Pass Manager in the PM Stack and
1334 /// add self into that manager.
1335 void ModulePass::assignPassManager(PMStack &PMS,
1336 PassManagerType PreferredType) {
1338 // Find Module Pass Manager
1339 while(!PMS.empty()) {
1340 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1341 if (TopPMType == PreferredType)
1342 break; // We found desired pass manager
1343 else if (TopPMType > PMT_ModulePassManager)
1344 PMS.pop(); // Pop children pass managers
1349 PMS.top()->add(this);
1352 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1353 /// in the PM Stack and add self into that manager.
1354 void FunctionPass::assignPassManager(PMStack &PMS,
1355 PassManagerType PreferredType) {
1357 // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1358 while(!PMS.empty()) {
1359 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1364 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1366 // Create new Function Pass Manager
1368 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1369 PMDataManager *PMD = PMS.top();
1371 // [1] Create new Function Pass Manager
1372 FPP = new FPPassManager(PMD->getDepth() + 1);
1374 // [2] Set up new manager's top level manager
1375 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1376 TPM->addIndirectPassManager(FPP);
1378 // [3] Assign manager to manage this new manager. This may create
1379 // and push new managers into PMS
1380 Pass *P = dynamic_cast<Pass *>(FPP);
1382 // If Call Graph Pass Manager is active then use it to manage
1383 // this new Function Pass manager.
1384 if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1385 P->assignPassManager(PMS, PMT_CallGraphPassManager);
1387 P->assignPassManager(PMS);
1389 // [4] Push new manager into PMS
1393 // Assign FPP as the manager of this pass.
1397 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1398 /// in the PM Stack and add self into that manager.
1399 void BasicBlockPass::assignPassManager(PMStack &PMS,
1400 PassManagerType PreferredType) {
1402 BBPassManager *BBP = NULL;
1404 // Basic Pass Manager is a leaf pass manager. It does not handle
1405 // any other pass manager.
1407 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1410 // If leaf manager is not Basic Block Pass manager then create new
1411 // basic Block Pass manager.
1414 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1415 PMDataManager *PMD = PMS.top();
1417 // [1] Create new Basic Block Manager
1418 BBP = new BBPassManager(PMD->getDepth() + 1);
1420 // [2] Set up new manager's top level manager
1421 // Basic Block Pass Manager does not live by itself
1422 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1423 TPM->addIndirectPassManager(BBP);
1425 // [3] Assign manager to manage this new manager. This may create
1426 // and push new managers into PMS
1427 Pass *P = dynamic_cast<Pass *>(BBP);
1428 P->assignPassManager(PMS);
1430 // [4] Push new manager into PMS
1434 // Assign BBP as the manager of this pass.