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/PrintModulePass.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/Timer.h"
21 #include "llvm/Module.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/System/Mutex.h"
27 #include "llvm/System/Threading.h"
28 #include "llvm-c/Core.h"
34 // See PassManagers.h for Pass Manager infrastructure overview.
38 //===----------------------------------------------------------------------===//
39 // Pass debugging information. Often it is useful to find out what pass is
40 // running when a crash occurs in a utility. When this library is compiled with
41 // debugging on, a command line option (--debug-pass) is enabled that causes the
42 // pass name to be printed before it executes.
45 // Different debug levels that can be enabled...
47 None, Arguments, Structure, Executions, Details
50 static cl::opt<enum PassDebugLevel>
51 PassDebugging("debug-pass", cl::Hidden,
52 cl::desc("Print PassManager debugging information"),
54 clEnumVal(None , "disable debug output"),
55 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
56 clEnumVal(Structure , "print pass structure before run()"),
57 clEnumVal(Executions, "print pass name before it is executed"),
58 clEnumVal(Details , "print pass details when it is executed"),
61 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
64 // Print IR out before/after specified passes.
66 PrintBefore("print-before",
67 llvm::cl::desc("Print IR before specified passes"));
70 PrintAfter("print-after",
71 llvm::cl::desc("Print IR after specified passes"));
74 PrintBeforeAll("print-before-all",
75 llvm::cl::desc("Print IR before each pass"),
78 PrintAfterAll("print-after-all",
79 llvm::cl::desc("Print IR after each pass"),
82 /// This is a helper to determine whether to print IR before or
85 static bool ShouldPrintBeforeOrAfterPass(Pass *P,
86 PassOptionList &PassesToPrint) {
87 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
88 const llvm::PassInfo *PassInf = PassesToPrint[i];
89 if (PassInf && P->getPassInfo())
90 if (PassInf->getPassArgument() ==
91 P->getPassInfo()->getPassArgument()) {
99 /// This is a utility to check whether a pass should have IR dumped
101 static bool ShouldPrintBeforePass(Pass *P) {
102 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(P, PrintBefore);
105 /// This is a utility to check whether a pass should have IR dumped
107 static bool ShouldPrintAfterPass(Pass *P) {
108 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(P, PrintAfter);
111 } // End of llvm namespace
113 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
114 /// or higher is specified.
115 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
116 return PassDebugging >= Executions;
122 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
123 if (V == 0 && M == 0)
124 OS << "Releasing pass '";
126 OS << "Running pass '";
128 OS << P->getPassName() << "'";
131 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
140 if (isa<Function>(V))
142 else if (isa<BasicBlock>(V))
148 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
155 //===----------------------------------------------------------------------===//
158 /// BBPassManager manages BasicBlockPass. It batches all the
159 /// pass together and sequence them to process one basic block before
160 /// processing next basic block.
161 class BBPassManager : public PMDataManager, public FunctionPass {
165 explicit BBPassManager(int Depth)
166 : PMDataManager(Depth), FunctionPass(&ID) {}
168 /// Execute all of the passes scheduled for execution. Keep track of
169 /// whether any of the passes modifies the function, and if so, return true.
170 bool runOnFunction(Function &F);
172 /// Pass Manager itself does not invalidate any analysis info.
173 void getAnalysisUsage(AnalysisUsage &Info) const {
174 Info.setPreservesAll();
177 bool doInitialization(Module &M);
178 bool doInitialization(Function &F);
179 bool doFinalization(Module &M);
180 bool doFinalization(Function &F);
182 virtual PMDataManager *getAsPMDataManager() { return this; }
183 virtual Pass *getAsPass() { return this; }
185 virtual const char *getPassName() const {
186 return "BasicBlock Pass Manager";
189 // Print passes managed by this manager
190 void dumpPassStructure(unsigned Offset) {
191 llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
192 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
193 BasicBlockPass *BP = getContainedPass(Index);
194 BP->dumpPassStructure(Offset + 1);
195 dumpLastUses(BP, Offset+1);
199 BasicBlockPass *getContainedPass(unsigned N) {
200 assert(N < PassVector.size() && "Pass number out of range!");
201 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
205 virtual PassManagerType getPassManagerType() const {
206 return PMT_BasicBlockPassManager;
210 char BBPassManager::ID = 0;
215 //===----------------------------------------------------------------------===//
216 // FunctionPassManagerImpl
218 /// FunctionPassManagerImpl manages FPPassManagers
219 class FunctionPassManagerImpl : public Pass,
220 public PMDataManager,
221 public PMTopLevelManager {
226 explicit FunctionPassManagerImpl(int Depth) :
227 Pass(PT_PassManager, &ID), PMDataManager(Depth),
228 PMTopLevelManager(TLM_Function), wasRun(false) { }
230 /// add - Add a pass to the queue of passes to run. This passes ownership of
231 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
232 /// will be destroyed as well, so there is no need to delete the pass. This
233 /// implies that all passes MUST be allocated with 'new'.
238 /// createPrinterPass - Get a function printer pass.
239 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
240 return createPrintFunctionPass(Banner, &O);
243 // Prepare for running an on the fly pass, freeing memory if needed
244 // from a previous run.
245 void releaseMemoryOnTheFly();
247 /// run - Execute all of the passes scheduled for execution. Keep track of
248 /// whether any of the passes modifies the module, and if so, return true.
249 bool run(Function &F);
251 /// doInitialization - Run all of the initializers for the function passes.
253 bool doInitialization(Module &M);
255 /// doFinalization - Run all of the finalizers for the function passes.
257 bool doFinalization(Module &M);
260 virtual PMDataManager *getAsPMDataManager() { return this; }
261 virtual Pass *getAsPass() { return this; }
263 /// Pass Manager itself does not invalidate any analysis info.
264 void getAnalysisUsage(AnalysisUsage &Info) const {
265 Info.setPreservesAll();
268 inline void addTopLevelPass(Pass *P) {
269 if (ImmutablePass *IP = P->getAsImmutablePass()) {
270 // P is a immutable pass and it will be managed by this
271 // top level manager. Set up analysis resolver to connect them.
272 AnalysisResolver *AR = new AnalysisResolver(*this);
274 initializeAnalysisImpl(P);
275 addImmutablePass(IP);
276 recordAvailableAnalysis(IP);
278 P->assignPassManager(activeStack, PMT_FunctionPassManager);
283 FPPassManager *getContainedManager(unsigned N) {
284 assert(N < PassManagers.size() && "Pass number out of range!");
285 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
290 char FunctionPassManagerImpl::ID = 0;
291 //===----------------------------------------------------------------------===//
294 /// MPPassManager manages ModulePasses and function pass managers.
295 /// It batches all Module passes and function pass managers together and
296 /// sequences them to process one module.
297 class MPPassManager : public Pass, public PMDataManager {
300 explicit MPPassManager(int Depth) :
301 Pass(PT_PassManager, &ID), PMDataManager(Depth) { }
303 // Delete on the fly managers.
304 virtual ~MPPassManager() {
305 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
306 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
308 FunctionPassManagerImpl *FPP = I->second;
313 /// createPrinterPass - Get a module printer pass.
314 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
315 return createPrintModulePass(&O, false, Banner);
318 /// run - Execute all of the passes scheduled for execution. Keep track of
319 /// whether any of the passes modifies the module, and if so, return true.
320 bool runOnModule(Module &M);
322 /// Pass Manager itself does not invalidate any analysis info.
323 void getAnalysisUsage(AnalysisUsage &Info) const {
324 Info.setPreservesAll();
327 /// Add RequiredPass into list of lower level passes required by pass P.
328 /// RequiredPass is run on the fly by Pass Manager when P requests it
329 /// through getAnalysis interface.
330 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
332 /// Return function pass corresponding to PassInfo PI, that is
333 /// required by module pass MP. Instantiate analysis pass, by using
334 /// its runOnFunction() for function F.
335 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
337 virtual const char *getPassName() const {
338 return "Module Pass Manager";
341 virtual PMDataManager *getAsPMDataManager() { return this; }
342 virtual Pass *getAsPass() { return this; }
344 // Print passes managed by this manager
345 void dumpPassStructure(unsigned Offset) {
346 llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
347 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
348 ModulePass *MP = getContainedPass(Index);
349 MP->dumpPassStructure(Offset + 1);
350 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
351 OnTheFlyManagers.find(MP);
352 if (I != OnTheFlyManagers.end())
353 I->second->dumpPassStructure(Offset + 2);
354 dumpLastUses(MP, Offset+1);
358 ModulePass *getContainedPass(unsigned N) {
359 assert(N < PassVector.size() && "Pass number out of range!");
360 return static_cast<ModulePass *>(PassVector[N]);
363 virtual PassManagerType getPassManagerType() const {
364 return PMT_ModulePassManager;
368 /// Collection of on the fly FPPassManagers. These managers manage
369 /// function passes that are required by module passes.
370 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
373 char MPPassManager::ID = 0;
374 //===----------------------------------------------------------------------===//
378 /// PassManagerImpl manages MPPassManagers
379 class PassManagerImpl : public Pass,
380 public PMDataManager,
381 public PMTopLevelManager {
385 explicit PassManagerImpl(int Depth) :
386 Pass(PT_PassManager, &ID), PMDataManager(Depth),
387 PMTopLevelManager(TLM_Pass) { }
389 /// add - Add a pass to the queue of passes to run. This passes ownership of
390 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
391 /// will be destroyed as well, so there is no need to delete the pass. This
392 /// implies that all passes MUST be allocated with 'new'.
397 /// createPrinterPass - Get a module printer pass.
398 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
399 return createPrintModulePass(&O, false, Banner);
402 /// run - Execute all of the passes scheduled for execution. Keep track of
403 /// whether any of the passes modifies the module, and if so, return true.
406 /// Pass Manager itself does not invalidate any analysis info.
407 void getAnalysisUsage(AnalysisUsage &Info) const {
408 Info.setPreservesAll();
411 inline void addTopLevelPass(Pass *P) {
412 if (ImmutablePass *IP = P->getAsImmutablePass()) {
413 // P is a immutable pass and it will be managed by this
414 // top level manager. Set up analysis resolver to connect them.
415 AnalysisResolver *AR = new AnalysisResolver(*this);
417 initializeAnalysisImpl(P);
418 addImmutablePass(IP);
419 recordAvailableAnalysis(IP);
421 P->assignPassManager(activeStack, PMT_ModulePassManager);
425 virtual PMDataManager *getAsPMDataManager() { return this; }
426 virtual Pass *getAsPass() { return this; }
428 MPPassManager *getContainedManager(unsigned N) {
429 assert(N < PassManagers.size() && "Pass number out of range!");
430 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
435 char PassManagerImpl::ID = 0;
436 } // End of llvm namespace
440 //===----------------------------------------------------------------------===//
441 /// TimingInfo Class - This class is used to calculate information about the
442 /// amount of time each pass takes to execute. This only happens when
443 /// -time-passes is enabled on the command line.
446 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
449 DenseMap<Pass*, Timer*> TimingData;
452 // Use 'create' member to get this.
453 TimingInfo() : TG("... Pass execution timing report ...") {}
455 // TimingDtor - Print out information about timing information
457 // Delete all of the timers, which accumulate their info into the
459 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
460 E = TimingData.end(); I != E; ++I)
462 // TimerGroup is deleted next, printing the report.
465 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
466 // to a non null value (if the -time-passes option is enabled) or it leaves it
467 // null. It may be called multiple times.
468 static void createTheTimeInfo();
470 /// getPassTimer - Return the timer for the specified pass if it exists.
471 Timer *getPassTimer(Pass *P) {
472 if (P->getAsPMDataManager())
475 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
476 Timer *&T = TimingData[P];
478 T = new Timer(P->getPassName(), TG);
483 } // End of anon namespace
485 static TimingInfo *TheTimeInfo;
487 //===----------------------------------------------------------------------===//
488 // PMTopLevelManager implementation
490 /// Initialize top level manager. Create first pass manager.
491 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
493 MPPassManager *MPP = new MPPassManager(1);
494 MPP->setTopLevelManager(this);
496 activeStack.push(MPP);
497 } else if (t == TLM_Function) {
498 FPPassManager *FPP = new FPPassManager(1);
499 FPP->setTopLevelManager(this);
501 activeStack.push(FPP);
505 /// Set pass P as the last user of the given analysis passes.
506 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
508 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
509 E = AnalysisPasses.end(); I != E; ++I) {
516 // If AP is the last user of other passes then make P last user of
518 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
519 LUE = LastUser.end(); LUI != LUE; ++LUI) {
520 if (LUI->second == AP)
521 // DenseMap iterator is not invalidated here because
522 // this is just updating exisitng entry.
523 LastUser[LUI->first] = P;
528 /// Collect passes whose last user is P
529 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
531 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
532 InversedLastUser.find(P);
533 if (DMI == InversedLastUser.end())
536 SmallPtrSet<Pass *, 8> &LU = DMI->second;
537 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
538 E = LU.end(); I != E; ++I) {
539 LastUses.push_back(*I);
544 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
545 AnalysisUsage *AnUsage = NULL;
546 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
547 if (DMI != AnUsageMap.end())
548 AnUsage = DMI->second;
550 AnUsage = new AnalysisUsage();
551 P->getAnalysisUsage(*AnUsage);
552 AnUsageMap[P] = AnUsage;
557 /// Schedule pass P for execution. Make sure that passes required by
558 /// P are run before P is run. Update analysis info maintained by
559 /// the manager. Remove dead passes. This is a recursive function.
560 void PMTopLevelManager::schedulePass(Pass *P) {
562 // TODO : Allocate function manager for this pass, other wise required set
563 // may be inserted into previous function manager
565 // Give pass a chance to prepare the stage.
566 P->preparePassManager(activeStack);
568 // If P is an analysis pass and it is available then do not
569 // generate the analysis again. Stale analysis info should not be
570 // available at this point.
571 if (P->getPassInfo() &&
572 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
577 AnalysisUsage *AnUsage = findAnalysisUsage(P);
579 bool checkAnalysis = true;
580 while (checkAnalysis) {
581 checkAnalysis = false;
583 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
584 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
585 E = RequiredSet.end(); I != E; ++I) {
587 Pass *AnalysisPass = findAnalysisPass(*I);
589 AnalysisPass = (*I)->createPass();
590 if (P->getPotentialPassManagerType () ==
591 AnalysisPass->getPotentialPassManagerType())
592 // Schedule analysis pass that is managed by the same pass manager.
593 schedulePass(AnalysisPass);
594 else if (P->getPotentialPassManagerType () >
595 AnalysisPass->getPotentialPassManagerType()) {
596 // Schedule analysis pass that is managed by a new manager.
597 schedulePass(AnalysisPass);
598 // Recheck analysis passes to ensure that required analysises that
599 // are already checked are still available.
600 checkAnalysis = true;
603 // Do not schedule this analysis. Lower level analsyis
604 // passes are run on the fly.
610 // Now all required passes are available.
614 /// Find the pass that implements Analysis AID. Search immutable
615 /// passes and all pass managers. If desired pass is not found
616 /// then return NULL.
617 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
620 // Check pass managers
621 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
622 E = PassManagers.end(); P == NULL && I != E; ++I) {
623 PMDataManager *PMD = *I;
624 P = PMD->findAnalysisPass(AID, false);
627 // Check other pass managers
628 for (SmallVector<PMDataManager *, 8>::iterator
629 I = IndirectPassManagers.begin(),
630 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
631 P = (*I)->findAnalysisPass(AID, false);
633 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
634 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
635 const PassInfo *PI = (*I)->getPassInfo();
639 // If Pass not found then check the interfaces implemented by Immutable Pass
641 const std::vector<const PassInfo*> &ImmPI =
642 PI->getInterfacesImplemented();
643 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
651 // Print passes managed by this top level manager.
652 void PMTopLevelManager::dumpPasses() const {
654 if (PassDebugging < Structure)
657 // Print out the immutable passes
658 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
659 ImmutablePasses[i]->dumpPassStructure(0);
662 // Every class that derives from PMDataManager also derives from Pass
663 // (sometimes indirectly), but there's no inheritance relationship
664 // between PMDataManager and Pass, so we have to getAsPass to get
665 // from a PMDataManager* to a Pass*.
666 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
667 E = PassManagers.end(); I != E; ++I)
668 (*I)->getAsPass()->dumpPassStructure(1);
671 void PMTopLevelManager::dumpArguments() const {
673 if (PassDebugging < Arguments)
676 dbgs() << "Pass Arguments: ";
677 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
678 E = PassManagers.end(); I != E; ++I)
679 (*I)->dumpPassArguments();
683 void PMTopLevelManager::initializeAllAnalysisInfo() {
684 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
685 E = PassManagers.end(); I != E; ++I)
686 (*I)->initializeAnalysisInfo();
688 // Initailize other pass managers
689 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
690 E = IndirectPassManagers.end(); I != E; ++I)
691 (*I)->initializeAnalysisInfo();
693 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
694 DME = LastUser.end(); DMI != DME; ++DMI) {
695 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
696 InversedLastUser.find(DMI->second);
697 if (InvDMI != InversedLastUser.end()) {
698 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
699 L.insert(DMI->first);
701 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
702 InversedLastUser[DMI->second] = L;
708 PMTopLevelManager::~PMTopLevelManager() {
709 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
710 E = PassManagers.end(); I != E; ++I)
713 for (SmallVector<ImmutablePass *, 8>::iterator
714 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
717 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
718 DME = AnUsageMap.end(); DMI != DME; ++DMI)
722 //===----------------------------------------------------------------------===//
723 // PMDataManager implementation
725 /// Augement AvailableAnalysis by adding analysis made available by pass P.
726 void PMDataManager::recordAvailableAnalysis(Pass *P) {
727 const PassInfo *PI = P->getPassInfo();
730 AvailableAnalysis[PI] = P;
732 //This pass is the current implementation of all of the interfaces it
733 //implements as well.
734 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
735 for (unsigned i = 0, e = II.size(); i != e; ++i)
736 AvailableAnalysis[II[i]] = P;
739 // Return true if P preserves high level analysis used by other
740 // passes managed by this manager
741 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
742 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
743 if (AnUsage->getPreservesAll())
746 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
747 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
748 E = HigherLevelAnalysis.end(); I != E; ++I) {
750 if (P1->getAsImmutablePass() == 0 &&
751 std::find(PreservedSet.begin(), PreservedSet.end(),
752 P1->getPassInfo()) ==
760 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
761 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
762 // Don't do this unless assertions are enabled.
766 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
767 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
769 // Verify preserved analysis
770 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
771 E = PreservedSet.end(); I != E; ++I) {
773 if (Pass *AP = findAnalysisPass(AID, true)) {
774 TimeRegion PassTimer(getPassTimer(AP));
775 AP->verifyAnalysis();
780 /// Remove Analysis not preserved by Pass P
781 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
782 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
783 if (AnUsage->getPreservesAll())
786 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
787 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
788 E = AvailableAnalysis.end(); I != E; ) {
789 std::map<AnalysisID, Pass*>::iterator Info = I++;
790 if (Info->second->getAsImmutablePass() == 0 &&
791 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
792 PreservedSet.end()) {
793 // Remove this analysis
794 if (PassDebugging >= Details) {
795 Pass *S = Info->second;
796 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
797 dbgs() << S->getPassName() << "'\n";
799 AvailableAnalysis.erase(Info);
803 // Check inherited analysis also. If P is not preserving analysis
804 // provided by parent manager then remove it here.
805 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
807 if (!InheritedAnalysis[Index])
810 for (std::map<AnalysisID, Pass*>::iterator
811 I = InheritedAnalysis[Index]->begin(),
812 E = InheritedAnalysis[Index]->end(); I != E; ) {
813 std::map<AnalysisID, Pass *>::iterator Info = I++;
814 if (Info->second->getAsImmutablePass() == 0 &&
815 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
816 PreservedSet.end()) {
817 // Remove this analysis
818 if (PassDebugging >= Details) {
819 Pass *S = Info->second;
820 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
821 dbgs() << S->getPassName() << "'\n";
823 InheritedAnalysis[Index]->erase(Info);
829 /// Remove analysis passes that are not used any longer
830 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
831 enum PassDebuggingString DBG_STR) {
833 SmallVector<Pass *, 12> DeadPasses;
835 // If this is a on the fly manager then it does not have TPM.
839 TPM->collectLastUses(DeadPasses, P);
841 if (PassDebugging >= Details && !DeadPasses.empty()) {
842 dbgs() << " -*- '" << P->getPassName();
843 dbgs() << "' is the last user of following pass instances.";
844 dbgs() << " Free these instances\n";
847 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
848 E = DeadPasses.end(); I != E; ++I)
849 freePass(*I, Msg, DBG_STR);
852 void PMDataManager::freePass(Pass *P, StringRef Msg,
853 enum PassDebuggingString DBG_STR) {
854 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
857 // If the pass crashes releasing memory, remember this.
858 PassManagerPrettyStackEntry X(P);
859 TimeRegion PassTimer(getPassTimer(P));
864 if (const PassInfo *PI = P->getPassInfo()) {
865 // Remove the pass itself (if it is not already removed).
866 AvailableAnalysis.erase(PI);
868 // Remove all interfaces this pass implements, for which it is also
869 // listed as the available implementation.
870 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
871 for (unsigned i = 0, e = II.size(); i != e; ++i) {
872 std::map<AnalysisID, Pass*>::iterator Pos =
873 AvailableAnalysis.find(II[i]);
874 if (Pos != AvailableAnalysis.end() && Pos->second == P)
875 AvailableAnalysis.erase(Pos);
880 /// Add pass P into the PassVector. Update
881 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
882 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
883 // This manager is going to manage pass P. Set up analysis resolver
885 AnalysisResolver *AR = new AnalysisResolver(*this);
888 // If a FunctionPass F is the last user of ModulePass info M
889 // then the F's manager, not F, records itself as a last user of M.
890 SmallVector<Pass *, 12> TransferLastUses;
892 if (!ProcessAnalysis) {
894 PassVector.push_back(P);
898 // At the moment, this pass is the last user of all required passes.
899 SmallVector<Pass *, 12> LastUses;
900 SmallVector<Pass *, 8> RequiredPasses;
901 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
903 unsigned PDepth = this->getDepth();
905 collectRequiredAnalysis(RequiredPasses,
906 ReqAnalysisNotAvailable, P);
907 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
908 E = RequiredPasses.end(); I != E; ++I) {
909 Pass *PRequired = *I;
912 assert(PRequired->getResolver() && "Analysis Resolver is not set");
913 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
914 RDepth = DM.getDepth();
916 if (PDepth == RDepth)
917 LastUses.push_back(PRequired);
918 else if (PDepth > RDepth) {
919 // Let the parent claim responsibility of last use
920 TransferLastUses.push_back(PRequired);
921 // Keep track of higher level analysis used by this manager.
922 HigherLevelAnalysis.push_back(PRequired);
924 llvm_unreachable("Unable to accomodate Required Pass");
927 // Set P as P's last user until someone starts using P.
928 // However, if P is a Pass Manager then it does not need
929 // to record its last user.
930 if (P->getAsPMDataManager() == 0)
931 LastUses.push_back(P);
932 TPM->setLastUser(LastUses, P);
934 if (!TransferLastUses.empty()) {
935 Pass *My_PM = getAsPass();
936 TPM->setLastUser(TransferLastUses, My_PM);
937 TransferLastUses.clear();
940 // Now, take care of required analysises that are not available.
941 for (SmallVector<AnalysisID, 8>::iterator
942 I = ReqAnalysisNotAvailable.begin(),
943 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
944 Pass *AnalysisPass = (*I)->createPass();
945 this->addLowerLevelRequiredPass(P, AnalysisPass);
948 // Take a note of analysis required and made available by this pass.
949 // Remove the analysis not preserved by this pass
950 removeNotPreservedAnalysis(P);
951 recordAvailableAnalysis(P);
954 PassVector.push_back(P);
958 /// Populate RP with analysis pass that are required by
959 /// pass P and are available. Populate RP_NotAvail with analysis
960 /// pass that are required by pass P but are not available.
961 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
962 SmallVector<AnalysisID, 8> &RP_NotAvail,
964 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
965 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
966 for (AnalysisUsage::VectorType::const_iterator
967 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
968 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
969 RP.push_back(AnalysisPass);
971 RP_NotAvail.push_back(*I);
974 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
975 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
976 E = IDs.end(); I != E; ++I) {
977 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
978 RP.push_back(AnalysisPass);
980 RP_NotAvail.push_back(*I);
984 // All Required analyses should be available to the pass as it runs! Here
985 // we fill in the AnalysisImpls member of the pass so that it can
986 // successfully use the getAnalysis() method to retrieve the
987 // implementations it needs.
989 void PMDataManager::initializeAnalysisImpl(Pass *P) {
990 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
992 for (AnalysisUsage::VectorType::const_iterator
993 I = AnUsage->getRequiredSet().begin(),
994 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
995 Pass *Impl = findAnalysisPass(*I, true);
997 // This may be analysis pass that is initialized on the fly.
998 // If that is not the case then it will raise an assert when it is used.
1000 AnalysisResolver *AR = P->getResolver();
1001 assert(AR && "Analysis Resolver is not set");
1002 AR->addAnalysisImplsPair(*I, Impl);
1006 /// Find the pass that implements Analysis AID. If desired pass is not found
1007 /// then return NULL.
1008 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1010 // Check if AvailableAnalysis map has one entry.
1011 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1013 if (I != AvailableAnalysis.end())
1016 // Search Parents through TopLevelManager
1018 return TPM->findAnalysisPass(AID);
1023 // Print list of passes that are last used by P.
1024 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1026 SmallVector<Pass *, 12> LUses;
1028 // If this is a on the fly manager then it does not have TPM.
1032 TPM->collectLastUses(LUses, P);
1034 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
1035 E = LUses.end(); I != E; ++I) {
1036 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1037 (*I)->dumpPassStructure(0);
1041 void PMDataManager::dumpPassArguments() const {
1042 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1043 E = PassVector.end(); I != E; ++I) {
1044 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1045 PMD->dumpPassArguments();
1047 if (const PassInfo *PI = (*I)->getPassInfo())
1048 if (!PI->isAnalysisGroup())
1049 dbgs() << " -" << PI->getPassArgument();
1053 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1054 enum PassDebuggingString S2,
1056 if (PassDebugging < Executions)
1058 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1061 dbgs() << "Executing Pass '" << P->getPassName();
1063 case MODIFICATION_MSG:
1064 dbgs() << "Made Modification '" << P->getPassName();
1067 dbgs() << " Freeing Pass '" << P->getPassName();
1073 case ON_BASICBLOCK_MSG:
1074 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1076 case ON_FUNCTION_MSG:
1077 dbgs() << "' on Function '" << Msg << "'...\n";
1080 dbgs() << "' on Module '" << Msg << "'...\n";
1083 dbgs() << "' on Loop '" << Msg << "'...\n";
1086 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1093 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1094 if (PassDebugging < Details)
1097 AnalysisUsage analysisUsage;
1098 P->getAnalysisUsage(analysisUsage);
1099 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1102 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1103 if (PassDebugging < Details)
1106 AnalysisUsage analysisUsage;
1107 P->getAnalysisUsage(analysisUsage);
1108 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1111 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1112 const AnalysisUsage::VectorType &Set) const {
1113 assert(PassDebugging >= Details);
1116 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1117 for (unsigned i = 0; i != Set.size(); ++i) {
1118 if (i) dbgs() << ',';
1119 dbgs() << ' ' << Set[i]->getPassName();
1124 /// Add RequiredPass into list of lower level passes required by pass P.
1125 /// RequiredPass is run on the fly by Pass Manager when P requests it
1126 /// through getAnalysis interface.
1127 /// This should be handled by specific pass manager.
1128 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1130 TPM->dumpArguments();
1134 // Module Level pass may required Function Level analysis info
1135 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1136 // to provide this on demand. In that case, in Pass manager terminology,
1137 // module level pass is requiring lower level analysis info managed by
1138 // lower level pass manager.
1140 // When Pass manager is not able to order required analysis info, Pass manager
1141 // checks whether any lower level manager will be able to provide this
1142 // analysis info on demand or not.
1144 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1145 dbgs() << "' required by '" << P->getPassName() << "'\n";
1147 llvm_unreachable("Unable to schedule pass");
1150 Pass *PMDataManager::getOnTheFlyPass(Pass *P, const PassInfo *PI, Function &F) {
1151 assert(0 && "Unable to find on the fly pass");
1156 PMDataManager::~PMDataManager() {
1157 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1158 E = PassVector.end(); I != E; ++I)
1162 //===----------------------------------------------------------------------===//
1163 // NOTE: Is this the right place to define this method ?
1164 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1165 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1166 return PM.findAnalysisPass(ID, dir);
1169 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1171 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1174 //===----------------------------------------------------------------------===//
1175 // BBPassManager implementation
1177 /// Execute all of the passes scheduled for execution by invoking
1178 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1179 /// the function, and if so, return true.
1180 bool BBPassManager::runOnFunction(Function &F) {
1181 if (F.isDeclaration())
1184 bool Changed = doInitialization(F);
1186 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1187 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1188 BasicBlockPass *BP = getContainedPass(Index);
1189 bool LocalChanged = false;
1191 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1192 dumpRequiredSet(BP);
1194 initializeAnalysisImpl(BP);
1197 // If the pass crashes, remember this.
1198 PassManagerPrettyStackEntry X(BP, *I);
1199 TimeRegion PassTimer(getPassTimer(BP));
1201 LocalChanged |= BP->runOnBasicBlock(*I);
1204 Changed |= LocalChanged;
1206 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1208 dumpPreservedSet(BP);
1210 verifyPreservedAnalysis(BP);
1211 removeNotPreservedAnalysis(BP);
1212 recordAvailableAnalysis(BP);
1213 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1216 return doFinalization(F) || Changed;
1219 // Implement doInitialization and doFinalization
1220 bool BBPassManager::doInitialization(Module &M) {
1221 bool Changed = false;
1223 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1224 Changed |= getContainedPass(Index)->doInitialization(M);
1229 bool BBPassManager::doFinalization(Module &M) {
1230 bool Changed = false;
1232 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1233 Changed |= getContainedPass(Index)->doFinalization(M);
1238 bool BBPassManager::doInitialization(Function &F) {
1239 bool Changed = false;
1241 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1242 BasicBlockPass *BP = getContainedPass(Index);
1243 Changed |= BP->doInitialization(F);
1249 bool BBPassManager::doFinalization(Function &F) {
1250 bool Changed = false;
1252 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1253 BasicBlockPass *BP = getContainedPass(Index);
1254 Changed |= BP->doFinalization(F);
1261 //===----------------------------------------------------------------------===//
1262 // FunctionPassManager implementation
1264 /// Create new Function pass manager
1265 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1266 FPM = new FunctionPassManagerImpl(0);
1267 // FPM is the top level manager.
1268 FPM->setTopLevelManager(FPM);
1270 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1271 FPM->setResolver(AR);
1274 FunctionPassManager::~FunctionPassManager() {
1278 /// addImpl - Add a pass to the queue of passes to run, without
1279 /// checking whether to add a printer pass.
1280 void FunctionPassManager::addImpl(Pass *P) {
1284 /// add - Add a pass to the queue of passes to run. This passes
1285 /// ownership of the Pass to the PassManager. When the
1286 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1287 /// there is no need to delete the pass. (TODO delete passes.)
1288 /// This implies that all passes MUST be allocated with 'new'.
1289 void FunctionPassManager::add(Pass *P) {
1290 // If this is a not a function pass, don't add a printer for it.
1291 if (P->getPassKind() == PT_Function)
1292 if (ShouldPrintBeforePass(P))
1293 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1294 + P->getPassName() + " ***"));
1298 if (P->getPassKind() == PT_Function)
1299 if (ShouldPrintAfterPass(P))
1300 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1301 + P->getPassName() + " ***"));
1304 /// run - Execute all of the passes scheduled for execution. Keep
1305 /// track of whether any of the passes modifies the function, and if
1306 /// so, return true.
1308 bool FunctionPassManager::run(Function &F) {
1309 if (F.isMaterializable()) {
1311 if (F.Materialize(&errstr))
1312 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1318 /// doInitialization - Run all of the initializers for the function passes.
1320 bool FunctionPassManager::doInitialization() {
1321 return FPM->doInitialization(*M);
1324 /// doFinalization - Run all of the finalizers for the function passes.
1326 bool FunctionPassManager::doFinalization() {
1327 return FPM->doFinalization(*M);
1330 //===----------------------------------------------------------------------===//
1331 // FunctionPassManagerImpl implementation
1333 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1334 bool Changed = false;
1339 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1340 Changed |= getContainedManager(Index)->doInitialization(M);
1345 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1346 bool Changed = false;
1348 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1349 Changed |= getContainedManager(Index)->doFinalization(M);
1354 /// cleanup - After running all passes, clean up pass manager cache.
1355 void FPPassManager::cleanup() {
1356 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1357 FunctionPass *FP = getContainedPass(Index);
1358 AnalysisResolver *AR = FP->getResolver();
1359 assert(AR && "Analysis Resolver is not set");
1360 AR->clearAnalysisImpls();
1364 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1367 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1368 FPPassManager *FPPM = getContainedManager(Index);
1369 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1370 FPPM->getContainedPass(Index)->releaseMemory();
1376 // Execute all the passes managed by this top level manager.
1377 // Return true if any function is modified by a pass.
1378 bool FunctionPassManagerImpl::run(Function &F) {
1379 bool Changed = false;
1380 TimingInfo::createTheTimeInfo();
1382 initializeAllAnalysisInfo();
1383 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1384 Changed |= getContainedManager(Index)->runOnFunction(F);
1386 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1387 getContainedManager(Index)->cleanup();
1393 //===----------------------------------------------------------------------===//
1394 // FPPassManager implementation
1396 char FPPassManager::ID = 0;
1397 /// Print passes managed by this manager
1398 void FPPassManager::dumpPassStructure(unsigned Offset) {
1399 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1400 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1401 FunctionPass *FP = getContainedPass(Index);
1402 FP->dumpPassStructure(Offset + 1);
1403 dumpLastUses(FP, Offset+1);
1408 /// Execute all of the passes scheduled for execution by invoking
1409 /// runOnFunction method. Keep track of whether any of the passes modifies
1410 /// the function, and if so, return true.
1411 bool FPPassManager::runOnFunction(Function &F) {
1412 if (F.isDeclaration())
1415 bool Changed = false;
1417 // Collect inherited analysis from Module level pass manager.
1418 populateInheritedAnalysis(TPM->activeStack);
1420 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1421 FunctionPass *FP = getContainedPass(Index);
1422 bool LocalChanged = false;
1424 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1425 dumpRequiredSet(FP);
1427 initializeAnalysisImpl(FP);
1430 PassManagerPrettyStackEntry X(FP, F);
1431 TimeRegion PassTimer(getPassTimer(FP));
1433 LocalChanged |= FP->runOnFunction(F);
1436 Changed |= LocalChanged;
1438 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1439 dumpPreservedSet(FP);
1441 verifyPreservedAnalysis(FP);
1442 removeNotPreservedAnalysis(FP);
1443 recordAvailableAnalysis(FP);
1444 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1449 bool FPPassManager::runOnModule(Module &M) {
1450 bool Changed = doInitialization(M);
1452 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1455 return doFinalization(M) || Changed;
1458 bool FPPassManager::doInitialization(Module &M) {
1459 bool Changed = false;
1461 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1462 Changed |= getContainedPass(Index)->doInitialization(M);
1467 bool FPPassManager::doFinalization(Module &M) {
1468 bool Changed = false;
1470 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1471 Changed |= getContainedPass(Index)->doFinalization(M);
1476 //===----------------------------------------------------------------------===//
1477 // MPPassManager implementation
1479 /// Execute all of the passes scheduled for execution by invoking
1480 /// runOnModule method. Keep track of whether any of the passes modifies
1481 /// the module, and if so, return true.
1483 MPPassManager::runOnModule(Module &M) {
1484 bool Changed = false;
1486 // Initialize on-the-fly passes
1487 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1488 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1490 FunctionPassManagerImpl *FPP = I->second;
1491 Changed |= FPP->doInitialization(M);
1494 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1495 ModulePass *MP = getContainedPass(Index);
1496 bool LocalChanged = false;
1498 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1499 dumpRequiredSet(MP);
1501 initializeAnalysisImpl(MP);
1504 PassManagerPrettyStackEntry X(MP, M);
1505 TimeRegion PassTimer(getPassTimer(MP));
1507 LocalChanged |= MP->runOnModule(M);
1510 Changed |= LocalChanged;
1512 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1513 M.getModuleIdentifier());
1514 dumpPreservedSet(MP);
1516 verifyPreservedAnalysis(MP);
1517 removeNotPreservedAnalysis(MP);
1518 recordAvailableAnalysis(MP);
1519 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1522 // Finalize on-the-fly passes
1523 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1524 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1526 FunctionPassManagerImpl *FPP = I->second;
1527 // We don't know when is the last time an on-the-fly pass is run,
1528 // so we need to releaseMemory / finalize here
1529 FPP->releaseMemoryOnTheFly();
1530 Changed |= FPP->doFinalization(M);
1535 /// Add RequiredPass into list of lower level passes required by pass P.
1536 /// RequiredPass is run on the fly by Pass Manager when P requests it
1537 /// through getAnalysis interface.
1538 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1539 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1540 "Unable to handle Pass that requires lower level Analysis pass");
1541 assert((P->getPotentialPassManagerType() <
1542 RequiredPass->getPotentialPassManagerType()) &&
1543 "Unable to handle Pass that requires lower level Analysis pass");
1545 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1547 FPP = new FunctionPassManagerImpl(0);
1548 // FPP is the top level manager.
1549 FPP->setTopLevelManager(FPP);
1551 OnTheFlyManagers[P] = FPP;
1553 FPP->add(RequiredPass);
1555 // Register P as the last user of RequiredPass.
1556 SmallVector<Pass *, 12> LU;
1557 LU.push_back(RequiredPass);
1558 FPP->setLastUser(LU, P);
1561 /// Return function pass corresponding to PassInfo PI, that is
1562 /// required by module pass MP. Instantiate analysis pass, by using
1563 /// its runOnFunction() for function F.
1564 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1565 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1566 assert(FPP && "Unable to find on the fly pass");
1568 FPP->releaseMemoryOnTheFly();
1570 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1574 //===----------------------------------------------------------------------===//
1575 // PassManagerImpl implementation
1577 /// run - Execute all of the passes scheduled for execution. Keep track of
1578 /// whether any of the passes modifies the module, and if so, return true.
1579 bool PassManagerImpl::run(Module &M) {
1580 bool Changed = false;
1581 TimingInfo::createTheTimeInfo();
1586 initializeAllAnalysisInfo();
1587 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1588 Changed |= getContainedManager(Index)->runOnModule(M);
1592 //===----------------------------------------------------------------------===//
1593 // PassManager implementation
1595 /// Create new pass manager
1596 PassManager::PassManager() {
1597 PM = new PassManagerImpl(0);
1598 // PM is the top level manager
1599 PM->setTopLevelManager(PM);
1602 PassManager::~PassManager() {
1606 /// addImpl - Add a pass to the queue of passes to run, without
1607 /// checking whether to add a printer pass.
1608 void PassManager::addImpl(Pass *P) {
1612 /// add - Add a pass to the queue of passes to run. This passes ownership of
1613 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1614 /// will be destroyed as well, so there is no need to delete the pass. This
1615 /// implies that all passes MUST be allocated with 'new'.
1616 void PassManager::add(Pass *P) {
1617 if (ShouldPrintBeforePass(P))
1618 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1619 + P->getPassName() + " ***"));
1623 if (ShouldPrintAfterPass(P))
1624 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1625 + P->getPassName() + " ***"));
1628 /// run - Execute all of the passes scheduled for execution. Keep track of
1629 /// whether any of the passes modifies the module, and if so, return true.
1630 bool PassManager::run(Module &M) {
1634 //===----------------------------------------------------------------------===//
1635 // TimingInfo Class - This class is used to calculate information about the
1636 // amount of time each pass takes to execute. This only happens with
1637 // -time-passes is enabled on the command line.
1639 bool llvm::TimePassesIsEnabled = false;
1640 static cl::opt<bool,true>
1641 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1642 cl::desc("Time each pass, printing elapsed time for each on exit"));
1644 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1645 // a non null value (if the -time-passes option is enabled) or it leaves it
1646 // null. It may be called multiple times.
1647 void TimingInfo::createTheTimeInfo() {
1648 if (!TimePassesIsEnabled || TheTimeInfo) return;
1650 // Constructed the first time this is called, iff -time-passes is enabled.
1651 // This guarantees that the object will be constructed before static globals,
1652 // thus it will be destroyed before them.
1653 static ManagedStatic<TimingInfo> TTI;
1654 TheTimeInfo = &*TTI;
1657 /// If TimingInfo is enabled then start pass timer.
1658 Timer *llvm::getPassTimer(Pass *P) {
1660 return TheTimeInfo->getPassTimer(P);
1664 //===----------------------------------------------------------------------===//
1665 // PMStack implementation
1668 // Pop Pass Manager from the stack and clear its analysis info.
1669 void PMStack::pop() {
1671 PMDataManager *Top = this->top();
1672 Top->initializeAnalysisInfo();
1677 // Push PM on the stack and set its top level manager.
1678 void PMStack::push(PMDataManager *PM) {
1679 assert(PM && "Unable to push. Pass Manager expected");
1681 if (!this->empty()) {
1682 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1684 assert(TPM && "Unable to find top level manager");
1685 TPM->addIndirectPassManager(PM);
1686 PM->setTopLevelManager(TPM);
1692 // Dump content of the pass manager stack.
1693 void PMStack::dump() {
1694 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1695 E = S.end(); I != E; ++I)
1696 printf("%s ", (*I)->getAsPass()->getPassName());
1702 /// Find appropriate Module Pass Manager in the PM Stack and
1703 /// add self into that manager.
1704 void ModulePass::assignPassManager(PMStack &PMS,
1705 PassManagerType PreferredType) {
1706 // Find Module Pass Manager
1707 while(!PMS.empty()) {
1708 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1709 if (TopPMType == PreferredType)
1710 break; // We found desired pass manager
1711 else if (TopPMType > PMT_ModulePassManager)
1712 PMS.pop(); // Pop children pass managers
1716 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1717 PMS.top()->add(this);
1720 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1721 /// in the PM Stack and add self into that manager.
1722 void FunctionPass::assignPassManager(PMStack &PMS,
1723 PassManagerType PreferredType) {
1725 // Find Module Pass Manager
1726 while (!PMS.empty()) {
1727 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1733 // Create new Function Pass Manager if needed.
1735 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1736 FPP = (FPPassManager *)PMS.top();
1738 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1739 PMDataManager *PMD = PMS.top();
1741 // [1] Create new Function Pass Manager
1742 FPP = new FPPassManager(PMD->getDepth() + 1);
1743 FPP->populateInheritedAnalysis(PMS);
1745 // [2] Set up new manager's top level manager
1746 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1747 TPM->addIndirectPassManager(FPP);
1749 // [3] Assign manager to manage this new manager. This may create
1750 // and push new managers into PMS
1751 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1753 // [4] Push new manager into PMS
1757 // Assign FPP as the manager of this pass.
1761 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1762 /// in the PM Stack and add self into that manager.
1763 void BasicBlockPass::assignPassManager(PMStack &PMS,
1764 PassManagerType PreferredType) {
1767 // Basic Pass Manager is a leaf pass manager. It does not handle
1768 // any other pass manager.
1770 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1771 BBP = (BBPassManager *)PMS.top();
1773 // If leaf manager is not Basic Block Pass manager then create new
1774 // basic Block Pass manager.
1775 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1776 PMDataManager *PMD = PMS.top();
1778 // [1] Create new Basic Block Manager
1779 BBP = new BBPassManager(PMD->getDepth() + 1);
1781 // [2] Set up new manager's top level manager
1782 // Basic Block Pass Manager does not live by itself
1783 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1784 TPM->addIndirectPassManager(BBP);
1786 // [3] Assign manager to manage this new manager. This may create
1787 // and push new managers into PMS
1788 BBP->assignPassManager(PMS, PreferredType);
1790 // [4] Push new manager into PMS
1794 // Assign BBP as the manager of this pass.
1798 PassManagerBase::~PassManagerBase() {}
1800 /*===-- C Bindings --------------------------------------------------------===*/
1802 LLVMPassManagerRef LLVMCreatePassManager() {
1803 return wrap(new PassManager());
1806 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
1807 return wrap(new FunctionPassManager(unwrap(M)));
1810 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1811 return LLVMCreateFunctionPassManagerForModule(
1812 reinterpret_cast<LLVMModuleRef>(P));
1815 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1816 return unwrap<PassManager>(PM)->run(*unwrap(M));
1819 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1820 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1823 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1824 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1827 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1828 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1831 void LLVMDisposePassManager(LLVMPassManagerRef PM) {