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/PassManager.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 //===----------------------------------------------------------------------===//
28 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
30 // o Manage optimization pass execution order
31 // o Make required Analysis information available before pass P is run
32 // o Release memory occupied by dead passes
33 // o If Analysis information is dirtied by a pass then regenerate Analysis
34 // information before it is consumed by another pass.
36 // Pass Manager Infrastructure uses multiple pass managers. They are
37 // PassManager, FunctionPassManager, ModulePassManager, BasicBlockPassManager.
38 // This class hierarcy uses multiple inheritance but pass managers do not derive
39 // from another pass manager.
41 // PassManager and FunctionPassManager are two top-level pass manager that
42 // represents the external interface of this entire pass manager infrastucture.
44 // Important classes :
46 // [o] class PMTopLevelManager;
48 // Two top level managers, PassManager and FunctionPassManager, derive from
49 // PMTopLevelManager. PMTopLevelManager manages information used by top level
50 // managers such as last user info.
52 // [o] class PMDataManager;
54 // PMDataManager manages information, e.g. list of available analysis info,
55 // used by a pass manager to manage execution order of passes. It also provides
56 // a place to implement common pass manager APIs. All pass managers derive from
59 // [o] class BasicBlockPassManager : public FunctionPass, public PMDataManager;
61 // BasicBlockPassManager manages BasicBlockPasses.
63 // [o] class FunctionPassManager;
65 // This is a external interface used by JIT to manage FunctionPasses. This
66 // interface relies on FunctionPassManagerImpl to do all the tasks.
68 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
69 // public PMTopLevelManager;
71 // FunctionPassManagerImpl is a top level manager. It manages FunctionPasses
72 // and BasicBlockPassManagers.
74 // [o] class ModulePassManager : public Pass, public PMDataManager;
76 // ModulePassManager manages ModulePasses and FunctionPassManagerImpls.
78 // [o] class PassManager;
80 // This is a external interface used by various tools to manages passes. It
81 // relies on PassManagerImpl to do all the tasks.
83 // [o] class PassManagerImpl : public Pass, public PMDataManager,
84 // public PMDTopLevelManager
86 // PassManagerImpl is a top level pass manager responsible for managing
87 // ModulePassManagers.
88 //===----------------------------------------------------------------------===//
92 //===----------------------------------------------------------------------===//
93 // Pass debugging information. Often it is useful to find out what pass is
94 // running when a crash occurs in a utility. When this library is compiled with
95 // debugging on, a command line option (--debug-pass) is enabled that causes the
96 // pass name to be printed before it executes.
99 // Different debug levels that can be enabled...
100 enum PassDebugLevel {
101 None, Arguments, Structure, Executions, Details
104 static cl::opt<enum PassDebugLevel>
105 PassDebugging_New("debug-pass", cl::Hidden,
106 cl::desc("Print PassManager debugging information"),
108 clEnumVal(None , "disable debug output"),
109 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
110 clEnumVal(Structure , "print pass structure before run()"),
111 clEnumVal(Executions, "print pass name before it is executed"),
112 clEnumVal(Details , "print pass details when it is executed"),
114 } // End of llvm namespace
116 #ifndef USE_OLD_PASSMANAGER
121 //===----------------------------------------------------------------------===//
124 /// PMTopLevelManager manages LastUser info and collects common APIs used by
125 /// top level pass managers.
126 class PMTopLevelManager {
129 inline std::vector<Pass *>::iterator passManagersBegin() {
130 return PassManagers.begin();
133 inline std::vector<Pass *>::iterator passManagersEnd() {
134 return PassManagers.end();
137 /// Schedule pass P for execution. Make sure that passes required by
138 /// P are run before P is run. Update analysis info maintained by
139 /// the manager. Remove dead passes. This is a recursive function.
140 void schedulePass(Pass *P);
142 /// This is implemented by top level pass manager and used by
143 /// schedulePass() to add analysis info passes that are not available.
144 virtual void addTopLevelPass(Pass *P) = 0;
146 /// Set pass P as the last user of the given analysis passes.
147 void setLastUser(std::vector<Pass *> &AnalysisPasses, Pass *P);
149 /// Collect passes whose last user is P
150 void collectLastUses(std::vector<Pass *> &LastUses, Pass *P);
152 /// Find the pass that implements Analysis AID. Search immutable
153 /// passes and all pass managers. If desired pass is not found
154 /// then return NULL.
155 Pass *findAnalysisPass(AnalysisID AID);
157 inline void clearManagers() {
158 PassManagers.clear();
161 virtual ~PMTopLevelManager() {
162 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
163 E = PassManagers.end(); I != E; ++I)
166 for (std::vector<ImmutablePass *>::iterator
167 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
170 PassManagers.clear();
173 /// Add immutable pass and initialize it.
174 inline void addImmutablePass(ImmutablePass *P) {
176 ImmutablePasses.push_back(P);
179 inline std::vector<ImmutablePass *>& getImmutablePasses() {
180 return ImmutablePasses;
183 void addPassManager(Pass *Manager) {
184 PassManagers.push_back(Manager);
187 // Add Manager into the list of managers that are not directly
188 // maintained by this top level pass manager
189 inline void addIndirectPassManager(PMDataManager *Manager) {
190 IndirectPassManagers.push_back(Manager);
193 // Print passes managed by this top level manager.
195 void dumpArguments();
199 /// Collection of pass managers
200 std::vector<Pass *> PassManagers;
202 /// Collection of pass managers that are not directly maintained
203 /// by this pass manager
204 std::vector<PMDataManager *> IndirectPassManagers;
206 // Map to keep track of last user of the analysis pass.
207 // LastUser->second is the last user of Lastuser->first.
208 std::map<Pass *, Pass *> LastUser;
210 /// Immutable passes are managed by top level manager.
211 std::vector<ImmutablePass *> ImmutablePasses;
214 //===----------------------------------------------------------------------===//
217 /// PMDataManager provides the common place to manage the analysis data
218 /// used by pass managers.
219 class PMDataManager {
221 PMDataManager(int D) : TPM(NULL), Depth(D) {
222 initializeAnalysisInfo();
225 virtual ~PMDataManager() {
227 for (std::vector<Pass *>::iterator I = PassVector.begin(),
228 E = PassVector.end(); I != E; ++I)
234 /// Return true IFF pass P's required analysis set does not required new
236 bool manageablePass(Pass *P);
238 /// Augment AvailableAnalysis by adding analysis made available by pass P.
239 void recordAvailableAnalysis(Pass *P);
241 /// Remove Analysis that is not preserved by the pass
242 void removeNotPreservedAnalysis(Pass *P);
244 /// Remove dead passes
245 void removeDeadPasses(Pass *P, std::string &Msg);
247 /// Add pass P into the PassVector. Update
248 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
249 void addPassToManager(Pass *P, bool ProcessAnalysis = true);
251 /// Initialize available analysis information.
252 void initializeAnalysisInfo() {
253 ForcedLastUses.clear();
254 AvailableAnalysis.clear();
257 /// Populate RequiredPasses with the analysis pass that are required by
259 void collectRequiredAnalysisPasses(std::vector<Pass *> &RequiredPasses,
262 /// All Required analyses should be available to the pass as it runs! Here
263 /// we fill in the AnalysisImpls member of the pass so that it can
264 /// successfully use the getAnalysis() method to retrieve the
265 /// implementations it needs.
266 void initializeAnalysisImpl(Pass *P);
268 /// Find the pass that implements Analysis AID. If desired pass is not found
269 /// then return NULL.
270 Pass *findAnalysisPass(AnalysisID AID, bool Direction);
272 inline std::vector<Pass *>::iterator passVectorBegin() {
273 return PassVector.begin();
276 inline std::vector<Pass *>::iterator passVectorEnd() {
277 return PassVector.end();
280 // Access toplevel manager
281 PMTopLevelManager *getTopLevelManager() { return TPM; }
282 void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
284 unsigned getDepth() { return Depth; }
286 // Print list of passes that are last used by P.
287 void dumpLastUses(Pass *P, unsigned Offset) {
289 std::vector<Pass *> LUses;
291 assert (TPM && "Top Level Manager is missing");
292 TPM->collectLastUses(LUses, P);
294 for (std::vector<Pass *>::iterator I = LUses.begin(),
295 E = LUses.end(); I != E; ++I) {
296 llvm::cerr << "--" << std::string(Offset*2, ' ');
297 (*I)->dumpPassStructure(0);
301 void dumpPassArguments() {
302 for(std::vector<Pass *>::iterator I = PassVector.begin(),
303 E = PassVector.end(); I != E; ++I) {
304 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
305 PMD->dumpPassArguments();
307 if (const PassInfo *PI = (*I)->getPassInfo())
308 if (!PI->isAnalysisGroup())
309 cerr << " -" << PI->getPassArgument();
313 void dumpPassInfo(Pass *P, std::string &Msg1, std::string &Msg2) {
314 if (PassDebugging_New < Executions)
316 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
318 cerr << P->getPassName();
322 void dumpAnalysisSetInfo(const char *Msg, Pass *P,
323 const std::vector<AnalysisID> &Set) {
324 if (PassDebugging_New >= Details && !Set.empty()) {
325 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
326 for (unsigned i = 0; i != Set.size(); ++i) {
328 cerr << " " << Set[i]->getPassName();
335 // Collection of pass whose last user asked this manager to claim
336 // last use. If a FunctionPass F is the last user of ModulePass info M
337 // then the F's manager, not F, records itself as a last user of M.
338 std::vector<Pass *> ForcedLastUses;
340 // Top level manager.
341 PMTopLevelManager *TPM;
344 // Set of available Analysis. This information is used while scheduling
345 // pass. If a pass requires an analysis which is not not available then
346 // equired analysis pass is scheduled to run before the pass itself is
348 std::map<AnalysisID, Pass*> AvailableAnalysis;
350 // Collection of pass that are managed by this manager
351 std::vector<Pass *> PassVector;
356 //===----------------------------------------------------------------------===//
357 // BasicBlockPassManager
359 /// BasicBlockPassManager manages BasicBlockPass. It batches all the
360 /// pass together and sequence them to process one basic block before
361 /// processing next basic block.
362 class BasicBlockPassManager : public PMDataManager,
363 public FunctionPass {
366 BasicBlockPassManager(int D) : PMDataManager(D) { }
368 /// Add a pass into a passmanager queue.
369 bool addPass(Pass *p);
371 /// Execute all of the passes scheduled for execution. Keep track of
372 /// whether any of the passes modifies the function, and if so, return true.
373 bool runOnFunction(Function &F);
375 /// Pass Manager itself does not invalidate any analysis info.
376 void getAnalysisUsage(AnalysisUsage &Info) const {
377 Info.setPreservesAll();
380 bool doInitialization(Module &M);
381 bool doInitialization(Function &F);
382 bool doFinalization(Module &M);
383 bool doFinalization(Function &F);
385 // Print passes managed by this manager
386 void dumpPassStructure(unsigned Offset) {
387 llvm::cerr << std::string(Offset*2, ' ') << "BasicBLockPass Manager\n";
388 for (std::vector<Pass *>::iterator I = passVectorBegin(),
389 E = passVectorEnd(); I != E; ++I) {
390 (*I)->dumpPassStructure(Offset + 1);
391 dumpLastUses(*I, Offset+1);
396 //===----------------------------------------------------------------------===//
397 // FunctionPassManagerImpl_New
399 /// FunctionPassManagerImpl_New manages FunctionPasses and
400 /// BasicBlockPassManagers. It batches all function passes and basic block pass
401 /// managers together and sequence them to process one function at a time before
402 /// processing next function.
403 class FunctionPassManagerImpl_New : public ModulePass,
404 public PMDataManager,
405 public PMTopLevelManager {
407 FunctionPassManagerImpl_New(int D) : PMDataManager(D) {
408 activeBBPassManager = NULL;
410 ~FunctionPassManagerImpl_New() { /* TODO */ };
412 inline void addTopLevelPass(Pass *P) {
414 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
416 // P is a immutable pass then it will be managed by this
417 // top level manager. Set up analysis resolver to connect them.
418 AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
420 initializeAnalysisImpl(P);
421 addImmutablePass(IP);
422 recordAvailableAnalysis(IP);
428 /// add - Add a pass to the queue of passes to run. This passes
429 /// ownership of the Pass to the PassManager. When the
430 /// PassManager_X is destroyed, the pass will be destroyed as well, so
431 /// there is no need to delete the pass. (TODO delete passes.)
432 /// This implies that all passes MUST be allocated with 'new'.
437 /// Add pass into the pass manager queue.
438 bool addPass(Pass *P);
440 /// Execute all of the passes scheduled for execution. Keep
441 /// track of whether any of the passes modifies the function, and if
443 bool runOnModule(Module &M);
444 bool runOnFunction(Function &F);
445 bool run(Function &F);
447 /// doInitialization - Run all of the initializers for the function passes.
449 bool doInitialization(Module &M);
451 /// doFinalization - Run all of the initializers for the function passes.
453 bool doFinalization(Module &M);
455 /// Pass Manager itself does not invalidate any analysis info.
456 void getAnalysisUsage(AnalysisUsage &Info) const {
457 Info.setPreservesAll();
460 // Print passes managed by this manager
461 void dumpPassStructure(unsigned Offset) {
462 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
463 for (std::vector<Pass *>::iterator I = passVectorBegin(),
464 E = passVectorEnd(); I != E; ++I) {
465 (*I)->dumpPassStructure(Offset + 1);
466 dumpLastUses(*I, Offset+1);
471 // Active Pass Managers
472 BasicBlockPassManager *activeBBPassManager;
475 //===----------------------------------------------------------------------===//
478 /// ModulePassManager manages ModulePasses and function pass managers.
479 /// It batches all Module passes passes and function pass managers together and
480 /// sequence them to process one module.
481 class ModulePassManager : public Pass, public PMDataManager {
484 ModulePassManager(int D) : PMDataManager(D) {
485 activeFunctionPassManager = NULL;
488 /// Add a pass into a passmanager queue.
489 bool addPass(Pass *p);
491 /// run - Execute all of the passes scheduled for execution. Keep track of
492 /// whether any of the passes modifies the module, and if so, return true.
493 bool runOnModule(Module &M);
495 /// Pass Manager itself does not invalidate any analysis info.
496 void getAnalysisUsage(AnalysisUsage &Info) const {
497 Info.setPreservesAll();
500 // Print passes managed by this manager
501 void dumpPassStructure(unsigned Offset) {
502 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
503 for (std::vector<Pass *>::iterator I = passVectorBegin(),
504 E = passVectorEnd(); I != E; ++I) {
505 (*I)->dumpPassStructure(Offset + 1);
506 dumpLastUses(*I, Offset+1);
511 // Active Pass Manager
512 FunctionPassManagerImpl_New *activeFunctionPassManager;
515 //===----------------------------------------------------------------------===//
516 // PassManagerImpl_New
518 /// PassManagerImpl_New manages ModulePassManagers
519 class PassManagerImpl_New : public Pass,
520 public PMDataManager,
521 public PMTopLevelManager {
525 PassManagerImpl_New(int D) : PMDataManager(D) {
526 activeManager = NULL;
529 /// add - Add a pass to the queue of passes to run. This passes ownership of
530 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
531 /// will be destroyed as well, so there is no need to delete the pass. This
532 /// implies that all passes MUST be allocated with 'new'.
537 /// run - Execute all of the passes scheduled for execution. Keep track of
538 /// whether any of the passes modifies the module, and if so, return true.
541 /// Pass Manager itself does not invalidate any analysis info.
542 void getAnalysisUsage(AnalysisUsage &Info) const {
543 Info.setPreservesAll();
546 inline void addTopLevelPass(Pass *P) {
548 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
550 // P is a immutable pass and it will be managed by this
551 // top level manager. Set up analysis resolver to connect them.
552 AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
554 initializeAnalysisImpl(P);
555 addImmutablePass(IP);
556 recordAvailableAnalysis(IP);
564 /// Add a pass into a passmanager queue.
565 bool addPass(Pass *p);
567 // Active Pass Manager
568 ModulePassManager *activeManager;
571 //===----------------------------------------------------------------------===//
572 // TimingInfo Class - This class is used to calculate information about the
573 // amount of time each pass takes to execute. This only happens when
574 // -time-passes is enabled on the command line.
578 std::map<Pass*, Timer> TimingData;
582 // Use 'create' member to get this.
583 TimingInfo() : TG("... Pass execution timing report ...") {}
585 // TimingDtor - Print out information about timing information
587 // Delete all of the timers...
589 // TimerGroup is deleted next, printing the report.
592 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
593 // to a non null value (if the -time-passes option is enabled) or it leaves it
594 // null. It may be called multiple times.
595 static void createTheTimeInfo();
597 void passStarted(Pass *P) {
599 if (dynamic_cast<PMDataManager *>(P))
602 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
603 if (I == TimingData.end())
604 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
605 I->second.startTimer();
607 void passEnded(Pass *P) {
609 if (dynamic_cast<PMDataManager *>(P))
612 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
613 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
614 I->second.stopTimer();
618 static TimingInfo *TheTimeInfo;
620 } // End of llvm namespace
622 //===----------------------------------------------------------------------===//
623 // PMTopLevelManager implementation
625 /// Set pass P as the last user of the given analysis passes.
626 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
629 for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
630 E = AnalysisPasses.end(); I != E; ++I) {
633 // If AP is the last user of other passes then make P last user of
635 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
636 LUE = LastUser.end(); LUI != LUE; ++LUI) {
637 if (LUI->second == AP)
638 LastUser[LUI->first] = P;
643 /// Collect passes whose last user is P
644 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
646 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
647 LUE = LastUser.end(); LUI != LUE; ++LUI)
648 if (LUI->second == P)
649 LastUses.push_back(LUI->first);
652 /// Schedule pass P for execution. Make sure that passes required by
653 /// P are run before P is run. Update analysis info maintained by
654 /// the manager. Remove dead passes. This is a recursive function.
655 void PMTopLevelManager::schedulePass(Pass *P) {
657 // TODO : Allocate function manager for this pass, other wise required set
658 // may be inserted into previous function manager
660 AnalysisUsage AnUsage;
661 P->getAnalysisUsage(AnUsage);
662 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
663 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
664 E = RequiredSet.end(); I != E; ++I) {
666 Pass *AnalysisPass = findAnalysisPass(*I);
668 // Schedule this analysis run first.
669 AnalysisPass = (*I)->createPass();
670 schedulePass(AnalysisPass);
674 // Now all required passes are available.
678 /// Find the pass that implements Analysis AID. Search immutable
679 /// passes and all pass managers. If desired pass is not found
680 /// then return NULL.
681 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
684 // Check pass managers
685 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
686 E = PassManagers.end(); P == NULL && I != E; ++I) {
687 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
688 assert(PMD && "This is not a PassManager");
689 P = PMD->findAnalysisPass(AID, false);
692 // Check other pass managers
693 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
694 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
695 P = (*I)->findAnalysisPass(AID, false);
697 for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
698 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
699 const PassInfo *PI = (*I)->getPassInfo();
703 // If Pass not found then check the interfaces implemented by Immutable Pass
705 const std::vector<const PassInfo*> &ImmPI =
706 PI->getInterfacesImplemented();
707 for (unsigned Index = 0, End = ImmPI.size();
708 P == NULL && Index != End; ++Index)
709 if (ImmPI[Index] == AID)
717 // Print passes managed by this top level manager.
718 void PMTopLevelManager::dumpPasses() {
720 // Print out the immutable passes
721 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
722 ImmutablePasses[i]->dumpPassStructure(0);
725 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
726 E = PassManagers.end(); I != E; ++I)
727 (*I)->dumpPassStructure(1);
731 void PMTopLevelManager::dumpArguments() {
733 if (PassDebugging_New < Arguments)
736 cerr << "Pass Arguments: ";
737 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
738 E = PassManagers.end(); I != E; ++I) {
739 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
740 assert(PMD && "This is not a PassManager");
741 PMD->dumpPassArguments();
746 //===----------------------------------------------------------------------===//
747 // PMDataManager implementation
749 /// Return true IFF pass P's required analysis set does not required new
751 bool PMDataManager::manageablePass(Pass *P) {
754 // If this pass is not preserving information that is required by a
755 // pass maintained by higher level pass manager then do not insert
756 // this pass into current manager. Use new manager. For example,
757 // For example, If FunctionPass F is not preserving ModulePass Info M1
758 // that is used by another ModulePass M2 then do not insert F in
759 // current function pass manager.
763 /// Augement AvailableAnalysis by adding analysis made available by pass P.
764 void PMDataManager::recordAvailableAnalysis(Pass *P) {
766 if (const PassInfo *PI = P->getPassInfo()) {
767 AvailableAnalysis[PI] = P;
769 //This pass is the current implementation of all of the interfaces it
770 //implements as well.
771 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
772 for (unsigned i = 0, e = II.size(); i != e; ++i)
773 AvailableAnalysis[II[i]] = P;
777 /// Remove Analyss not preserved by Pass P
778 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
779 AnalysisUsage AnUsage;
780 P->getAnalysisUsage(AnUsage);
782 if (AnUsage.getPreservesAll())
785 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
786 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
787 E = AvailableAnalysis.end(); I != E; ) {
788 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) ==
789 PreservedSet.end()) {
790 // Remove this analysis
791 if (!dynamic_cast<ImmutablePass*>(I->second)) {
792 std::map<AnalysisID, Pass*>::iterator J = I++;
793 AvailableAnalysis.erase(J);
801 /// Remove analysis passes that are not used any longer
802 void PMDataManager::removeDeadPasses(Pass *P, std::string &Msg) {
804 std::vector<Pass *> DeadPasses;
805 TPM->collectLastUses(DeadPasses, P);
807 for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
808 E = DeadPasses.end(); I != E; ++I) {
810 std::string Msg1 = " Freeing Pass '";
811 dumpPassInfo(*I, Msg1, Msg);
813 if (TheTimeInfo) TheTimeInfo->passStarted(P);
814 (*I)->releaseMemory();
815 if (TheTimeInfo) TheTimeInfo->passEnded(P);
817 std::map<AnalysisID, Pass*>::iterator Pos =
818 AvailableAnalysis.find((*I)->getPassInfo());
820 // It is possible that pass is already removed from the AvailableAnalysis
821 if (Pos != AvailableAnalysis.end())
822 AvailableAnalysis.erase(Pos);
826 /// Add pass P into the PassVector. Update
827 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
828 void PMDataManager::addPassToManager(Pass *P,
829 bool ProcessAnalysis) {
831 // This manager is going to manage pass P. Set up analysis resolver
833 AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
836 if (ProcessAnalysis) {
838 // At the moment, this pass is the last user of all required passes.
839 std::vector<Pass *> LastUses;
840 std::vector<Pass *> RequiredPasses;
841 unsigned PDepth = this->getDepth();
843 collectRequiredAnalysisPasses(RequiredPasses, P);
844 for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
845 E = RequiredPasses.end(); I != E; ++I) {
846 Pass *PRequired = *I;
849 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
850 RDepth = DM.getDepth();
852 if (PDepth == RDepth)
853 LastUses.push_back(PRequired);
854 else if (PDepth > RDepth) {
855 // Let the parent claim responsibility of last use
856 ForcedLastUses.push_back(PRequired);
858 // Note : This feature is not yet implemented
860 "Unable to handle Pass that requires lower level Analysis pass");
864 if (!LastUses.empty())
865 TPM->setLastUser(LastUses, P);
867 // Take a note of analysis required and made available by this pass.
868 // Remove the analysis not preserved by this pass
869 removeNotPreservedAnalysis(P);
870 recordAvailableAnalysis(P);
874 PassVector.push_back(P);
877 /// Populate RequiredPasses with the analysis pass that are required by
879 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
881 AnalysisUsage AnUsage;
882 P->getAnalysisUsage(AnUsage);
883 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
884 for (std::vector<AnalysisID>::const_iterator
885 I = RequiredSet.begin(), E = RequiredSet.end();
887 Pass *AnalysisPass = findAnalysisPass(*I, true);
888 assert (AnalysisPass && "Analysis pass is not available");
889 RP.push_back(AnalysisPass);
892 const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
893 for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
894 E = IDs.end(); I != E; ++I) {
895 Pass *AnalysisPass = findAnalysisPass(*I, true);
896 assert (AnalysisPass && "Analysis pass is not available");
897 RP.push_back(AnalysisPass);
901 // All Required analyses should be available to the pass as it runs! Here
902 // we fill in the AnalysisImpls member of the pass so that it can
903 // successfully use the getAnalysis() method to retrieve the
904 // implementations it needs.
906 void PMDataManager::initializeAnalysisImpl(Pass *P) {
907 AnalysisUsage AnUsage;
908 P->getAnalysisUsage(AnUsage);
910 for (std::vector<const PassInfo *>::const_iterator
911 I = AnUsage.getRequiredSet().begin(),
912 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
913 Pass *Impl = findAnalysisPass(*I, true);
915 assert(0 && "Analysis used but not available!");
916 AnalysisResolver_New *AR = P->getResolver();
917 AR->addAnalysisImplsPair(*I, Impl);
921 /// Find the pass that implements Analysis AID. If desired pass is not found
922 /// then return NULL.
923 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
925 // Check if AvailableAnalysis map has one entry.
926 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
928 if (I != AvailableAnalysis.end())
931 // Search Parents through TopLevelManager
933 return TPM->findAnalysisPass(AID);
939 //===----------------------------------------------------------------------===//
940 // NOTE: Is this the right place to define this method ?
941 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
942 Pass *AnalysisResolver_New::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
943 return PM.findAnalysisPass(ID, dir);
946 //===----------------------------------------------------------------------===//
947 // BasicBlockPassManager implementation
949 /// Add pass P into PassVector and return true. If this pass is not
950 /// manageable by this manager then return false.
952 BasicBlockPassManager::addPass(Pass *P) {
954 BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
958 // If this pass does not preserve anlysis that is used by other passes
959 // managed by this manager than it is not a suiable pass for this manager.
960 if (!manageablePass(P))
963 addPassToManager(BP);
968 /// Execute all of the passes scheduled for execution by invoking
969 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
970 /// the function, and if so, return true.
972 BasicBlockPassManager::runOnFunction(Function &F) {
977 bool Changed = doInitialization(F);
978 initializeAnalysisInfo();
980 std::string Msg1 = "Executing Pass '";
981 std::string Msg3 = "' Made Modification '";
983 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
984 for (std::vector<Pass *>::iterator itr = passVectorBegin(),
985 e = passVectorEnd(); itr != e; ++itr) {
987 AnalysisUsage AnUsage;
988 P->getAnalysisUsage(AnUsage);
990 std::string Msg2 = "' on BasicBlock '" + (*I).getName() + "'...\n";
991 dumpPassInfo(P, Msg1, Msg2);
992 dumpAnalysisSetInfo("Required", P, AnUsage.getRequiredSet());
994 initializeAnalysisImpl(P);
996 BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
997 if (TheTimeInfo) TheTimeInfo->passStarted(P);
998 Changed |= BP->runOnBasicBlock(*I);
999 if (TheTimeInfo) TheTimeInfo->passEnded(P);
1002 dumpPassInfo(P, Msg3, Msg2);
1003 dumpAnalysisSetInfo("Preserved", P, AnUsage.getPreservedSet());
1005 removeNotPreservedAnalysis(P);
1006 recordAvailableAnalysis(P);
1007 removeDeadPasses(P, Msg2);
1009 return Changed | doFinalization(F);
1012 // Implement doInitialization and doFinalization
1013 inline bool BasicBlockPassManager::doInitialization(Module &M) {
1014 bool Changed = false;
1016 for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1017 e = passVectorEnd(); itr != e; ++itr) {
1019 BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
1020 Changed |= BP->doInitialization(M);
1026 inline bool BasicBlockPassManager::doFinalization(Module &M) {
1027 bool Changed = false;
1029 for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1030 e = passVectorEnd(); itr != e; ++itr) {
1032 BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
1033 Changed |= BP->doFinalization(M);
1039 inline bool BasicBlockPassManager::doInitialization(Function &F) {
1040 bool Changed = false;
1042 for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1043 e = passVectorEnd(); itr != e; ++itr) {
1045 BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
1046 Changed |= BP->doInitialization(F);
1052 inline bool BasicBlockPassManager::doFinalization(Function &F) {
1053 bool Changed = false;
1055 for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1056 e = passVectorEnd(); itr != e; ++itr) {
1058 BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
1059 Changed |= BP->doFinalization(F);
1066 //===----------------------------------------------------------------------===//
1067 // FunctionPassManager implementation
1069 /// Create new Function pass manager
1070 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1071 FPM = new FunctionPassManagerImpl_New(0);
1072 // FPM is the top level manager.
1073 FPM->setTopLevelManager(FPM);
1075 PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
1076 AnalysisResolver_New *AR = new AnalysisResolver_New(*PMD);
1077 FPM->setResolver(AR);
1079 FPM->addPassManager(FPM);
1083 FunctionPassManager::~FunctionPassManager() {
1084 // Note : FPM maintains one entry in PassManagers vector.
1085 // This one entry is FPM itself. This is not ideal. One
1086 // alternative is have one additional layer between
1087 // FunctionPassManager and FunctionPassManagerImpl.
1088 // Meanwhile, to avoid going into infinte loop, first
1089 // remove FPM from its PassMangers vector.
1090 FPM->clearManagers();
1094 /// add - Add a pass to the queue of passes to run. This passes
1095 /// ownership of the Pass to the PassManager. When the
1096 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1097 /// there is no need to delete the pass. (TODO delete passes.)
1098 /// This implies that all passes MUST be allocated with 'new'.
1099 void FunctionPassManager::add(Pass *P) {
1103 /// run - Execute all of the passes scheduled for execution. Keep
1104 /// track of whether any of the passes modifies the function, and if
1105 /// so, return true.
1107 bool FunctionPassManager::run(Function &F) {
1109 if (MP->materializeFunction(&F, &errstr)) {
1110 cerr << "Error reading bytecode file: " << errstr << "\n";
1117 /// doInitialization - Run all of the initializers for the function passes.
1119 bool FunctionPassManager::doInitialization() {
1120 return FPM->doInitialization(*MP->getModule());
1123 /// doFinalization - Run all of the initializers for the function passes.
1125 bool FunctionPassManager::doFinalization() {
1126 return FPM->doFinalization(*MP->getModule());
1129 //===----------------------------------------------------------------------===//
1130 // FunctionPassManagerImpl_New implementation
1132 /// Add pass P into the pass manager queue. If P is a BasicBlockPass then
1133 /// either use it into active basic block pass manager or create new basic
1134 /// block pass manager to handle pass P.
1136 FunctionPassManagerImpl_New::addPass(Pass *P) {
1138 // If P is a BasicBlockPass then use BasicBlockPassManager.
1139 if (BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P)) {
1141 if (!activeBBPassManager || !activeBBPassManager->addPass(BP)) {
1143 // If active manager exists then clear its analysis info.
1144 if (activeBBPassManager)
1145 activeBBPassManager->initializeAnalysisInfo();
1147 // Create and add new manager
1148 activeBBPassManager =
1149 new BasicBlockPassManager(getDepth() + 1);
1150 // Inherit top level manager
1151 activeBBPassManager->setTopLevelManager(this->getTopLevelManager());
1153 // Add new manager into current manager's list.
1154 addPassToManager(activeBBPassManager, false);
1156 // Add new manager into top level manager's indirect passes list
1157 PMDataManager *PMD = dynamic_cast<PMDataManager *>(activeBBPassManager);
1158 assert (PMD && "Manager is not Pass Manager");
1159 TPM->addIndirectPassManager(PMD);
1161 // Add pass into new manager. This time it must succeed.
1162 if (!activeBBPassManager->addPass(BP))
1163 assert(0 && "Unable to add Pass");
1166 if (!ForcedLastUses.empty())
1167 TPM->setLastUser(ForcedLastUses, this);
1172 FunctionPass *FP = dynamic_cast<FunctionPass *>(P);
1176 // If this pass does not preserve anlysis that is used by other passes
1177 // managed by this manager than it is not a suiable pass for this manager.
1178 if (!manageablePass(P))
1181 addPassToManager (FP);
1183 // If active manager exists then clear its analysis info.
1184 if (activeBBPassManager) {
1185 activeBBPassManager->initializeAnalysisInfo();
1186 activeBBPassManager = NULL;
1192 /// Execute all of the passes scheduled for execution by invoking
1193 /// runOnFunction method. Keep track of whether any of the passes modifies
1194 /// the function, and if so, return true.
1195 bool FunctionPassManagerImpl_New::runOnModule(Module &M) {
1197 bool Changed = doInitialization(M);
1198 initializeAnalysisInfo();
1200 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1201 this->runOnFunction(*I);
1203 return Changed | doFinalization(M);
1206 /// Execute all of the passes scheduled for execution by invoking
1207 /// runOnFunction method. Keep track of whether any of the passes modifies
1208 /// the function, and if so, return true.
1209 bool FunctionPassManagerImpl_New::runOnFunction(Function &F) {
1211 bool Changed = false;
1216 initializeAnalysisInfo();
1218 std::string Msg1 = "Executing Pass '";
1219 std::string Msg3 = "' Made Modification '";
1221 for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1222 e = passVectorEnd(); itr != e; ++itr) {
1224 AnalysisUsage AnUsage;
1225 P->getAnalysisUsage(AnUsage);
1227 std::string Msg2 = "' on Function '" + F.getName() + "'...\n";
1228 dumpPassInfo(P, Msg1, Msg2);
1229 dumpAnalysisSetInfo("Required", P, AnUsage.getRequiredSet());
1231 initializeAnalysisImpl(P);
1232 FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
1234 if (TheTimeInfo) TheTimeInfo->passStarted(P);
1235 Changed |= FP->runOnFunction(F);
1236 if (TheTimeInfo) TheTimeInfo->passEnded(P);
1239 dumpPassInfo(P, Msg3, Msg2);
1240 dumpAnalysisSetInfo("Preserved", P, AnUsage.getPreservedSet());
1242 removeNotPreservedAnalysis(P);
1243 recordAvailableAnalysis(P);
1244 removeDeadPasses(P, Msg2);
1250 inline bool FunctionPassManagerImpl_New::doInitialization(Module &M) {
1251 bool Changed = false;
1253 for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1254 e = passVectorEnd(); itr != e; ++itr) {
1257 FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
1258 Changed |= FP->doInitialization(M);
1264 inline bool FunctionPassManagerImpl_New::doFinalization(Module &M) {
1265 bool Changed = false;
1267 for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1268 e = passVectorEnd(); itr != e; ++itr) {
1271 FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
1272 Changed |= FP->doFinalization(M);
1278 // Execute all the passes managed by this top level manager.
1279 // Return true if any function is modified by a pass.
1280 bool FunctionPassManagerImpl_New::run(Function &F) {
1282 bool Changed = false;
1283 for (std::vector<Pass *>::iterator I = passManagersBegin(),
1284 E = passManagersEnd(); I != E; ++I) {
1285 FunctionPassManagerImpl_New *FP =
1286 dynamic_cast<FunctionPassManagerImpl_New *>(*I);
1287 Changed |= FP->runOnFunction(F);
1292 //===----------------------------------------------------------------------===//
1293 // ModulePassManager implementation
1295 /// Add P into pass vector if it is manageble. If P is a FunctionPass
1296 /// then use FunctionPassManagerImpl_New to manage it. Return false if P
1297 /// is not manageable by this manager.
1299 ModulePassManager::addPass(Pass *P) {
1301 // If P is FunctionPass then use function pass maanager.
1302 if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P)) {
1304 if (!activeFunctionPassManager || !activeFunctionPassManager->addPass(P)) {
1306 // If active manager exists then clear its analysis info.
1307 if (activeFunctionPassManager)
1308 activeFunctionPassManager->initializeAnalysisInfo();
1310 // Create and add new manager
1311 activeFunctionPassManager =
1312 new FunctionPassManagerImpl_New(getDepth() + 1);
1314 // Add new manager into current manager's list
1315 addPassToManager(activeFunctionPassManager, false);
1317 // Inherit top level manager
1318 activeFunctionPassManager->setTopLevelManager(this->getTopLevelManager());
1320 // Add new manager into top level manager's indirect passes list
1321 PMDataManager *PMD =
1322 dynamic_cast<PMDataManager *>(activeFunctionPassManager);
1323 assert(PMD && "Manager is not Pass Manager");
1324 TPM->addIndirectPassManager(PMD);
1326 // Add pass into new manager. This time it must succeed.
1327 if (!activeFunctionPassManager->addPass(FP))
1328 assert(0 && "Unable to add pass");
1331 if (!ForcedLastUses.empty())
1332 TPM->setLastUser(ForcedLastUses, this);
1337 ModulePass *MP = dynamic_cast<ModulePass *>(P);
1341 // If this pass does not preserve anlysis that is used by other passes
1342 // managed by this manager than it is not a suiable pass for this manager.
1343 if (!manageablePass(P))
1346 addPassToManager(MP);
1347 // If active manager exists then clear its analysis info.
1348 if (activeFunctionPassManager) {
1349 activeFunctionPassManager->initializeAnalysisInfo();
1350 activeFunctionPassManager = NULL;
1357 /// Execute all of the passes scheduled for execution by invoking
1358 /// runOnModule method. Keep track of whether any of the passes modifies
1359 /// the module, and if so, return true.
1361 ModulePassManager::runOnModule(Module &M) {
1362 bool Changed = false;
1363 initializeAnalysisInfo();
1365 std::string Msg1 = "Executing Pass '";
1366 std::string Msg3 = "' Made Modification '";
1368 for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1369 e = passVectorEnd(); itr != e; ++itr) {
1371 AnalysisUsage AnUsage;
1372 P->getAnalysisUsage(AnUsage);
1374 std::string Msg2 = "' on Module '" + M.getModuleIdentifier() + "'...\n";
1375 dumpPassInfo(P, Msg1, Msg2);
1376 dumpAnalysisSetInfo("Required", P, AnUsage.getRequiredSet());
1378 initializeAnalysisImpl(P);
1379 ModulePass *MP = dynamic_cast<ModulePass*>(P);
1381 if (TheTimeInfo) TheTimeInfo->passStarted(P);
1382 Changed |= MP->runOnModule(M);
1383 if (TheTimeInfo) TheTimeInfo->passEnded(P);
1386 dumpPassInfo(P, Msg3, Msg2);
1387 dumpAnalysisSetInfo("Preserved", P, AnUsage.getPreservedSet());
1389 removeNotPreservedAnalysis(P);
1390 recordAvailableAnalysis(P);
1391 removeDeadPasses(P, Msg2);
1396 //===----------------------------------------------------------------------===//
1397 // PassManagerImpl implementation
1399 /// Add P into active pass manager or use new module pass manager to
1401 bool PassManagerImpl_New::addPass(Pass *P) {
1403 if (!activeManager || !activeManager->addPass(P)) {
1404 activeManager = new ModulePassManager(getDepth() + 1);
1405 // Inherit top level manager
1406 activeManager->setTopLevelManager(this->getTopLevelManager());
1408 // This top level manager is going to manage activeManager.
1409 // Set up analysis resolver to connect them.
1410 AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
1411 activeManager->setResolver(AR);
1413 addPassManager(activeManager);
1414 return activeManager->addPass(P);
1419 /// run - Execute all of the passes scheduled for execution. Keep track of
1420 /// whether any of the passes modifies the module, and if so, return true.
1421 bool PassManagerImpl_New::run(Module &M) {
1423 bool Changed = false;
1425 TimingInfo::createTheTimeInfo();
1428 if (PassDebugging_New >= Structure)
1431 for (std::vector<Pass *>::iterator I = passManagersBegin(),
1432 E = passManagersEnd(); I != E; ++I) {
1433 ModulePassManager *MP = dynamic_cast<ModulePassManager *>(*I);
1434 Changed |= MP->runOnModule(M);
1439 //===----------------------------------------------------------------------===//
1440 // PassManager implementation
1442 /// Create new pass manager
1443 PassManager::PassManager() {
1444 PM = new PassManagerImpl_New(0);
1445 // PM is the top level manager
1446 PM->setTopLevelManager(PM);
1449 PassManager::~PassManager() {
1453 /// add - Add a pass to the queue of passes to run. This passes ownership of
1454 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1455 /// will be destroyed as well, so there is no need to delete the pass. This
1456 /// implies that all passes MUST be allocated with 'new'.
1458 PassManager::add(Pass *P) {
1462 /// run - Execute all of the passes scheduled for execution. Keep track of
1463 /// whether any of the passes modifies the module, and if so, return true.
1465 PassManager::run(Module &M) {
1469 //===----------------------------------------------------------------------===//
1470 // TimingInfo Class - This class is used to calculate information about the
1471 // amount of time each pass takes to execute. This only happens with
1472 // -time-passes is enabled on the command line.
1474 bool llvm::TimePassesIsEnabled = false;
1475 static cl::opt<bool,true>
1476 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1477 cl::desc("Time each pass, printing elapsed time for each on exit"));
1479 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1480 // a non null value (if the -time-passes option is enabled) or it leaves it
1481 // null. It may be called multiple times.
1482 void TimingInfo::createTheTimeInfo() {
1483 if (!TimePassesIsEnabled || TheTimeInfo) return;
1485 // Constructed the first time this is called, iff -time-passes is enabled.
1486 // This guarantees that the object will be constructed before static globals,
1487 // thus it will be destroyed before them.
1488 static ManagedStatic<TimingInfo> TTI;
1489 TheTimeInfo = &*TTI;