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 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() const {
214 return PMT_ModulePassManager;
218 //===----------------------------------------------------------------------===//
221 /// PassManagerImpl manages MPPassManagers
222 class PassManagerImpl : public Pass,
223 public PMDataManager,
224 public PMTopLevelManager {
228 PassManagerImpl(int Depth) : PMDataManager(Depth),
229 PMTopLevelManager(TLM_Pass) { }
231 /// add - Add a pass to the queue of passes to run. This passes ownership of
232 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
233 /// will be destroyed as well, so there is no need to delete the pass. This
234 /// implies that all passes MUST be allocated with 'new'.
239 /// run - Execute all of the passes scheduled for execution. Keep track of
240 /// whether any of the passes modifies the module, and if so, return true.
243 /// Pass Manager itself does not invalidate any analysis info.
244 void getAnalysisUsage(AnalysisUsage &Info) const {
245 Info.setPreservesAll();
248 inline void addTopLevelPass(Pass *P) {
250 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
252 // P is a immutable pass and it will be managed by this
253 // top level manager. Set up analysis resolver to connect them.
254 AnalysisResolver *AR = new AnalysisResolver(*this);
256 initializeAnalysisImpl(P);
257 addImmutablePass(IP);
258 recordAvailableAnalysis(IP);
260 P->assignPassManager(activeStack);
265 MPPassManager *getContainedManager(unsigned N) {
266 assert ( N < PassManagers.size() && "Pass number out of range!");
267 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
273 } // End of llvm namespace
277 //===----------------------------------------------------------------------===//
278 // TimingInfo Class - This class is used to calculate information about the
279 // amount of time each pass takes to execute. This only happens when
280 // -time-passes is enabled on the command line.
283 class VISIBILITY_HIDDEN TimingInfo {
284 std::map<Pass*, Timer> TimingData;
288 // Use 'create' member to get this.
289 TimingInfo() : TG("... Pass execution timing report ...") {}
291 // TimingDtor - Print out information about timing information
293 // Delete all of the timers...
295 // TimerGroup is deleted next, printing the report.
298 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
299 // to a non null value (if the -time-passes option is enabled) or it leaves it
300 // null. It may be called multiple times.
301 static void createTheTimeInfo();
303 void passStarted(Pass *P) {
305 if (dynamic_cast<PMDataManager *>(P))
308 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
309 if (I == TimingData.end())
310 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
311 I->second.startTimer();
313 void passEnded(Pass *P) {
315 if (dynamic_cast<PMDataManager *>(P))
318 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
319 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
320 I->second.stopTimer();
324 static TimingInfo *TheTimeInfo;
326 } // End of anon namespace
328 //===----------------------------------------------------------------------===//
329 // PMTopLevelManager implementation
331 /// Initialize top level manager. Create first pass manager.
332 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
335 MPPassManager *MPP = new MPPassManager(1);
336 MPP->setTopLevelManager(this);
338 activeStack.push(MPP);
340 else if (t == TLM_Function) {
341 FPPassManager *FPP = new FPPassManager(1);
342 FPP->setTopLevelManager(this);
344 activeStack.push(FPP);
348 /// Set pass P as the last user of the given analysis passes.
349 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
352 for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
353 E = AnalysisPasses.end(); I != E; ++I) {
356 // If AP is the last user of other passes then make P last user of
358 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
359 LUE = LastUser.end(); LUI != LUE; ++LUI) {
360 if (LUI->second == AP)
361 LastUser[LUI->first] = P;
366 /// Collect passes whose last user is P
367 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
369 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
370 LUE = LastUser.end(); LUI != LUE; ++LUI)
371 if (LUI->second == P)
372 LastUses.push_back(LUI->first);
375 /// Schedule pass P for execution. Make sure that passes required by
376 /// P are run before P is run. Update analysis info maintained by
377 /// the manager. Remove dead passes. This is a recursive function.
378 void PMTopLevelManager::schedulePass(Pass *P) {
380 // TODO : Allocate function manager for this pass, other wise required set
381 // may be inserted into previous function manager
383 // If this Analysis is already requested by one of the previous pass
384 // and it is still available then do not insert new pass in the queue again.
385 if (findAnalysisPass(P->getPassInfo()))
388 // Give pass a chance to prepare the stage.
389 P->preparePassManager(activeStack);
391 AnalysisUsage AnUsage;
392 P->getAnalysisUsage(AnUsage);
393 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
394 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
395 E = RequiredSet.end(); I != E; ++I) {
397 Pass *AnalysisPass = findAnalysisPass(*I);
399 // Schedule this analysis run first.
400 AnalysisPass = (*I)->createPass();
401 schedulePass(AnalysisPass);
405 // Now all required passes are available.
409 /// Find the pass that implements Analysis AID. Search immutable
410 /// passes and all pass managers. If desired pass is not found
411 /// then return NULL.
412 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
415 // Check pass managers
416 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
417 E = PassManagers.end(); P == NULL && I != E; ++I) {
418 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
419 assert(PMD && "This is not a PassManager");
420 P = PMD->findAnalysisPass(AID, false);
423 // Check other pass managers
424 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
425 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
426 P = (*I)->findAnalysisPass(AID, false);
428 for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
429 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
430 const PassInfo *PI = (*I)->getPassInfo();
434 // If Pass not found then check the interfaces implemented by Immutable Pass
436 const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
437 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
445 // Print passes managed by this top level manager.
446 void PMTopLevelManager::dumpPasses() const {
448 if (PassDebugging < Structure)
451 // Print out the immutable passes
452 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
453 ImmutablePasses[i]->dumpPassStructure(0);
456 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
457 E = PassManagers.end(); I != E; ++I)
458 (*I)->dumpPassStructure(1);
461 void PMTopLevelManager::dumpArguments() const {
463 if (PassDebugging < Arguments)
466 cerr << "Pass Arguments: ";
467 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
468 E = PassManagers.end(); I != E; ++I) {
469 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
470 assert(PMD && "This is not a PassManager");
471 PMD->dumpPassArguments();
476 void PMTopLevelManager::initializeAllAnalysisInfo() {
478 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
479 E = PassManagers.end(); I != E; ++I) {
480 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
481 assert(PMD && "This is not a PassManager");
482 PMD->initializeAnalysisInfo();
485 // Initailize other pass managers
486 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
487 E = IndirectPassManagers.end(); I != E; ++I)
488 (*I)->initializeAnalysisInfo();
492 PMTopLevelManager::~PMTopLevelManager() {
493 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
494 E = PassManagers.end(); I != E; ++I)
497 for (std::vector<ImmutablePass *>::iterator
498 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
501 PassManagers.clear();
504 //===----------------------------------------------------------------------===//
505 // PMDataManager implementation
507 /// Return true IFF pass P's required analysis set does not required new
509 bool PMDataManager::manageablePass(Pass *P) {
512 // If this pass is not preserving information that is required by a
513 // pass maintained by higher level pass manager then do not insert
514 // this pass into current manager. Use new manager. For example,
515 // For example, If FunctionPass F is not preserving ModulePass Info M1
516 // that is used by another ModulePass M2 then do not insert F in
517 // current function pass manager.
521 /// Augement AvailableAnalysis by adding analysis made available by pass P.
522 void PMDataManager::recordAvailableAnalysis(Pass *P) {
524 if (const PassInfo *PI = P->getPassInfo()) {
525 AvailableAnalysis[PI] = P;
527 //This pass is the current implementation of all of the interfaces it
528 //implements as well.
529 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
530 for (unsigned i = 0, e = II.size(); i != e; ++i)
531 AvailableAnalysis[II[i]] = P;
535 // Return true if P preserves high level analysis used by other
536 // passes managed by this manager
537 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
539 AnalysisUsage AnUsage;
540 P->getAnalysisUsage(AnUsage);
542 if (AnUsage.getPreservesAll())
545 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
546 for (std::vector<Pass *>::iterator I = HigherLevelAnalysis.begin(),
547 E = HigherLevelAnalysis.end(); I != E; ++I) {
549 if (std::find(PreservedSet.begin(), PreservedSet.end(), P1->getPassInfo()) ==
550 PreservedSet.end()) {
551 if (!dynamic_cast<ImmutablePass*>(P1))
559 /// Remove Analyss not preserved by Pass P
560 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
561 AnalysisUsage AnUsage;
562 P->getAnalysisUsage(AnUsage);
564 if (AnUsage.getPreservesAll())
567 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
568 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
569 E = AvailableAnalysis.end(); I != E; ) {
570 std::map<AnalysisID, Pass*>::iterator Info = I++;
571 if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
572 PreservedSet.end()) {
573 // Remove this analysis
574 if (!dynamic_cast<ImmutablePass*>(Info->second))
575 AvailableAnalysis.erase(Info);
579 // Check inherited analysis also. If P is not preserving analysis
580 // provided by parent manager then remove it here.
581 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
583 if (!InheritedAnalysis[Index])
586 for (std::map<AnalysisID, Pass*>::iterator
587 I = InheritedAnalysis[Index]->begin(),
588 E = InheritedAnalysis[Index]->end(); I != E; ) {
589 std::map<AnalysisID, Pass *>::iterator Info = I++;
590 if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
591 PreservedSet.end()) {
592 // Remove this analysis
593 if (!dynamic_cast<ImmutablePass*>(Info->second))
594 InheritedAnalysis[Index]->erase(Info);
601 /// Remove analysis passes that are not used any longer
602 void PMDataManager::removeDeadPasses(Pass *P, std::string Msg,
603 enum PassDebuggingString DBG_STR) {
605 std::vector<Pass *> DeadPasses;
606 TPM->collectLastUses(DeadPasses, P);
608 for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
609 E = DeadPasses.end(); I != E; ++I) {
611 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
613 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
614 (*I)->releaseMemory();
615 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
617 std::map<AnalysisID, Pass*>::iterator Pos =
618 AvailableAnalysis.find((*I)->getPassInfo());
620 // It is possible that pass is already removed from the AvailableAnalysis
621 if (Pos != AvailableAnalysis.end())
622 AvailableAnalysis.erase(Pos);
626 /// Add pass P into the PassVector. Update
627 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
628 void PMDataManager::add(Pass *P,
629 bool ProcessAnalysis) {
631 // This manager is going to manage pass P. Set up analysis resolver
633 AnalysisResolver *AR = new AnalysisResolver(*this);
636 // If a FunctionPass F is the last user of ModulePass info M
637 // then the F's manager, not F, records itself as a last user of M.
638 std::vector<Pass *> TransferLastUses;
640 if (ProcessAnalysis) {
642 // At the moment, this pass is the last user of all required passes.
643 std::vector<Pass *> LastUses;
644 std::vector<Pass *> RequiredPasses;
645 unsigned PDepth = this->getDepth();
647 collectRequiredAnalysisPasses(RequiredPasses, P);
648 for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
649 E = RequiredPasses.end(); I != E; ++I) {
650 Pass *PRequired = *I;
653 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
654 RDepth = DM.getDepth();
656 if (PDepth == RDepth)
657 LastUses.push_back(PRequired);
658 else if (PDepth > RDepth) {
659 // Let the parent claim responsibility of last use
660 TransferLastUses.push_back(PRequired);
661 // Keep track of higher level analysis used by this manager.
662 HigherLevelAnalysis.push_back(PRequired);
664 // Note : This feature is not yet implemented
666 "Unable to handle Pass that requires lower level Analysis pass");
670 // Set P as P's last user until someone starts using P.
671 // However, if P is a Pass Manager then it does not need
672 // to record its last user.
673 if (!dynamic_cast<PMDataManager *>(P))
674 LastUses.push_back(P);
675 TPM->setLastUser(LastUses, P);
677 if (!TransferLastUses.empty()) {
678 Pass *My_PM = dynamic_cast<Pass *>(this);
679 TPM->setLastUser(TransferLastUses, My_PM);
680 TransferLastUses.clear();
683 // Take a note of analysis required and made available by this pass.
684 // Remove the analysis not preserved by this pass
685 removeNotPreservedAnalysis(P);
686 recordAvailableAnalysis(P);
690 PassVector.push_back(P);
693 /// Populate RequiredPasses with the analysis pass that are required by
695 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
697 AnalysisUsage AnUsage;
698 P->getAnalysisUsage(AnUsage);
699 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
700 for (std::vector<AnalysisID>::const_iterator
701 I = RequiredSet.begin(), E = RequiredSet.end();
703 Pass *AnalysisPass = findAnalysisPass(*I, true);
704 assert (AnalysisPass && "Analysis pass is not available");
705 RP.push_back(AnalysisPass);
708 const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
709 for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
710 E = IDs.end(); I != E; ++I) {
711 Pass *AnalysisPass = findAnalysisPass(*I, true);
712 assert (AnalysisPass && "Analysis pass is not available");
713 RP.push_back(AnalysisPass);
717 // All Required analyses should be available to the pass as it runs! Here
718 // we fill in the AnalysisImpls member of the pass so that it can
719 // successfully use the getAnalysis() method to retrieve the
720 // implementations it needs.
722 void PMDataManager::initializeAnalysisImpl(Pass *P) {
723 AnalysisUsage AnUsage;
724 P->getAnalysisUsage(AnUsage);
726 for (std::vector<const PassInfo *>::const_iterator
727 I = AnUsage.getRequiredSet().begin(),
728 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
729 Pass *Impl = findAnalysisPass(*I, true);
731 assert(0 && "Analysis used but not available!");
732 AnalysisResolver *AR = P->getResolver();
733 AR->addAnalysisImplsPair(*I, Impl);
737 /// Find the pass that implements Analysis AID. If desired pass is not found
738 /// then return NULL.
739 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
741 // Check if AvailableAnalysis map has one entry.
742 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
744 if (I != AvailableAnalysis.end())
747 // Search Parents through TopLevelManager
749 return TPM->findAnalysisPass(AID);
754 // Print list of passes that are last used by P.
755 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
757 std::vector<Pass *> LUses;
759 assert (TPM && "Top Level Manager is missing");
760 TPM->collectLastUses(LUses, P);
762 for (std::vector<Pass *>::iterator I = LUses.begin(),
763 E = LUses.end(); I != E; ++I) {
764 llvm::cerr << "--" << std::string(Offset*2, ' ');
765 (*I)->dumpPassStructure(0);
769 void PMDataManager::dumpPassArguments() const {
770 for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
771 E = PassVector.end(); I != E; ++I) {
772 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
773 PMD->dumpPassArguments();
775 if (const PassInfo *PI = (*I)->getPassInfo())
776 if (!PI->isAnalysisGroup())
777 cerr << " -" << PI->getPassArgument();
781 void PMDataManager:: dumpPassInfo(Pass *P, enum PassDebuggingString S1,
782 enum PassDebuggingString S2,
784 if (PassDebugging < Executions)
786 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
789 cerr << "Executing Pass '" << P->getPassName();
791 case MODIFICATION_MSG:
792 cerr << "' Made Modification '" << P->getPassName();
795 cerr << " Freeing Pass '" << P->getPassName();
801 case ON_BASICBLOCK_MSG:
802 cerr << "' on BasicBlock '" << Msg << "...\n";
804 case ON_FUNCTION_MSG:
805 cerr << "' on Function '" << Msg << "...\n";
808 cerr << "' on Module '" << Msg << "...\n";
811 cerr << "' on Loop " << Msg << "...\n";
814 cerr << "' on Call Graph " << Msg << "...\n";
821 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
822 const std::vector<AnalysisID> &Set)
824 if (PassDebugging >= Details && !Set.empty()) {
825 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
826 for (unsigned i = 0; i != Set.size(); ++i) {
828 cerr << " " << Set[i]->getPassName();
835 PMDataManager::~PMDataManager() {
837 for (std::vector<Pass *>::iterator I = PassVector.begin(),
838 E = PassVector.end(); I != E; ++I)
844 //===----------------------------------------------------------------------===//
845 // NOTE: Is this the right place to define this method ?
846 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
847 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
848 return PM.findAnalysisPass(ID, dir);
851 //===----------------------------------------------------------------------===//
852 // BBPassManager implementation
854 /// Execute all of the passes scheduled for execution by invoking
855 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
856 /// the function, and if so, return true.
858 BBPassManager::runOnFunction(Function &F) {
860 if (F.isDeclaration())
863 bool Changed = doInitialization(F);
865 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
866 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
867 BasicBlockPass *BP = getContainedPass(Index);
868 AnalysisUsage AnUsage;
869 BP->getAnalysisUsage(AnUsage);
871 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
872 dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
874 initializeAnalysisImpl(BP);
876 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
877 Changed |= BP->runOnBasicBlock(*I);
878 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
881 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
882 dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
884 removeNotPreservedAnalysis(BP);
885 recordAvailableAnalysis(BP);
886 removeDeadPasses(BP, (*I).getName(), ON_BASICBLOCK_MSG);
889 return Changed |= doFinalization(F);
892 // Implement doInitialization and doFinalization
893 inline bool BBPassManager::doInitialization(Module &M) {
894 bool Changed = false;
896 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
897 BasicBlockPass *BP = getContainedPass(Index);
898 Changed |= BP->doInitialization(M);
904 inline bool BBPassManager::doFinalization(Module &M) {
905 bool Changed = false;
907 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
908 BasicBlockPass *BP = getContainedPass(Index);
909 Changed |= BP->doFinalization(M);
915 inline bool BBPassManager::doInitialization(Function &F) {
916 bool Changed = false;
918 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
919 BasicBlockPass *BP = getContainedPass(Index);
920 Changed |= BP->doInitialization(F);
926 inline bool BBPassManager::doFinalization(Function &F) {
927 bool Changed = false;
929 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
930 BasicBlockPass *BP = getContainedPass(Index);
931 Changed |= BP->doFinalization(F);
938 //===----------------------------------------------------------------------===//
939 // FunctionPassManager implementation
941 /// Create new Function pass manager
942 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
943 FPM = new FunctionPassManagerImpl(0);
944 // FPM is the top level manager.
945 FPM->setTopLevelManager(FPM);
947 PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
948 AnalysisResolver *AR = new AnalysisResolver(*PMD);
949 FPM->setResolver(AR);
954 FunctionPassManager::~FunctionPassManager() {
958 /// add - Add a pass to the queue of passes to run. This passes
959 /// ownership of the Pass to the PassManager. When the
960 /// PassManager_X is destroyed, the pass will be destroyed as well, so
961 /// there is no need to delete the pass. (TODO delete passes.)
962 /// This implies that all passes MUST be allocated with 'new'.
963 void FunctionPassManager::add(Pass *P) {
967 /// run - Execute all of the passes scheduled for execution. Keep
968 /// track of whether any of the passes modifies the function, and if
971 bool FunctionPassManager::run(Function &F) {
973 if (MP->materializeFunction(&F, &errstr)) {
974 cerr << "Error reading bytecode file: " << errstr << "\n";
981 /// doInitialization - Run all of the initializers for the function passes.
983 bool FunctionPassManager::doInitialization() {
984 return FPM->doInitialization(*MP->getModule());
987 /// doFinalization - Run all of the initializers for the function passes.
989 bool FunctionPassManager::doFinalization() {
990 return FPM->doFinalization(*MP->getModule());
993 //===----------------------------------------------------------------------===//
994 // FunctionPassManagerImpl implementation
996 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
997 bool Changed = false;
999 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1000 FPPassManager *FP = getContainedManager(Index);
1001 Changed |= FP->doInitialization(M);
1007 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1008 bool Changed = false;
1010 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1011 FPPassManager *FP = getContainedManager(Index);
1012 Changed |= FP->doFinalization(M);
1018 // Execute all the passes managed by this top level manager.
1019 // Return true if any function is modified by a pass.
1020 bool FunctionPassManagerImpl::run(Function &F) {
1022 bool Changed = false;
1024 TimingInfo::createTheTimeInfo();
1029 initializeAllAnalysisInfo();
1030 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1031 FPPassManager *FP = getContainedManager(Index);
1032 Changed |= FP->runOnFunction(F);
1037 //===----------------------------------------------------------------------===//
1038 // FPPassManager implementation
1040 /// Print passes managed by this manager
1041 void FPPassManager::dumpPassStructure(unsigned Offset) {
1042 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1043 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1044 FunctionPass *FP = getContainedPass(Index);
1045 FP->dumpPassStructure(Offset + 1);
1046 dumpLastUses(FP, Offset+1);
1051 /// Execute all of the passes scheduled for execution by invoking
1052 /// runOnFunction method. Keep track of whether any of the passes modifies
1053 /// the function, and if so, return true.
1054 bool FPPassManager::runOnFunction(Function &F) {
1056 bool Changed = false;
1058 if (F.isDeclaration())
1061 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1062 FunctionPass *FP = getContainedPass(Index);
1064 AnalysisUsage AnUsage;
1065 FP->getAnalysisUsage(AnUsage);
1067 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1068 dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1070 initializeAnalysisImpl(FP);
1072 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1073 Changed |= FP->runOnFunction(F);
1074 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1077 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1078 dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1080 removeNotPreservedAnalysis(FP);
1081 recordAvailableAnalysis(FP);
1082 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1087 bool FPPassManager::runOnModule(Module &M) {
1089 bool Changed = doInitialization(M);
1091 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1092 this->runOnFunction(*I);
1094 return Changed |= doFinalization(M);
1097 inline bool FPPassManager::doInitialization(Module &M) {
1098 bool Changed = false;
1100 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1101 FunctionPass *FP = getContainedPass(Index);
1102 Changed |= FP->doInitialization(M);
1108 inline bool FPPassManager::doFinalization(Module &M) {
1109 bool Changed = false;
1111 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1112 FunctionPass *FP = getContainedPass(Index);
1113 Changed |= FP->doFinalization(M);
1119 //===----------------------------------------------------------------------===//
1120 // MPPassManager implementation
1122 /// Execute all of the passes scheduled for execution by invoking
1123 /// runOnModule method. Keep track of whether any of the passes modifies
1124 /// the module, and if so, return true.
1126 MPPassManager::runOnModule(Module &M) {
1127 bool Changed = false;
1129 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1130 ModulePass *MP = getContainedPass(Index);
1132 AnalysisUsage AnUsage;
1133 MP->getAnalysisUsage(AnUsage);
1135 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1136 dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1138 initializeAnalysisImpl(MP);
1140 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1141 Changed |= MP->runOnModule(M);
1142 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1145 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1146 M.getModuleIdentifier());
1147 dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1149 removeNotPreservedAnalysis(MP);
1150 recordAvailableAnalysis(MP);
1151 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1156 //===----------------------------------------------------------------------===//
1157 // PassManagerImpl implementation
1159 /// run - Execute all of the passes scheduled for execution. Keep track of
1160 /// whether any of the passes modifies the module, and if so, return true.
1161 bool PassManagerImpl::run(Module &M) {
1163 bool Changed = false;
1165 TimingInfo::createTheTimeInfo();
1170 initializeAllAnalysisInfo();
1171 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1172 MPPassManager *MP = getContainedManager(Index);
1173 Changed |= MP->runOnModule(M);
1178 //===----------------------------------------------------------------------===//
1179 // PassManager implementation
1181 /// Create new pass manager
1182 PassManager::PassManager() {
1183 PM = new PassManagerImpl(0);
1184 // PM is the top level manager
1185 PM->setTopLevelManager(PM);
1188 PassManager::~PassManager() {
1192 /// add - Add a pass to the queue of passes to run. This passes ownership of
1193 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1194 /// will be destroyed as well, so there is no need to delete the pass. This
1195 /// implies that all passes MUST be allocated with 'new'.
1197 PassManager::add(Pass *P) {
1201 /// run - Execute all of the passes scheduled for execution. Keep track of
1202 /// whether any of the passes modifies the module, and if so, return true.
1204 PassManager::run(Module &M) {
1208 //===----------------------------------------------------------------------===//
1209 // TimingInfo Class - This class is used to calculate information about the
1210 // amount of time each pass takes to execute. This only happens with
1211 // -time-passes is enabled on the command line.
1213 bool llvm::TimePassesIsEnabled = false;
1214 static cl::opt<bool,true>
1215 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1216 cl::desc("Time each pass, printing elapsed time for each on exit"));
1218 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1219 // a non null value (if the -time-passes option is enabled) or it leaves it
1220 // null. It may be called multiple times.
1221 void TimingInfo::createTheTimeInfo() {
1222 if (!TimePassesIsEnabled || TheTimeInfo) return;
1224 // Constructed the first time this is called, iff -time-passes is enabled.
1225 // This guarantees that the object will be constructed before static globals,
1226 // thus it will be destroyed before them.
1227 static ManagedStatic<TimingInfo> TTI;
1228 TheTimeInfo = &*TTI;
1231 /// If TimingInfo is enabled then start pass timer.
1232 void StartPassTimer(Pass *P) {
1234 TheTimeInfo->passStarted(P);
1237 /// If TimingInfo is enabled then stop pass timer.
1238 void StopPassTimer(Pass *P) {
1240 TheTimeInfo->passEnded(P);
1243 //===----------------------------------------------------------------------===//
1244 // PMStack implementation
1247 // Pop Pass Manager from the stack and clear its analysis info.
1248 void PMStack::pop() {
1250 PMDataManager *Top = this->top();
1251 Top->initializeAnalysisInfo();
1256 // Push PM on the stack and set its top level manager.
1257 void PMStack::push(Pass *P) {
1259 PMDataManager *Top = NULL;
1260 PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1261 assert (PM && "Unable to push. Pass Manager expected");
1263 if (this->empty()) {
1268 PMTopLevelManager *TPM = Top->getTopLevelManager();
1270 assert (TPM && "Unable to find top level manager");
1271 TPM->addIndirectPassManager(PM);
1272 PM->setTopLevelManager(TPM);
1275 AnalysisResolver *AR = new AnalysisResolver(*Top);
1281 // Dump content of the pass manager stack.
1282 void PMStack::dump() {
1283 for(std::deque<PMDataManager *>::iterator I = S.begin(),
1284 E = S.end(); I != E; ++I) {
1285 Pass *P = dynamic_cast<Pass *>(*I);
1286 printf ("%s ", P->getPassName());
1292 /// Find appropriate Module Pass Manager in the PM Stack and
1293 /// add self into that manager.
1294 void ModulePass::assignPassManager(PMStack &PMS,
1295 PassManagerType PreferredType) {
1297 // Find Module Pass Manager
1298 while(!PMS.empty()) {
1299 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1300 if (TopPMType == PreferredType)
1301 break; // We found desired pass manager
1302 else if (TopPMType > PMT_ModulePassManager)
1303 PMS.pop(); // Pop children pass managers
1308 PMS.top()->add(this);
1311 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1312 /// in the PM Stack and add self into that manager.
1313 void FunctionPass::assignPassManager(PMStack &PMS,
1314 PassManagerType PreferredType) {
1316 // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1317 while(!PMS.empty()) {
1318 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1323 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1325 // Create new Function Pass Manager
1327 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1328 PMDataManager *PMD = PMS.top();
1330 // [1] Create new Function Pass Manager
1331 FPP = new FPPassManager(PMD->getDepth() + 1);
1333 // [2] Set up new manager's top level manager
1334 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1335 TPM->addIndirectPassManager(FPP);
1337 // [3] Assign manager to manage this new manager. This may create
1338 // and push new managers into PMS
1339 Pass *P = dynamic_cast<Pass *>(FPP);
1341 // If Call Graph Pass Manager is active then use it to manage
1342 // this new Function Pass manager.
1343 if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1344 P->assignPassManager(PMS, PMT_CallGraphPassManager);
1346 P->assignPassManager(PMS);
1348 // [4] Push new manager into PMS
1352 // Assign FPP as the manager of this pass.
1356 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1357 /// in the PM Stack and add self into that manager.
1358 void BasicBlockPass::assignPassManager(PMStack &PMS,
1359 PassManagerType PreferredType) {
1361 BBPassManager *BBP = NULL;
1363 // Basic Pass Manager is a leaf pass manager. It does not handle
1364 // any other pass manager.
1366 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1369 // If leaf manager is not Basic Block Pass manager then create new
1370 // basic Block Pass manager.
1373 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1374 PMDataManager *PMD = PMS.top();
1376 // [1] Create new Basic Block Manager
1377 BBP = new BBPassManager(PMD->getDepth() + 1);
1379 // [2] Set up new manager's top level manager
1380 // Basic Block Pass Manager does not live by itself
1381 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1382 TPM->addIndirectPassManager(BBP);
1384 // [3] Assign manager to manage this new manager. This may create
1385 // and push new managers into PMS
1386 Pass *P = dynamic_cast<Pass *>(BBP);
1387 P->assignPassManager(PMS);
1389 // [4] Push new manager into PMS
1393 // Assign BBP as the manager of this pass.