1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Assembly/Writer.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Timer.h"
20 #include "llvm/Module.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/System/Threading.h"
26 #include "llvm-c/Core.h"
32 // See PassManagers.h for Pass Manager infrastructure overview.
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information. Often it is useful to find out what pass is
38 // running when a crash occurs in a utility. When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
43 // Different debug levels that can be enabled...
45 None, Arguments, Structure, Executions, Details
48 static cl::opt<enum PassDebugLevel>
49 PassDebugging("debug-pass", cl::Hidden,
50 cl::desc("Print PassManager debugging information"),
52 clEnumVal(None , "disable debug output"),
53 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54 clEnumVal(Structure , "print pass structure before run()"),
55 clEnumVal(Executions, "print pass name before it is executed"),
56 clEnumVal(Details , "print pass details when it is executed"),
58 } // End of llvm namespace
60 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
61 /// or higher is specified.
62 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
63 return PassDebugging >= Executions;
69 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
71 OS << "Releasing pass '";
73 OS << "Running pass '";
75 OS << P->getPassName() << "'";
78 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
89 else if (isa<BasicBlock>(V))
95 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
102 //===----------------------------------------------------------------------===//
105 /// BBPassManager manages BasicBlockPass. It batches all the
106 /// pass together and sequence them to process one basic block before
107 /// processing next basic block.
108 class BBPassManager : public PMDataManager, public FunctionPass {
112 explicit BBPassManager(int Depth)
113 : PMDataManager(Depth), FunctionPass(&ID) {}
115 /// Execute all of the passes scheduled for execution. Keep track of
116 /// whether any of the passes modifies the function, and if so, return true.
117 bool runOnFunction(Function &F);
119 /// Pass Manager itself does not invalidate any analysis info.
120 void getAnalysisUsage(AnalysisUsage &Info) const {
121 Info.setPreservesAll();
124 bool doInitialization(Module &M);
125 bool doInitialization(Function &F);
126 bool doFinalization(Module &M);
127 bool doFinalization(Function &F);
129 virtual PMDataManager *getAsPMDataManager() { return this; }
130 virtual Pass *getAsPass() { return this; }
132 virtual const char *getPassName() const {
133 return "BasicBlock Pass Manager";
136 // Print passes managed by this manager
137 void dumpPassStructure(unsigned Offset) {
138 llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
139 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
140 BasicBlockPass *BP = getContainedPass(Index);
141 BP->dumpPassStructure(Offset + 1);
142 dumpLastUses(BP, Offset+1);
146 BasicBlockPass *getContainedPass(unsigned N) {
147 assert(N < PassVector.size() && "Pass number out of range!");
148 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
152 virtual PassManagerType getPassManagerType() const {
153 return PMT_BasicBlockPassManager;
157 char BBPassManager::ID = 0;
162 //===----------------------------------------------------------------------===//
163 // FunctionPassManagerImpl
165 /// FunctionPassManagerImpl manages FPPassManagers
166 class FunctionPassManagerImpl : public Pass,
167 public PMDataManager,
168 public PMTopLevelManager {
173 explicit FunctionPassManagerImpl(int Depth) :
174 Pass(PT_PassManager, &ID), PMDataManager(Depth),
175 PMTopLevelManager(TLM_Function), wasRun(false) { }
177 /// add - Add a pass to the queue of passes to run. This passes ownership of
178 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
179 /// will be destroyed as well, so there is no need to delete the pass. This
180 /// implies that all passes MUST be allocated with 'new'.
185 // Prepare for running an on the fly pass, freeing memory if needed
186 // from a previous run.
187 void releaseMemoryOnTheFly();
189 /// run - Execute all of the passes scheduled for execution. Keep track of
190 /// whether any of the passes modifies the module, and if so, return true.
191 bool run(Function &F);
193 /// doInitialization - Run all of the initializers for the function passes.
195 bool doInitialization(Module &M);
197 /// doFinalization - Run all of the finalizers for the function passes.
199 bool doFinalization(Module &M);
202 virtual PMDataManager *getAsPMDataManager() { return this; }
203 virtual Pass *getAsPass() { return this; }
205 /// Pass Manager itself does not invalidate any analysis info.
206 void getAnalysisUsage(AnalysisUsage &Info) const {
207 Info.setPreservesAll();
210 inline void addTopLevelPass(Pass *P) {
211 if (ImmutablePass *IP = P->getAsImmutablePass()) {
212 // P is a immutable pass and it will be managed by this
213 // top level manager. Set up analysis resolver to connect them.
214 AnalysisResolver *AR = new AnalysisResolver(*this);
216 initializeAnalysisImpl(P);
217 addImmutablePass(IP);
218 recordAvailableAnalysis(IP);
220 P->assignPassManager(activeStack);
225 FPPassManager *getContainedManager(unsigned N) {
226 assert(N < PassManagers.size() && "Pass number out of range!");
227 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
232 char FunctionPassManagerImpl::ID = 0;
233 //===----------------------------------------------------------------------===//
236 /// MPPassManager manages ModulePasses and function pass managers.
237 /// It batches all Module passes and function pass managers together and
238 /// sequences them to process one module.
239 class MPPassManager : public Pass, public PMDataManager {
242 explicit MPPassManager(int Depth) :
243 Pass(PT_PassManager, &ID), PMDataManager(Depth) { }
245 // Delete on the fly managers.
246 virtual ~MPPassManager() {
247 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
248 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
250 FunctionPassManagerImpl *FPP = I->second;
255 /// run - Execute all of the passes scheduled for execution. Keep track of
256 /// whether any of the passes modifies the module, and if so, return true.
257 bool runOnModule(Module &M);
259 /// Pass Manager itself does not invalidate any analysis info.
260 void getAnalysisUsage(AnalysisUsage &Info) const {
261 Info.setPreservesAll();
264 /// Add RequiredPass into list of lower level passes required by pass P.
265 /// RequiredPass is run on the fly by Pass Manager when P requests it
266 /// through getAnalysis interface.
267 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
269 /// Return function pass corresponding to PassInfo PI, that is
270 /// required by module pass MP. Instantiate analysis pass, by using
271 /// its runOnFunction() for function F.
272 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
274 virtual const char *getPassName() const {
275 return "Module Pass Manager";
278 virtual PMDataManager *getAsPMDataManager() { return this; }
279 virtual Pass *getAsPass() { return this; }
281 // Print passes managed by this manager
282 void dumpPassStructure(unsigned Offset) {
283 llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
284 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
285 ModulePass *MP = getContainedPass(Index);
286 MP->dumpPassStructure(Offset + 1);
287 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
288 OnTheFlyManagers.find(MP);
289 if (I != OnTheFlyManagers.end())
290 I->second->dumpPassStructure(Offset + 2);
291 dumpLastUses(MP, Offset+1);
295 ModulePass *getContainedPass(unsigned N) {
296 assert(N < PassVector.size() && "Pass number out of range!");
297 return static_cast<ModulePass *>(PassVector[N]);
300 virtual PassManagerType getPassManagerType() const {
301 return PMT_ModulePassManager;
305 /// Collection of on the fly FPPassManagers. These managers manage
306 /// function passes that are required by module passes.
307 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
310 char MPPassManager::ID = 0;
311 //===----------------------------------------------------------------------===//
315 /// PassManagerImpl manages MPPassManagers
316 class PassManagerImpl : public Pass,
317 public PMDataManager,
318 public PMTopLevelManager {
322 explicit PassManagerImpl(int Depth) :
323 Pass(PT_PassManager, &ID), PMDataManager(Depth),
324 PMTopLevelManager(TLM_Pass) { }
326 /// add - Add a pass to the queue of passes to run. This passes ownership of
327 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
328 /// will be destroyed as well, so there is no need to delete the pass. This
329 /// implies that all passes MUST be allocated with 'new'.
334 /// run - Execute all of the passes scheduled for execution. Keep track of
335 /// whether any of the passes modifies the module, and if so, return true.
338 /// Pass Manager itself does not invalidate any analysis info.
339 void getAnalysisUsage(AnalysisUsage &Info) const {
340 Info.setPreservesAll();
343 inline void addTopLevelPass(Pass *P) {
344 if (ImmutablePass *IP = P->getAsImmutablePass()) {
345 // P is a immutable pass and it will be managed by this
346 // top level manager. Set up analysis resolver to connect them.
347 AnalysisResolver *AR = new AnalysisResolver(*this);
349 initializeAnalysisImpl(P);
350 addImmutablePass(IP);
351 recordAvailableAnalysis(IP);
353 P->assignPassManager(activeStack);
357 virtual PMDataManager *getAsPMDataManager() { return this; }
358 virtual Pass *getAsPass() { return this; }
360 MPPassManager *getContainedManager(unsigned N) {
361 assert(N < PassManagers.size() && "Pass number out of range!");
362 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
367 char PassManagerImpl::ID = 0;
368 } // End of llvm namespace
372 //===----------------------------------------------------------------------===//
373 /// TimingInfo Class - This class is used to calculate information about the
374 /// amount of time each pass takes to execute. This only happens when
375 /// -time-passes is enabled on the command line.
378 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
381 DenseMap<Pass*, Timer*> TimingData;
384 // Use 'create' member to get this.
385 TimingInfo() : TG("... Pass execution timing report ...") {}
387 // TimingDtor - Print out information about timing information
389 // Delete all of the timers, which accumulate their info into the
391 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
392 E = TimingData.end(); I != E; ++I)
394 // TimerGroup is deleted next, printing the report.
397 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
398 // to a non null value (if the -time-passes option is enabled) or it leaves it
399 // null. It may be called multiple times.
400 static void createTheTimeInfo();
402 /// getPassTimer - Return the timer for the specified pass if it exists.
403 Timer *getPassTimer(Pass *P) {
404 if (P->getAsPMDataManager())
407 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
408 Timer *&T = TimingData[P];
410 T = new Timer(P->getPassName(), TG);
415 } // End of anon namespace
417 static TimingInfo *TheTimeInfo;
419 //===----------------------------------------------------------------------===//
420 // PMTopLevelManager implementation
422 /// Initialize top level manager. Create first pass manager.
423 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
425 MPPassManager *MPP = new MPPassManager(1);
426 MPP->setTopLevelManager(this);
428 activeStack.push(MPP);
429 } else if (t == TLM_Function) {
430 FPPassManager *FPP = new FPPassManager(1);
431 FPP->setTopLevelManager(this);
433 activeStack.push(FPP);
437 /// Set pass P as the last user of the given analysis passes.
438 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
440 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
441 E = AnalysisPasses.end(); I != E; ++I) {
448 // If AP is the last user of other passes then make P last user of
450 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
451 LUE = LastUser.end(); LUI != LUE; ++LUI) {
452 if (LUI->second == AP)
453 // DenseMap iterator is not invalidated here because
454 // this is just updating exisitng entry.
455 LastUser[LUI->first] = P;
460 /// Collect passes whose last user is P
461 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
463 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
464 InversedLastUser.find(P);
465 if (DMI == InversedLastUser.end())
468 SmallPtrSet<Pass *, 8> &LU = DMI->second;
469 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
470 E = LU.end(); I != E; ++I) {
471 LastUses.push_back(*I);
476 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
477 AnalysisUsage *AnUsage = NULL;
478 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
479 if (DMI != AnUsageMap.end())
480 AnUsage = DMI->second;
482 AnUsage = new AnalysisUsage();
483 P->getAnalysisUsage(*AnUsage);
484 AnUsageMap[P] = AnUsage;
489 /// Schedule pass P for execution. Make sure that passes required by
490 /// P are run before P is run. Update analysis info maintained by
491 /// the manager. Remove dead passes. This is a recursive function.
492 void PMTopLevelManager::schedulePass(Pass *P) {
494 // TODO : Allocate function manager for this pass, other wise required set
495 // may be inserted into previous function manager
497 // Give pass a chance to prepare the stage.
498 P->preparePassManager(activeStack);
500 // If P is an analysis pass and it is available then do not
501 // generate the analysis again. Stale analysis info should not be
502 // available at this point.
503 if (P->getPassInfo() &&
504 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
509 AnalysisUsage *AnUsage = findAnalysisUsage(P);
511 bool checkAnalysis = true;
512 while (checkAnalysis) {
513 checkAnalysis = false;
515 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
516 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
517 E = RequiredSet.end(); I != E; ++I) {
519 Pass *AnalysisPass = findAnalysisPass(*I);
521 AnalysisPass = (*I)->createPass();
522 if (P->getPotentialPassManagerType () ==
523 AnalysisPass->getPotentialPassManagerType())
524 // Schedule analysis pass that is managed by the same pass manager.
525 schedulePass(AnalysisPass);
526 else if (P->getPotentialPassManagerType () >
527 AnalysisPass->getPotentialPassManagerType()) {
528 // Schedule analysis pass that is managed by a new manager.
529 schedulePass(AnalysisPass);
530 // Recheck analysis passes to ensure that required analysises that
531 // are already checked are still available.
532 checkAnalysis = true;
535 // Do not schedule this analysis. Lower level analsyis
536 // passes are run on the fly.
542 // Now all required passes are available.
546 /// Find the pass that implements Analysis AID. Search immutable
547 /// passes and all pass managers. If desired pass is not found
548 /// then return NULL.
549 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
552 // Check pass managers
553 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
554 E = PassManagers.end(); P == NULL && I != E; ++I) {
555 PMDataManager *PMD = *I;
556 P = PMD->findAnalysisPass(AID, false);
559 // Check other pass managers
560 for (SmallVector<PMDataManager *, 8>::iterator
561 I = IndirectPassManagers.begin(),
562 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
563 P = (*I)->findAnalysisPass(AID, false);
565 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
566 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
567 const PassInfo *PI = (*I)->getPassInfo();
571 // If Pass not found then check the interfaces implemented by Immutable Pass
573 const std::vector<const PassInfo*> &ImmPI =
574 PI->getInterfacesImplemented();
575 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
583 // Print passes managed by this top level manager.
584 void PMTopLevelManager::dumpPasses() const {
586 if (PassDebugging < Structure)
589 // Print out the immutable passes
590 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
591 ImmutablePasses[i]->dumpPassStructure(0);
594 // Every class that derives from PMDataManager also derives from Pass
595 // (sometimes indirectly), but there's no inheritance relationship
596 // between PMDataManager and Pass, so we have to getAsPass to get
597 // from a PMDataManager* to a Pass*.
598 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
599 E = PassManagers.end(); I != E; ++I)
600 (*I)->getAsPass()->dumpPassStructure(1);
603 void PMTopLevelManager::dumpArguments() const {
605 if (PassDebugging < Arguments)
608 dbgs() << "Pass Arguments: ";
609 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
610 E = PassManagers.end(); I != E; ++I)
611 (*I)->dumpPassArguments();
615 void PMTopLevelManager::initializeAllAnalysisInfo() {
616 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
617 E = PassManagers.end(); I != E; ++I)
618 (*I)->initializeAnalysisInfo();
620 // Initailize other pass managers
621 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
622 E = IndirectPassManagers.end(); I != E; ++I)
623 (*I)->initializeAnalysisInfo();
625 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
626 DME = LastUser.end(); DMI != DME; ++DMI) {
627 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
628 InversedLastUser.find(DMI->second);
629 if (InvDMI != InversedLastUser.end()) {
630 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
631 L.insert(DMI->first);
633 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
634 InversedLastUser[DMI->second] = L;
640 PMTopLevelManager::~PMTopLevelManager() {
641 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
642 E = PassManagers.end(); I != E; ++I)
645 for (SmallVector<ImmutablePass *, 8>::iterator
646 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
649 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
650 DME = AnUsageMap.end(); DMI != DME; ++DMI)
654 //===----------------------------------------------------------------------===//
655 // PMDataManager implementation
657 /// Augement AvailableAnalysis by adding analysis made available by pass P.
658 void PMDataManager::recordAvailableAnalysis(Pass *P) {
659 const PassInfo *PI = P->getPassInfo();
662 AvailableAnalysis[PI] = P;
664 //This pass is the current implementation of all of the interfaces it
665 //implements as well.
666 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
667 for (unsigned i = 0, e = II.size(); i != e; ++i)
668 AvailableAnalysis[II[i]] = P;
671 // Return true if P preserves high level analysis used by other
672 // passes managed by this manager
673 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
674 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
675 if (AnUsage->getPreservesAll())
678 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
679 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
680 E = HigherLevelAnalysis.end(); I != E; ++I) {
682 if (P1->getAsImmutablePass() == 0 &&
683 std::find(PreservedSet.begin(), PreservedSet.end(),
684 P1->getPassInfo()) ==
692 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
693 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
694 // Don't do this unless assertions are enabled.
698 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
699 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
701 // Verify preserved analysis
702 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
703 E = PreservedSet.end(); I != E; ++I) {
705 if (Pass *AP = findAnalysisPass(AID, true)) {
706 TimeRegion PassTimer(getPassTimer(AP));
707 AP->verifyAnalysis();
712 /// Remove Analysis not preserved by Pass P
713 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
714 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
715 if (AnUsage->getPreservesAll())
718 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
719 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
720 E = AvailableAnalysis.end(); I != E; ) {
721 std::map<AnalysisID, Pass*>::iterator Info = I++;
722 if (Info->second->getAsImmutablePass() == 0 &&
723 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
724 PreservedSet.end()) {
725 // Remove this analysis
726 if (PassDebugging >= Details) {
727 Pass *S = Info->second;
728 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
729 dbgs() << S->getPassName() << "'\n";
731 AvailableAnalysis.erase(Info);
735 // Check inherited analysis also. If P is not preserving analysis
736 // provided by parent manager then remove it here.
737 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
739 if (!InheritedAnalysis[Index])
742 for (std::map<AnalysisID, Pass*>::iterator
743 I = InheritedAnalysis[Index]->begin(),
744 E = InheritedAnalysis[Index]->end(); I != E; ) {
745 std::map<AnalysisID, Pass *>::iterator Info = I++;
746 if (Info->second->getAsImmutablePass() == 0 &&
747 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
748 PreservedSet.end()) {
749 // Remove this analysis
750 if (PassDebugging >= Details) {
751 Pass *S = Info->second;
752 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
753 dbgs() << S->getPassName() << "'\n";
755 InheritedAnalysis[Index]->erase(Info);
761 /// Remove analysis passes that are not used any longer
762 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
763 enum PassDebuggingString DBG_STR) {
765 SmallVector<Pass *, 12> DeadPasses;
767 // If this is a on the fly manager then it does not have TPM.
771 TPM->collectLastUses(DeadPasses, P);
773 if (PassDebugging >= Details && !DeadPasses.empty()) {
774 dbgs() << " -*- '" << P->getPassName();
775 dbgs() << "' is the last user of following pass instances.";
776 dbgs() << " Free these instances\n";
779 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
780 E = DeadPasses.end(); I != E; ++I)
781 freePass(*I, Msg, DBG_STR);
784 void PMDataManager::freePass(Pass *P, StringRef Msg,
785 enum PassDebuggingString DBG_STR) {
786 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
789 // If the pass crashes releasing memory, remember this.
790 PassManagerPrettyStackEntry X(P);
791 TimeRegion PassTimer(getPassTimer(P));
796 if (const PassInfo *PI = P->getPassInfo()) {
797 // Remove the pass itself (if it is not already removed).
798 AvailableAnalysis.erase(PI);
800 // Remove all interfaces this pass implements, for which it is also
801 // listed as the available implementation.
802 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
803 for (unsigned i = 0, e = II.size(); i != e; ++i) {
804 std::map<AnalysisID, Pass*>::iterator Pos =
805 AvailableAnalysis.find(II[i]);
806 if (Pos != AvailableAnalysis.end() && Pos->second == P)
807 AvailableAnalysis.erase(Pos);
812 /// Add pass P into the PassVector. Update
813 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
814 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
815 // This manager is going to manage pass P. Set up analysis resolver
817 AnalysisResolver *AR = new AnalysisResolver(*this);
820 // If a FunctionPass F is the last user of ModulePass info M
821 // then the F's manager, not F, records itself as a last user of M.
822 SmallVector<Pass *, 12> TransferLastUses;
824 if (!ProcessAnalysis) {
826 PassVector.push_back(P);
830 // At the moment, this pass is the last user of all required passes.
831 SmallVector<Pass *, 12> LastUses;
832 SmallVector<Pass *, 8> RequiredPasses;
833 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
835 unsigned PDepth = this->getDepth();
837 collectRequiredAnalysis(RequiredPasses,
838 ReqAnalysisNotAvailable, P);
839 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
840 E = RequiredPasses.end(); I != E; ++I) {
841 Pass *PRequired = *I;
844 assert(PRequired->getResolver() && "Analysis Resolver is not set");
845 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
846 RDepth = DM.getDepth();
848 if (PDepth == RDepth)
849 LastUses.push_back(PRequired);
850 else if (PDepth > RDepth) {
851 // Let the parent claim responsibility of last use
852 TransferLastUses.push_back(PRequired);
853 // Keep track of higher level analysis used by this manager.
854 HigherLevelAnalysis.push_back(PRequired);
856 llvm_unreachable("Unable to accomodate Required Pass");
859 // Set P as P's last user until someone starts using P.
860 // However, if P is a Pass Manager then it does not need
861 // to record its last user.
862 if (P->getAsPMDataManager() == 0)
863 LastUses.push_back(P);
864 TPM->setLastUser(LastUses, P);
866 if (!TransferLastUses.empty()) {
867 Pass *My_PM = getAsPass();
868 TPM->setLastUser(TransferLastUses, My_PM);
869 TransferLastUses.clear();
872 // Now, take care of required analysises that are not available.
873 for (SmallVector<AnalysisID, 8>::iterator
874 I = ReqAnalysisNotAvailable.begin(),
875 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
876 Pass *AnalysisPass = (*I)->createPass();
877 this->addLowerLevelRequiredPass(P, AnalysisPass);
880 // Take a note of analysis required and made available by this pass.
881 // Remove the analysis not preserved by this pass
882 removeNotPreservedAnalysis(P);
883 recordAvailableAnalysis(P);
886 PassVector.push_back(P);
890 /// Populate RP with analysis pass that are required by
891 /// pass P and are available. Populate RP_NotAvail with analysis
892 /// pass that are required by pass P but are not available.
893 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
894 SmallVector<AnalysisID, 8> &RP_NotAvail,
896 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
897 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
898 for (AnalysisUsage::VectorType::const_iterator
899 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
900 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
901 RP.push_back(AnalysisPass);
903 RP_NotAvail.push_back(*I);
906 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
907 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
908 E = IDs.end(); I != E; ++I) {
909 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
910 RP.push_back(AnalysisPass);
912 RP_NotAvail.push_back(*I);
916 // All Required analyses should be available to the pass as it runs! Here
917 // we fill in the AnalysisImpls member of the pass so that it can
918 // successfully use the getAnalysis() method to retrieve the
919 // implementations it needs.
921 void PMDataManager::initializeAnalysisImpl(Pass *P) {
922 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
924 for (AnalysisUsage::VectorType::const_iterator
925 I = AnUsage->getRequiredSet().begin(),
926 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
927 Pass *Impl = findAnalysisPass(*I, true);
929 // This may be analysis pass that is initialized on the fly.
930 // If that is not the case then it will raise an assert when it is used.
932 AnalysisResolver *AR = P->getResolver();
933 assert(AR && "Analysis Resolver is not set");
934 AR->addAnalysisImplsPair(*I, Impl);
938 /// Find the pass that implements Analysis AID. If desired pass is not found
939 /// then return NULL.
940 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
942 // Check if AvailableAnalysis map has one entry.
943 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
945 if (I != AvailableAnalysis.end())
948 // Search Parents through TopLevelManager
950 return TPM->findAnalysisPass(AID);
955 // Print list of passes that are last used by P.
956 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
958 SmallVector<Pass *, 12> LUses;
960 // If this is a on the fly manager then it does not have TPM.
964 TPM->collectLastUses(LUses, P);
966 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
967 E = LUses.end(); I != E; ++I) {
968 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
969 (*I)->dumpPassStructure(0);
973 void PMDataManager::dumpPassArguments() const {
974 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
975 E = PassVector.end(); I != E; ++I) {
976 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
977 PMD->dumpPassArguments();
979 if (const PassInfo *PI = (*I)->getPassInfo())
980 if (!PI->isAnalysisGroup())
981 dbgs() << " -" << PI->getPassArgument();
985 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
986 enum PassDebuggingString S2,
988 if (PassDebugging < Executions)
990 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
993 dbgs() << "Executing Pass '" << P->getPassName();
995 case MODIFICATION_MSG:
996 dbgs() << "Made Modification '" << P->getPassName();
999 dbgs() << " Freeing Pass '" << P->getPassName();
1005 case ON_BASICBLOCK_MSG:
1006 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1008 case ON_FUNCTION_MSG:
1009 dbgs() << "' on Function '" << Msg << "'...\n";
1012 dbgs() << "' on Module '" << Msg << "'...\n";
1015 dbgs() << "' on Loop '" << Msg << "'...\n";
1018 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1025 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1026 if (PassDebugging < Details)
1029 AnalysisUsage analysisUsage;
1030 P->getAnalysisUsage(analysisUsage);
1031 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1034 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1035 if (PassDebugging < Details)
1038 AnalysisUsage analysisUsage;
1039 P->getAnalysisUsage(analysisUsage);
1040 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1043 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1044 const AnalysisUsage::VectorType &Set) const {
1045 assert(PassDebugging >= Details);
1048 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1049 for (unsigned i = 0; i != Set.size(); ++i) {
1050 if (i) dbgs() << ',';
1051 dbgs() << ' ' << Set[i]->getPassName();
1056 /// Add RequiredPass into list of lower level passes required by pass P.
1057 /// RequiredPass is run on the fly by Pass Manager when P requests it
1058 /// through getAnalysis interface.
1059 /// This should be handled by specific pass manager.
1060 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1062 TPM->dumpArguments();
1066 // Module Level pass may required Function Level analysis info
1067 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1068 // to provide this on demand. In that case, in Pass manager terminology,
1069 // module level pass is requiring lower level analysis info managed by
1070 // lower level pass manager.
1072 // When Pass manager is not able to order required analysis info, Pass manager
1073 // checks whether any lower level manager will be able to provide this
1074 // analysis info on demand or not.
1076 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1077 dbgs() << "' required by '" << P->getPassName() << "'\n";
1079 llvm_unreachable("Unable to schedule pass");
1083 PMDataManager::~PMDataManager() {
1084 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1085 E = PassVector.end(); I != E; ++I)
1089 //===----------------------------------------------------------------------===//
1090 // NOTE: Is this the right place to define this method ?
1091 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1092 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1093 return PM.findAnalysisPass(ID, dir);
1096 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1098 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1101 //===----------------------------------------------------------------------===//
1102 // BBPassManager implementation
1104 /// Execute all of the passes scheduled for execution by invoking
1105 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1106 /// the function, and if so, return true.
1107 bool BBPassManager::runOnFunction(Function &F) {
1108 if (F.isDeclaration())
1111 bool Changed = doInitialization(F);
1113 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1114 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1115 BasicBlockPass *BP = getContainedPass(Index);
1116 bool LocalChanged = false;
1118 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1119 dumpRequiredSet(BP);
1121 initializeAnalysisImpl(BP);
1124 // If the pass crashes, remember this.
1125 PassManagerPrettyStackEntry X(BP, *I);
1126 TimeRegion PassTimer(getPassTimer(BP));
1128 LocalChanged |= BP->runOnBasicBlock(*I);
1131 Changed |= LocalChanged;
1133 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1135 dumpPreservedSet(BP);
1137 verifyPreservedAnalysis(BP);
1138 removeNotPreservedAnalysis(BP);
1139 recordAvailableAnalysis(BP);
1140 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1143 return doFinalization(F) || Changed;
1146 // Implement doInitialization and doFinalization
1147 bool BBPassManager::doInitialization(Module &M) {
1148 bool Changed = false;
1150 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1151 Changed |= getContainedPass(Index)->doInitialization(M);
1156 bool BBPassManager::doFinalization(Module &M) {
1157 bool Changed = false;
1159 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1160 Changed |= getContainedPass(Index)->doFinalization(M);
1165 bool BBPassManager::doInitialization(Function &F) {
1166 bool Changed = false;
1168 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1169 BasicBlockPass *BP = getContainedPass(Index);
1170 Changed |= BP->doInitialization(F);
1176 bool BBPassManager::doFinalization(Function &F) {
1177 bool Changed = false;
1179 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1180 BasicBlockPass *BP = getContainedPass(Index);
1181 Changed |= BP->doFinalization(F);
1188 //===----------------------------------------------------------------------===//
1189 // FunctionPassManager implementation
1191 /// Create new Function pass manager
1192 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1193 FPM = new FunctionPassManagerImpl(0);
1194 // FPM is the top level manager.
1195 FPM->setTopLevelManager(FPM);
1197 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1198 FPM->setResolver(AR);
1201 FunctionPassManager::~FunctionPassManager() {
1205 /// add - Add a pass to the queue of passes to run. This passes
1206 /// ownership of the Pass to the PassManager. When the
1207 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1208 /// there is no need to delete the pass. (TODO delete passes.)
1209 /// This implies that all passes MUST be allocated with 'new'.
1210 void FunctionPassManager::add(Pass *P) {
1214 /// run - Execute all of the passes scheduled for execution. Keep
1215 /// track of whether any of the passes modifies the function, and if
1216 /// so, return true.
1218 bool FunctionPassManager::run(Function &F) {
1219 if (F.isMaterializable()) {
1221 if (F.Materialize(&errstr)) {
1222 llvm_report_error("Error reading bitcode file: " + errstr);
1229 /// doInitialization - Run all of the initializers for the function passes.
1231 bool FunctionPassManager::doInitialization() {
1232 return FPM->doInitialization(*M);
1235 /// doFinalization - Run all of the finalizers for the function passes.
1237 bool FunctionPassManager::doFinalization() {
1238 return FPM->doFinalization(*M);
1241 //===----------------------------------------------------------------------===//
1242 // FunctionPassManagerImpl implementation
1244 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1245 bool Changed = false;
1250 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1251 Changed |= getContainedManager(Index)->doInitialization(M);
1256 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1257 bool Changed = false;
1259 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1260 Changed |= getContainedManager(Index)->doFinalization(M);
1265 /// cleanup - After running all passes, clean up pass manager cache.
1266 void FPPassManager::cleanup() {
1267 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1268 FunctionPass *FP = getContainedPass(Index);
1269 AnalysisResolver *AR = FP->getResolver();
1270 assert(AR && "Analysis Resolver is not set");
1271 AR->clearAnalysisImpls();
1275 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1278 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1279 FPPassManager *FPPM = getContainedManager(Index);
1280 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1281 FPPM->getContainedPass(Index)->releaseMemory();
1287 // Execute all the passes managed by this top level manager.
1288 // Return true if any function is modified by a pass.
1289 bool FunctionPassManagerImpl::run(Function &F) {
1290 bool Changed = false;
1291 TimingInfo::createTheTimeInfo();
1293 initializeAllAnalysisInfo();
1294 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1295 Changed |= getContainedManager(Index)->runOnFunction(F);
1297 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1298 getContainedManager(Index)->cleanup();
1304 //===----------------------------------------------------------------------===//
1305 // FPPassManager implementation
1307 char FPPassManager::ID = 0;
1308 /// Print passes managed by this manager
1309 void FPPassManager::dumpPassStructure(unsigned Offset) {
1310 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1311 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1312 FunctionPass *FP = getContainedPass(Index);
1313 FP->dumpPassStructure(Offset + 1);
1314 dumpLastUses(FP, Offset+1);
1319 /// Execute all of the passes scheduled for execution by invoking
1320 /// runOnFunction method. Keep track of whether any of the passes modifies
1321 /// the function, and if so, return true.
1322 bool FPPassManager::runOnFunction(Function &F) {
1323 if (F.isDeclaration())
1326 bool Changed = false;
1328 // Collect inherited analysis from Module level pass manager.
1329 populateInheritedAnalysis(TPM->activeStack);
1331 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1332 FunctionPass *FP = getContainedPass(Index);
1333 bool LocalChanged = false;
1335 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1336 dumpRequiredSet(FP);
1338 initializeAnalysisImpl(FP);
1341 PassManagerPrettyStackEntry X(FP, F);
1342 TimeRegion PassTimer(getPassTimer(FP));
1344 LocalChanged |= FP->runOnFunction(F);
1347 Changed |= LocalChanged;
1349 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1350 dumpPreservedSet(FP);
1352 verifyPreservedAnalysis(FP);
1353 removeNotPreservedAnalysis(FP);
1354 recordAvailableAnalysis(FP);
1355 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1360 bool FPPassManager::runOnModule(Module &M) {
1361 bool Changed = doInitialization(M);
1363 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1366 return doFinalization(M) || Changed;
1369 bool FPPassManager::doInitialization(Module &M) {
1370 bool Changed = false;
1372 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1373 Changed |= getContainedPass(Index)->doInitialization(M);
1378 bool FPPassManager::doFinalization(Module &M) {
1379 bool Changed = false;
1381 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1382 Changed |= getContainedPass(Index)->doFinalization(M);
1387 //===----------------------------------------------------------------------===//
1388 // MPPassManager implementation
1390 /// Execute all of the passes scheduled for execution by invoking
1391 /// runOnModule method. Keep track of whether any of the passes modifies
1392 /// the module, and if so, return true.
1394 MPPassManager::runOnModule(Module &M) {
1395 bool Changed = false;
1397 // Initialize on-the-fly passes
1398 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1399 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1401 FunctionPassManagerImpl *FPP = I->second;
1402 Changed |= FPP->doInitialization(M);
1405 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1406 ModulePass *MP = getContainedPass(Index);
1407 bool LocalChanged = false;
1409 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1410 dumpRequiredSet(MP);
1412 initializeAnalysisImpl(MP);
1415 PassManagerPrettyStackEntry X(MP, M);
1416 TimeRegion PassTimer(getPassTimer(MP));
1418 LocalChanged |= MP->runOnModule(M);
1421 Changed |= LocalChanged;
1423 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1424 M.getModuleIdentifier());
1425 dumpPreservedSet(MP);
1427 verifyPreservedAnalysis(MP);
1428 removeNotPreservedAnalysis(MP);
1429 recordAvailableAnalysis(MP);
1430 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1433 // Finalize on-the-fly passes
1434 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1435 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1437 FunctionPassManagerImpl *FPP = I->second;
1438 // We don't know when is the last time an on-the-fly pass is run,
1439 // so we need to releaseMemory / finalize here
1440 FPP->releaseMemoryOnTheFly();
1441 Changed |= FPP->doFinalization(M);
1446 /// Add RequiredPass into list of lower level passes required by pass P.
1447 /// RequiredPass is run on the fly by Pass Manager when P requests it
1448 /// through getAnalysis interface.
1449 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1450 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1451 "Unable to handle Pass that requires lower level Analysis pass");
1452 assert((P->getPotentialPassManagerType() <
1453 RequiredPass->getPotentialPassManagerType()) &&
1454 "Unable to handle Pass that requires lower level Analysis pass");
1456 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1458 FPP = new FunctionPassManagerImpl(0);
1459 // FPP is the top level manager.
1460 FPP->setTopLevelManager(FPP);
1462 OnTheFlyManagers[P] = FPP;
1464 FPP->add(RequiredPass);
1466 // Register P as the last user of RequiredPass.
1467 SmallVector<Pass *, 12> LU;
1468 LU.push_back(RequiredPass);
1469 FPP->setLastUser(LU, P);
1472 /// Return function pass corresponding to PassInfo PI, that is
1473 /// required by module pass MP. Instantiate analysis pass, by using
1474 /// its runOnFunction() for function F.
1475 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1476 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1477 assert(FPP && "Unable to find on the fly pass");
1479 FPP->releaseMemoryOnTheFly();
1481 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1485 //===----------------------------------------------------------------------===//
1486 // PassManagerImpl implementation
1488 /// run - Execute all of the passes scheduled for execution. Keep track of
1489 /// whether any of the passes modifies the module, and if so, return true.
1490 bool PassManagerImpl::run(Module &M) {
1491 bool Changed = false;
1492 TimingInfo::createTheTimeInfo();
1497 initializeAllAnalysisInfo();
1498 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1499 Changed |= getContainedManager(Index)->runOnModule(M);
1503 //===----------------------------------------------------------------------===//
1504 // PassManager implementation
1506 /// Create new pass manager
1507 PassManager::PassManager() {
1508 PM = new PassManagerImpl(0);
1509 // PM is the top level manager
1510 PM->setTopLevelManager(PM);
1513 PassManager::~PassManager() {
1517 /// add - Add a pass to the queue of passes to run. This passes ownership of
1518 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1519 /// will be destroyed as well, so there is no need to delete the pass. This
1520 /// implies that all passes MUST be allocated with 'new'.
1521 void PassManager::add(Pass *P) {
1525 /// run - Execute all of the passes scheduled for execution. Keep track of
1526 /// whether any of the passes modifies the module, and if so, return true.
1527 bool PassManager::run(Module &M) {
1531 //===----------------------------------------------------------------------===//
1532 // TimingInfo Class - This class is used to calculate information about the
1533 // amount of time each pass takes to execute. This only happens with
1534 // -time-passes is enabled on the command line.
1536 bool llvm::TimePassesIsEnabled = false;
1537 static cl::opt<bool,true>
1538 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1539 cl::desc("Time each pass, printing elapsed time for each on exit"));
1541 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1542 // a non null value (if the -time-passes option is enabled) or it leaves it
1543 // null. It may be called multiple times.
1544 void TimingInfo::createTheTimeInfo() {
1545 if (!TimePassesIsEnabled || TheTimeInfo) return;
1547 // Constructed the first time this is called, iff -time-passes is enabled.
1548 // This guarantees that the object will be constructed before static globals,
1549 // thus it will be destroyed before them.
1550 static ManagedStatic<TimingInfo> TTI;
1551 TheTimeInfo = &*TTI;
1554 /// If TimingInfo is enabled then start pass timer.
1555 Timer *llvm::getPassTimer(Pass *P) {
1557 return TheTimeInfo->getPassTimer(P);
1561 //===----------------------------------------------------------------------===//
1562 // PMStack implementation
1565 // Pop Pass Manager from the stack and clear its analysis info.
1566 void PMStack::pop() {
1568 PMDataManager *Top = this->top();
1569 Top->initializeAnalysisInfo();
1574 // Push PM on the stack and set its top level manager.
1575 void PMStack::push(PMDataManager *PM) {
1576 assert(PM && "Unable to push. Pass Manager expected");
1578 if (!this->empty()) {
1579 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1581 assert(TPM && "Unable to find top level manager");
1582 TPM->addIndirectPassManager(PM);
1583 PM->setTopLevelManager(TPM);
1589 // Dump content of the pass manager stack.
1590 void PMStack::dump() {
1591 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1592 E = S.end(); I != E; ++I)
1593 printf("%s ", (*I)->getAsPass()->getPassName());
1599 /// Find appropriate Module Pass Manager in the PM Stack and
1600 /// add self into that manager.
1601 void ModulePass::assignPassManager(PMStack &PMS,
1602 PassManagerType PreferredType) {
1603 // Find Module Pass Manager
1604 while(!PMS.empty()) {
1605 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1606 if (TopPMType == PreferredType)
1607 break; // We found desired pass manager
1608 else if (TopPMType > PMT_ModulePassManager)
1609 PMS.pop(); // Pop children pass managers
1613 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1614 PMS.top()->add(this);
1617 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1618 /// in the PM Stack and add self into that manager.
1619 void FunctionPass::assignPassManager(PMStack &PMS,
1620 PassManagerType PreferredType) {
1622 // Find Module Pass Manager
1623 while (!PMS.empty()) {
1624 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1630 // Create new Function Pass Manager if needed.
1632 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1633 FPP = (FPPassManager *)PMS.top();
1635 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1636 PMDataManager *PMD = PMS.top();
1638 // [1] Create new Function Pass Manager
1639 FPP = new FPPassManager(PMD->getDepth() + 1);
1640 FPP->populateInheritedAnalysis(PMS);
1642 // [2] Set up new manager's top level manager
1643 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1644 TPM->addIndirectPassManager(FPP);
1646 // [3] Assign manager to manage this new manager. This may create
1647 // and push new managers into PMS
1648 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1650 // [4] Push new manager into PMS
1654 // Assign FPP as the manager of this pass.
1658 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1659 /// in the PM Stack and add self into that manager.
1660 void BasicBlockPass::assignPassManager(PMStack &PMS,
1661 PassManagerType PreferredType) {
1664 // Basic Pass Manager is a leaf pass manager. It does not handle
1665 // any other pass manager.
1667 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1668 BBP = (BBPassManager *)PMS.top();
1670 // If leaf manager is not Basic Block Pass manager then create new
1671 // basic Block Pass manager.
1672 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1673 PMDataManager *PMD = PMS.top();
1675 // [1] Create new Basic Block Manager
1676 BBP = new BBPassManager(PMD->getDepth() + 1);
1678 // [2] Set up new manager's top level manager
1679 // Basic Block Pass Manager does not live by itself
1680 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1681 TPM->addIndirectPassManager(BBP);
1683 // [3] Assign manager to manage this new manager. This may create
1684 // and push new managers into PMS
1685 BBP->assignPassManager(PMS);
1687 // [4] Push new manager into PMS
1691 // Assign BBP as the manager of this pass.
1695 PassManagerBase::~PassManagerBase() {}
1697 /*===-- C Bindings --------------------------------------------------------===*/
1699 LLVMPassManagerRef LLVMCreatePassManager() {
1700 return wrap(new PassManager());
1703 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
1704 return wrap(new FunctionPassManager(unwrap(M)));
1707 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1708 return LLVMCreateFunctionPassManagerForModule(
1709 reinterpret_cast<LLVMModuleRef>(P));
1712 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1713 return unwrap<PassManager>(PM)->run(*unwrap(M));
1716 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1717 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1720 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1721 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1724 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1725 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1728 void LLVMDisposePassManager(LLVMPassManagerRef PM) {