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 /// Return function pass corresponding to PassInfo PI, that is
199 /// required by module pass MP. Instantiate analysis pass, by using
200 /// its runOnFunction() for function F.
201 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
203 virtual const char *getPassName() const {
204 return "Module Pass Manager";
207 // Print passes managed by this manager
208 void dumpPassStructure(unsigned Offset) {
209 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
210 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
211 ModulePass *MP = getContainedPass(Index);
212 MP->dumpPassStructure(Offset + 1);
213 dumpLastUses(MP, Offset+1);
217 ModulePass *getContainedPass(unsigned N) {
218 assert ( N < PassVector.size() && "Pass number out of range!");
219 ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
223 virtual PassManagerType getPassManagerType() const {
224 return PMT_ModulePassManager;
228 /// Collection of on the fly FPPassManagers. These managers manage
229 /// function passes that are required by module passes.
230 std::map<Pass *, FPPassManager *> OnTheFlyManagers;
233 //===----------------------------------------------------------------------===//
236 /// PassManagerImpl manages MPPassManagers
237 class PassManagerImpl : public Pass,
238 public PMDataManager,
239 public PMTopLevelManager {
243 PassManagerImpl(int Depth) : PMDataManager(Depth),
244 PMTopLevelManager(TLM_Pass) { }
246 /// add - Add a pass to the queue of passes to run. This passes ownership of
247 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
248 /// will be destroyed as well, so there is no need to delete the pass. This
249 /// implies that all passes MUST be allocated with 'new'.
254 /// run - Execute all of the passes scheduled for execution. Keep track of
255 /// whether any of the passes modifies the module, and if so, return true.
258 /// Pass Manager itself does not invalidate any analysis info.
259 void getAnalysisUsage(AnalysisUsage &Info) const {
260 Info.setPreservesAll();
263 inline void addTopLevelPass(Pass *P) {
265 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
267 // P is a immutable pass and it will be managed by this
268 // top level manager. Set up analysis resolver to connect them.
269 AnalysisResolver *AR = new AnalysisResolver(*this);
271 initializeAnalysisImpl(P);
272 addImmutablePass(IP);
273 recordAvailableAnalysis(IP);
275 P->assignPassManager(activeStack);
280 MPPassManager *getContainedManager(unsigned N) {
281 assert ( N < PassManagers.size() && "Pass number out of range!");
282 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
288 } // End of llvm namespace
292 //===----------------------------------------------------------------------===//
293 // TimingInfo Class - This class is used to calculate information about the
294 // amount of time each pass takes to execute. This only happens when
295 // -time-passes is enabled on the command line.
298 class VISIBILITY_HIDDEN TimingInfo {
299 std::map<Pass*, Timer> TimingData;
303 // Use 'create' member to get this.
304 TimingInfo() : TG("... Pass execution timing report ...") {}
306 // TimingDtor - Print out information about timing information
308 // Delete all of the timers...
310 // TimerGroup is deleted next, printing the report.
313 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
314 // to a non null value (if the -time-passes option is enabled) or it leaves it
315 // null. It may be called multiple times.
316 static void createTheTimeInfo();
318 void passStarted(Pass *P) {
320 if (dynamic_cast<PMDataManager *>(P))
323 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
324 if (I == TimingData.end())
325 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
326 I->second.startTimer();
328 void passEnded(Pass *P) {
330 if (dynamic_cast<PMDataManager *>(P))
333 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
334 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
335 I->second.stopTimer();
339 static TimingInfo *TheTimeInfo;
341 } // End of anon namespace
343 //===----------------------------------------------------------------------===//
344 // PMTopLevelManager implementation
346 /// Initialize top level manager. Create first pass manager.
347 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
350 MPPassManager *MPP = new MPPassManager(1);
351 MPP->setTopLevelManager(this);
353 activeStack.push(MPP);
355 else if (t == TLM_Function) {
356 FPPassManager *FPP = new FPPassManager(1);
357 FPP->setTopLevelManager(this);
359 activeStack.push(FPP);
363 /// Set pass P as the last user of the given analysis passes.
364 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
367 for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
368 E = AnalysisPasses.end(); I != E; ++I) {
375 // If AP is the last user of other passes then make P last user of
377 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
378 LUE = LastUser.end(); LUI != LUE; ++LUI) {
379 if (LUI->second == AP)
380 LastUser[LUI->first] = P;
385 /// Collect passes whose last user is P
386 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
388 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
389 LUE = LastUser.end(); LUI != LUE; ++LUI)
390 if (LUI->second == P)
391 LastUses.push_back(LUI->first);
394 /// Schedule pass P for execution. Make sure that passes required by
395 /// P are run before P is run. Update analysis info maintained by
396 /// the manager. Remove dead passes. This is a recursive function.
397 void PMTopLevelManager::schedulePass(Pass *P) {
399 // TODO : Allocate function manager for this pass, other wise required set
400 // may be inserted into previous function manager
402 // If this Analysis is already requested by one of the previous pass
403 // and it is still available then do not insert new pass in the queue again.
404 if (findAnalysisPass(P->getPassInfo()))
407 // Give pass a chance to prepare the stage.
408 P->preparePassManager(activeStack);
410 AnalysisUsage AnUsage;
411 P->getAnalysisUsage(AnUsage);
412 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
413 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
414 E = RequiredSet.end(); I != E; ++I) {
416 Pass *AnalysisPass = findAnalysisPass(*I);
418 AnalysisPass = (*I)->createPass();
419 // Schedule this analysis run first only if it is not a lower level
420 // analysis pass. Lower level analsyis passes are run on the fly.
421 if (P->getPotentialPassManagerType () >=
422 AnalysisPass->getPotentialPassManagerType())
423 schedulePass(AnalysisPass);
429 // Now all required passes are available.
433 /// Find the pass that implements Analysis AID. Search immutable
434 /// passes and all pass managers. If desired pass is not found
435 /// then return NULL.
436 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
439 // Check pass managers
440 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
441 E = PassManagers.end(); P == NULL && I != E; ++I) {
442 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
443 assert(PMD && "This is not a PassManager");
444 P = PMD->findAnalysisPass(AID, false);
447 // Check other pass managers
448 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
449 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
450 P = (*I)->findAnalysisPass(AID, false);
452 for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
453 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
454 const PassInfo *PI = (*I)->getPassInfo();
458 // If Pass not found then check the interfaces implemented by Immutable Pass
460 const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
461 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
469 // Print passes managed by this top level manager.
470 void PMTopLevelManager::dumpPasses() const {
472 if (PassDebugging < Structure)
475 // Print out the immutable passes
476 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
477 ImmutablePasses[i]->dumpPassStructure(0);
480 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
481 E = PassManagers.end(); I != E; ++I)
482 (*I)->dumpPassStructure(1);
485 void PMTopLevelManager::dumpArguments() const {
487 if (PassDebugging < Arguments)
490 cerr << "Pass Arguments: ";
491 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
492 E = PassManagers.end(); I != E; ++I) {
493 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
494 assert(PMD && "This is not a PassManager");
495 PMD->dumpPassArguments();
500 void PMTopLevelManager::initializeAllAnalysisInfo() {
502 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
503 E = PassManagers.end(); I != E; ++I) {
504 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
505 assert(PMD && "This is not a PassManager");
506 PMD->initializeAnalysisInfo();
509 // Initailize other pass managers
510 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
511 E = IndirectPassManagers.end(); I != E; ++I)
512 (*I)->initializeAnalysisInfo();
516 PMTopLevelManager::~PMTopLevelManager() {
517 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
518 E = PassManagers.end(); I != E; ++I)
521 for (std::vector<ImmutablePass *>::iterator
522 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
525 PassManagers.clear();
528 //===----------------------------------------------------------------------===//
529 // PMDataManager implementation
531 /// Return true IFF pass P's required analysis set does not required new
533 bool PMDataManager::manageablePass(Pass *P) {
536 // If this pass is not preserving information that is required by a
537 // pass maintained by higher level pass manager then do not insert
538 // this pass into current manager. Use new manager. For example,
539 // For example, If FunctionPass F is not preserving ModulePass Info M1
540 // that is used by another ModulePass M2 then do not insert F in
541 // current function pass manager.
545 /// Augement AvailableAnalysis by adding analysis made available by pass P.
546 void PMDataManager::recordAvailableAnalysis(Pass *P) {
548 if (const PassInfo *PI = P->getPassInfo()) {
549 AvailableAnalysis[PI] = P;
551 //This pass is the current implementation of all of the interfaces it
552 //implements as well.
553 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
554 for (unsigned i = 0, e = II.size(); i != e; ++i)
555 AvailableAnalysis[II[i]] = P;
559 // Return true if P preserves high level analysis used by other
560 // passes managed by this manager
561 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
563 AnalysisUsage AnUsage;
564 P->getAnalysisUsage(AnUsage);
566 if (AnUsage.getPreservesAll())
569 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
570 for (std::vector<Pass *>::iterator I = HigherLevelAnalysis.begin(),
571 E = HigherLevelAnalysis.end(); I != E; ++I) {
573 if (!dynamic_cast<ImmutablePass*>(P1)
574 && std::find(PreservedSet.begin(), PreservedSet.end(), P1->getPassInfo()) ==
582 /// Remove Analyss not preserved by Pass P
583 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
584 AnalysisUsage AnUsage;
585 P->getAnalysisUsage(AnUsage);
587 if (AnUsage.getPreservesAll())
590 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
591 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
592 E = AvailableAnalysis.end(); I != E; ) {
593 std::map<AnalysisID, Pass*>::iterator Info = I++;
594 if (!dynamic_cast<ImmutablePass*>(Info->second)
595 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
597 // Remove this analysis
598 AvailableAnalysis.erase(Info);
601 // Check inherited analysis also. If P is not preserving analysis
602 // provided by parent manager then remove it here.
603 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
605 if (!InheritedAnalysis[Index])
608 for (std::map<AnalysisID, Pass*>::iterator
609 I = InheritedAnalysis[Index]->begin(),
610 E = InheritedAnalysis[Index]->end(); I != E; ) {
611 std::map<AnalysisID, Pass *>::iterator Info = I++;
612 if (!dynamic_cast<ImmutablePass*>(Info->second)
613 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
615 // Remove this analysis
616 InheritedAnalysis[Index]->erase(Info);
622 /// Remove analysis passes that are not used any longer
623 void PMDataManager::removeDeadPasses(Pass *P, std::string Msg,
624 enum PassDebuggingString DBG_STR) {
626 std::vector<Pass *> DeadPasses;
631 TPM->collectLastUses(DeadPasses, P);
633 for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
634 E = DeadPasses.end(); I != E; ++I) {
636 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
638 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
639 (*I)->releaseMemory();
640 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
642 std::map<AnalysisID, Pass*>::iterator Pos =
643 AvailableAnalysis.find((*I)->getPassInfo());
645 // It is possible that pass is already removed from the AvailableAnalysis
646 if (Pos != AvailableAnalysis.end())
647 AvailableAnalysis.erase(Pos);
651 /// Add pass P into the PassVector. Update
652 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
653 void PMDataManager::add(Pass *P,
654 bool ProcessAnalysis) {
656 // This manager is going to manage pass P. Set up analysis resolver
658 AnalysisResolver *AR = new AnalysisResolver(*this);
661 // If a FunctionPass F is the last user of ModulePass info M
662 // then the F's manager, not F, records itself as a last user of M.
663 std::vector<Pass *> TransferLastUses;
665 if (ProcessAnalysis) {
667 // At the moment, this pass is the last user of all required passes.
668 std::vector<Pass *> LastUses;
669 SmallVector<Pass *, 8> RequiredPasses;
670 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
672 unsigned PDepth = this->getDepth();
674 collectRequiredAnalysis(RequiredPasses,
675 ReqAnalysisNotAvailable, P);
676 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
677 E = RequiredPasses.end(); I != E; ++I) {
678 Pass *PRequired = *I;
681 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
682 RDepth = DM.getDepth();
684 if (PDepth == RDepth)
685 LastUses.push_back(PRequired);
686 else if (PDepth > RDepth) {
687 // Let the parent claim responsibility of last use
688 TransferLastUses.push_back(PRequired);
689 // Keep track of higher level analysis used by this manager.
690 HigherLevelAnalysis.push_back(PRequired);
692 assert (0 && "Unable to accomodate Required Pass");
695 // Set P as P's last user until someone starts using P.
696 // However, if P is a Pass Manager then it does not need
697 // to record its last user.
698 if (!dynamic_cast<PMDataManager *>(P))
699 LastUses.push_back(P);
700 TPM->setLastUser(LastUses, P);
702 if (!TransferLastUses.empty()) {
703 Pass *My_PM = dynamic_cast<Pass *>(this);
704 TPM->setLastUser(TransferLastUses, My_PM);
705 TransferLastUses.clear();
708 // Now, take care of required analysises that are not available.
709 for (SmallVector<AnalysisID, 8>::iterator
710 I = ReqAnalysisNotAvailable.begin(),
711 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
712 Pass *AnalysisPass = (*I)->createPass();
713 this->addLowerLevelRequiredPass(P, AnalysisPass);
716 // Take a note of analysis required and made available by this pass.
717 // Remove the analysis not preserved by this pass
718 removeNotPreservedAnalysis(P);
719 recordAvailableAnalysis(P);
723 PassVector.push_back(P);
727 /// Populate RP with analysis pass that are required by
728 /// pass P and are available. Populate RP_NotAvail with analysis
729 /// pass that are required by pass P but are not available.
730 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
731 SmallVector<AnalysisID, 8> &RP_NotAvail,
733 AnalysisUsage AnUsage;
734 P->getAnalysisUsage(AnUsage);
735 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
736 for (std::vector<AnalysisID>::const_iterator
737 I = RequiredSet.begin(), E = RequiredSet.end();
740 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
741 RP.push_back(AnalysisPass);
743 RP_NotAvail.push_back(AID);
746 const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
747 for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
748 E = IDs.end(); I != E; ++I) {
750 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
751 RP.push_back(AnalysisPass);
753 RP_NotAvail.push_back(AID);
757 // All Required analyses should be available to the pass as it runs! Here
758 // we fill in the AnalysisImpls member of the pass so that it can
759 // successfully use the getAnalysis() method to retrieve the
760 // implementations it needs.
762 void PMDataManager::initializeAnalysisImpl(Pass *P) {
763 AnalysisUsage AnUsage;
764 P->getAnalysisUsage(AnUsage);
766 for (std::vector<const PassInfo *>::const_iterator
767 I = AnUsage.getRequiredSet().begin(),
768 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
769 Pass *Impl = findAnalysisPass(*I, true);
771 assert(0 && "Analysis used but not available!");
772 AnalysisResolver *AR = P->getResolver();
773 AR->addAnalysisImplsPair(*I, Impl);
777 /// Find the pass that implements Analysis AID. If desired pass is not found
778 /// then return NULL.
779 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
781 // Check if AvailableAnalysis map has one entry.
782 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
784 if (I != AvailableAnalysis.end())
787 // Search Parents through TopLevelManager
789 return TPM->findAnalysisPass(AID);
794 // Print list of passes that are last used by P.
795 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
797 std::vector<Pass *> LUses;
799 assert (TPM && "Top Level Manager is missing");
800 TPM->collectLastUses(LUses, P);
802 for (std::vector<Pass *>::iterator I = LUses.begin(),
803 E = LUses.end(); I != E; ++I) {
804 llvm::cerr << "--" << std::string(Offset*2, ' ');
805 (*I)->dumpPassStructure(0);
809 void PMDataManager::dumpPassArguments() const {
810 for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
811 E = PassVector.end(); I != E; ++I) {
812 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
813 PMD->dumpPassArguments();
815 if (const PassInfo *PI = (*I)->getPassInfo())
816 if (!PI->isAnalysisGroup())
817 cerr << " -" << PI->getPassArgument();
821 void PMDataManager:: dumpPassInfo(Pass *P, enum PassDebuggingString S1,
822 enum PassDebuggingString S2,
824 if (PassDebugging < Executions)
826 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
829 cerr << "Executing Pass '" << P->getPassName();
831 case MODIFICATION_MSG:
832 cerr << "' Made Modification '" << P->getPassName();
835 cerr << " Freeing Pass '" << P->getPassName();
841 case ON_BASICBLOCK_MSG:
842 cerr << "' on BasicBlock '" << Msg << "...\n";
844 case ON_FUNCTION_MSG:
845 cerr << "' on Function '" << Msg << "...\n";
848 cerr << "' on Module '" << Msg << "...\n";
851 cerr << "' on Loop " << Msg << "...\n";
854 cerr << "' on Call Graph " << Msg << "...\n";
861 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
862 const std::vector<AnalysisID> &Set)
864 if (PassDebugging >= Details && !Set.empty()) {
865 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
866 for (unsigned i = 0; i != Set.size(); ++i) {
868 cerr << " " << Set[i]->getPassName();
875 PMDataManager::~PMDataManager() {
877 for (std::vector<Pass *>::iterator I = PassVector.begin(),
878 E = PassVector.end(); I != E; ++I)
884 //===----------------------------------------------------------------------===//
885 // NOTE: Is this the right place to define this method ?
886 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
887 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
888 return PM.findAnalysisPass(ID, dir);
891 //===----------------------------------------------------------------------===//
892 // BBPassManager implementation
894 /// Execute all of the passes scheduled for execution by invoking
895 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
896 /// the function, and if so, return true.
898 BBPassManager::runOnFunction(Function &F) {
900 if (F.isDeclaration())
903 bool Changed = doInitialization(F);
905 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
906 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
907 BasicBlockPass *BP = getContainedPass(Index);
908 AnalysisUsage AnUsage;
909 BP->getAnalysisUsage(AnUsage);
911 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
912 dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
914 initializeAnalysisImpl(BP);
916 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
917 Changed |= BP->runOnBasicBlock(*I);
918 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
921 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
922 dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
924 removeNotPreservedAnalysis(BP);
925 recordAvailableAnalysis(BP);
926 removeDeadPasses(BP, (*I).getName(), ON_BASICBLOCK_MSG);
929 return Changed |= doFinalization(F);
932 // Implement doInitialization and doFinalization
933 inline bool BBPassManager::doInitialization(Module &M) {
934 bool Changed = false;
936 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
937 BasicBlockPass *BP = getContainedPass(Index);
938 Changed |= BP->doInitialization(M);
944 inline bool BBPassManager::doFinalization(Module &M) {
945 bool Changed = false;
947 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
948 BasicBlockPass *BP = getContainedPass(Index);
949 Changed |= BP->doFinalization(M);
955 inline bool BBPassManager::doInitialization(Function &F) {
956 bool Changed = false;
958 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
959 BasicBlockPass *BP = getContainedPass(Index);
960 Changed |= BP->doInitialization(F);
966 inline bool BBPassManager::doFinalization(Function &F) {
967 bool Changed = false;
969 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
970 BasicBlockPass *BP = getContainedPass(Index);
971 Changed |= BP->doFinalization(F);
978 //===----------------------------------------------------------------------===//
979 // FunctionPassManager implementation
981 /// Create new Function pass manager
982 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
983 FPM = new FunctionPassManagerImpl(0);
984 // FPM is the top level manager.
985 FPM->setTopLevelManager(FPM);
987 PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
988 AnalysisResolver *AR = new AnalysisResolver(*PMD);
989 FPM->setResolver(AR);
994 FunctionPassManager::~FunctionPassManager() {
998 /// add - Add a pass to the queue of passes to run. This passes
999 /// ownership of the Pass to the PassManager. When the
1000 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1001 /// there is no need to delete the pass. (TODO delete passes.)
1002 /// This implies that all passes MUST be allocated with 'new'.
1003 void FunctionPassManager::add(Pass *P) {
1007 /// run - Execute all of the passes scheduled for execution. Keep
1008 /// track of whether any of the passes modifies the function, and if
1009 /// so, return true.
1011 bool FunctionPassManager::run(Function &F) {
1013 if (MP->materializeFunction(&F, &errstr)) {
1014 cerr << "Error reading bytecode file: " << errstr << "\n";
1021 /// doInitialization - Run all of the initializers for the function passes.
1023 bool FunctionPassManager::doInitialization() {
1024 return FPM->doInitialization(*MP->getModule());
1027 /// doFinalization - Run all of the initializers for the function passes.
1029 bool FunctionPassManager::doFinalization() {
1030 return FPM->doFinalization(*MP->getModule());
1033 //===----------------------------------------------------------------------===//
1034 // FunctionPassManagerImpl implementation
1036 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1037 bool Changed = false;
1039 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1040 FPPassManager *FP = getContainedManager(Index);
1041 Changed |= FP->doInitialization(M);
1047 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1048 bool Changed = false;
1050 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1051 FPPassManager *FP = getContainedManager(Index);
1052 Changed |= FP->doFinalization(M);
1058 // Execute all the passes managed by this top level manager.
1059 // Return true if any function is modified by a pass.
1060 bool FunctionPassManagerImpl::run(Function &F) {
1062 bool Changed = false;
1064 TimingInfo::createTheTimeInfo();
1069 initializeAllAnalysisInfo();
1070 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1071 FPPassManager *FP = getContainedManager(Index);
1072 Changed |= FP->runOnFunction(F);
1077 //===----------------------------------------------------------------------===//
1078 // FPPassManager implementation
1080 /// Print passes managed by this manager
1081 void FPPassManager::dumpPassStructure(unsigned Offset) {
1082 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1083 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1084 FunctionPass *FP = getContainedPass(Index);
1085 FP->dumpPassStructure(Offset + 1);
1086 dumpLastUses(FP, Offset+1);
1091 /// Execute all of the passes scheduled for execution by invoking
1092 /// runOnFunction method. Keep track of whether any of the passes modifies
1093 /// the function, and if so, return true.
1094 bool FPPassManager::runOnFunction(Function &F) {
1096 bool Changed = false;
1098 if (F.isDeclaration())
1101 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1102 FunctionPass *FP = getContainedPass(Index);
1104 AnalysisUsage AnUsage;
1105 FP->getAnalysisUsage(AnUsage);
1107 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1108 dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1110 initializeAnalysisImpl(FP);
1112 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1113 Changed |= FP->runOnFunction(F);
1114 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1117 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1118 dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1120 removeNotPreservedAnalysis(FP);
1121 recordAvailableAnalysis(FP);
1122 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1127 bool FPPassManager::runOnModule(Module &M) {
1129 bool Changed = doInitialization(M);
1131 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1132 this->runOnFunction(*I);
1134 return Changed |= doFinalization(M);
1137 inline bool FPPassManager::doInitialization(Module &M) {
1138 bool Changed = false;
1140 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1141 FunctionPass *FP = getContainedPass(Index);
1142 Changed |= FP->doInitialization(M);
1148 inline bool FPPassManager::doFinalization(Module &M) {
1149 bool Changed = false;
1151 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1152 FunctionPass *FP = getContainedPass(Index);
1153 Changed |= FP->doFinalization(M);
1159 //===----------------------------------------------------------------------===//
1160 // MPPassManager implementation
1162 /// Execute all of the passes scheduled for execution by invoking
1163 /// runOnModule method. Keep track of whether any of the passes modifies
1164 /// the module, and if so, return true.
1166 MPPassManager::runOnModule(Module &M) {
1167 bool Changed = false;
1169 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1170 ModulePass *MP = getContainedPass(Index);
1172 AnalysisUsage AnUsage;
1173 MP->getAnalysisUsage(AnUsage);
1175 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1176 dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1178 initializeAnalysisImpl(MP);
1180 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1181 Changed |= MP->runOnModule(M);
1182 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1185 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1186 M.getModuleIdentifier());
1187 dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1189 removeNotPreservedAnalysis(MP);
1190 recordAvailableAnalysis(MP);
1191 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1196 /// Add RequiredPass into list of lower level passes required by pass P.
1197 /// RequiredPass is run on the fly by Pass Manager when P requests it
1198 /// through getAnalysis interface.
1199 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1201 assert (P->getPotentialPassManagerType() == PMT_ModulePassManager
1202 && "Unable to handle Pass that requires lower level Analysis pass");
1203 assert ((P->getPotentialPassManagerType() <
1204 RequiredPass->getPotentialPassManagerType())
1205 && "Unable to handle Pass that requires lower level Analysis pass");
1207 FPPassManager *FPP = OnTheFlyManagers[P];
1209 FPP = new FPPassManager(getDepth() + 1);
1210 OnTheFlyManagers[P] = FPP;
1213 FPP->add(RequiredPass, false);
1216 /// Return function pass corresponding to PassInfo PI, that is
1217 /// required by module pass MP. Instantiate analysis pass, by using
1218 /// its runOnFunction() for function F.
1219 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI,
1221 AnalysisID AID = PI;
1222 FPPassManager *FPP =OnTheFlyManagers[MP];
1223 assert (FPP && "Unable to find on the fly pass");
1225 FPP->runOnFunction(F);
1226 return FPP->findAnalysisPass(AID, false);
1230 //===----------------------------------------------------------------------===//
1231 // PassManagerImpl implementation
1233 /// run - Execute all of the passes scheduled for execution. Keep track of
1234 /// whether any of the passes modifies the module, and if so, return true.
1235 bool PassManagerImpl::run(Module &M) {
1237 bool Changed = false;
1239 TimingInfo::createTheTimeInfo();
1244 initializeAllAnalysisInfo();
1245 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1246 MPPassManager *MP = getContainedManager(Index);
1247 Changed |= MP->runOnModule(M);
1252 //===----------------------------------------------------------------------===//
1253 // PassManager implementation
1255 /// Create new pass manager
1256 PassManager::PassManager() {
1257 PM = new PassManagerImpl(0);
1258 // PM is the top level manager
1259 PM->setTopLevelManager(PM);
1262 PassManager::~PassManager() {
1266 /// add - Add a pass to the queue of passes to run. This passes ownership of
1267 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1268 /// will be destroyed as well, so there is no need to delete the pass. This
1269 /// implies that all passes MUST be allocated with 'new'.
1271 PassManager::add(Pass *P) {
1275 /// run - Execute all of the passes scheduled for execution. Keep track of
1276 /// whether any of the passes modifies the module, and if so, return true.
1278 PassManager::run(Module &M) {
1282 //===----------------------------------------------------------------------===//
1283 // TimingInfo Class - This class is used to calculate information about the
1284 // amount of time each pass takes to execute. This only happens with
1285 // -time-passes is enabled on the command line.
1287 bool llvm::TimePassesIsEnabled = false;
1288 static cl::opt<bool,true>
1289 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1290 cl::desc("Time each pass, printing elapsed time for each on exit"));
1292 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1293 // a non null value (if the -time-passes option is enabled) or it leaves it
1294 // null. It may be called multiple times.
1295 void TimingInfo::createTheTimeInfo() {
1296 if (!TimePassesIsEnabled || TheTimeInfo) return;
1298 // Constructed the first time this is called, iff -time-passes is enabled.
1299 // This guarantees that the object will be constructed before static globals,
1300 // thus it will be destroyed before them.
1301 static ManagedStatic<TimingInfo> TTI;
1302 TheTimeInfo = &*TTI;
1305 /// If TimingInfo is enabled then start pass timer.
1306 void StartPassTimer(Pass *P) {
1308 TheTimeInfo->passStarted(P);
1311 /// If TimingInfo is enabled then stop pass timer.
1312 void StopPassTimer(Pass *P) {
1314 TheTimeInfo->passEnded(P);
1317 //===----------------------------------------------------------------------===//
1318 // PMStack implementation
1321 // Pop Pass Manager from the stack and clear its analysis info.
1322 void PMStack::pop() {
1324 PMDataManager *Top = this->top();
1325 Top->initializeAnalysisInfo();
1330 // Push PM on the stack and set its top level manager.
1331 void PMStack::push(Pass *P) {
1333 PMDataManager *Top = NULL;
1334 PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1335 assert (PM && "Unable to push. Pass Manager expected");
1337 if (this->empty()) {
1342 PMTopLevelManager *TPM = Top->getTopLevelManager();
1344 assert (TPM && "Unable to find top level manager");
1345 TPM->addIndirectPassManager(PM);
1346 PM->setTopLevelManager(TPM);
1349 AnalysisResolver *AR = new AnalysisResolver(*Top);
1355 // Dump content of the pass manager stack.
1356 void PMStack::dump() {
1357 for(std::deque<PMDataManager *>::iterator I = S.begin(),
1358 E = S.end(); I != E; ++I) {
1359 Pass *P = dynamic_cast<Pass *>(*I);
1360 printf ("%s ", P->getPassName());
1366 /// Find appropriate Module Pass Manager in the PM Stack and
1367 /// add self into that manager.
1368 void ModulePass::assignPassManager(PMStack &PMS,
1369 PassManagerType PreferredType) {
1371 // Find Module Pass Manager
1372 while(!PMS.empty()) {
1373 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1374 if (TopPMType == PreferredType)
1375 break; // We found desired pass manager
1376 else if (TopPMType > PMT_ModulePassManager)
1377 PMS.pop(); // Pop children pass managers
1382 PMS.top()->add(this);
1385 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1386 /// in the PM Stack and add self into that manager.
1387 void FunctionPass::assignPassManager(PMStack &PMS,
1388 PassManagerType PreferredType) {
1390 // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1391 while(!PMS.empty()) {
1392 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1397 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1399 // Create new Function Pass Manager
1401 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1402 PMDataManager *PMD = PMS.top();
1404 // [1] Create new Function Pass Manager
1405 FPP = new FPPassManager(PMD->getDepth() + 1);
1407 // [2] Set up new manager's top level manager
1408 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1409 TPM->addIndirectPassManager(FPP);
1411 // [3] Assign manager to manage this new manager. This may create
1412 // and push new managers into PMS
1413 Pass *P = dynamic_cast<Pass *>(FPP);
1415 // If Call Graph Pass Manager is active then use it to manage
1416 // this new Function Pass manager.
1417 if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1418 P->assignPassManager(PMS, PMT_CallGraphPassManager);
1420 P->assignPassManager(PMS);
1422 // [4] Push new manager into PMS
1426 // Assign FPP as the manager of this pass.
1430 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1431 /// in the PM Stack and add self into that manager.
1432 void BasicBlockPass::assignPassManager(PMStack &PMS,
1433 PassManagerType PreferredType) {
1435 BBPassManager *BBP = NULL;
1437 // Basic Pass Manager is a leaf pass manager. It does not handle
1438 // any other pass manager.
1440 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1443 // If leaf manager is not Basic Block Pass manager then create new
1444 // basic Block Pass manager.
1447 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1448 PMDataManager *PMD = PMS.top();
1450 // [1] Create new Basic Block Manager
1451 BBP = new BBPassManager(PMD->getDepth() + 1);
1453 // [2] Set up new manager's top level manager
1454 // Basic Block Pass Manager does not live by itself
1455 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1456 TPM->addIndirectPassManager(BBP);
1458 // [3] Assign manager to manage this new manager. This may create
1459 // and push new managers into PMS
1460 Pass *P = dynamic_cast<Pass *>(BBP);
1461 P->assignPassManager(PMS);
1463 // [4] Push new manager into PMS
1467 // Assign BBP as the manager of this pass.