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/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm-c/Core.h"
30 // See PassManagers.h for Pass Manager infrastructure overview.
34 //===----------------------------------------------------------------------===//
35 // Pass debugging information. Often it is useful to find out what pass is
36 // running when a crash occurs in a utility. When this library is compiled with
37 // debugging on, a command line option (--debug-pass) is enabled that causes the
38 // pass name to be printed before it executes.
41 // Different debug levels that can be enabled...
43 None
, Arguments
, Structure
, Executions
, Details
46 bool VerifyDomInfo
= false;
47 static cl::opt
<bool,true>
48 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo
),
49 cl::desc("Verify dominator info (time consuming)"));
51 static cl::opt
<enum PassDebugLevel
>
52 PassDebugging("debug-pass", cl::Hidden
,
53 cl::desc("Print PassManager debugging information"),
55 clEnumVal(None
, "disable debug output"),
56 clEnumVal(Arguments
, "print pass arguments to pass to 'opt'"),
57 clEnumVal(Structure
, "print pass structure before run()"),
58 clEnumVal(Executions
, "print pass name before it is executed"),
59 clEnumVal(Details
, "print pass details when it is executed"),
61 } // End of llvm namespace
63 void PassManagerPrettyStackEntry::print(raw_ostream
&OS
) const {
65 OS
<< "Releasing pass '";
67 OS
<< "Running pass '";
69 OS
<< P
->getPassName() << "'";
72 OS
<< " on module '" << M
->getModuleIdentifier() << "'.\n";
83 else if (isa
<BasicBlock
>(V
))
89 WriteAsOperand(OS
, V
, /*PrintTy=*/false, M
);
96 //===----------------------------------------------------------------------===//
99 /// BBPassManager manages BasicBlockPass. It batches all the
100 /// pass together and sequence them to process one basic block before
101 /// processing next basic block.
102 class VISIBILITY_HIDDEN BBPassManager
: public PMDataManager
,
103 public FunctionPass
{
107 explicit BBPassManager(int Depth
)
108 : PMDataManager(Depth
), FunctionPass(&ID
) {}
110 /// Execute all of the passes scheduled for execution. Keep track of
111 /// whether any of the passes modifies the function, and if so, return true.
112 bool runOnFunction(Function
&F
);
114 /// Pass Manager itself does not invalidate any analysis info.
115 void getAnalysisUsage(AnalysisUsage
&Info
) const {
116 Info
.setPreservesAll();
119 bool doInitialization(Module
&M
);
120 bool doInitialization(Function
&F
);
121 bool doFinalization(Module
&M
);
122 bool doFinalization(Function
&F
);
124 virtual const char *getPassName() const {
125 return "BasicBlock Pass Manager";
128 // Print passes managed by this manager
129 void dumpPassStructure(unsigned Offset
) {
130 llvm::cerr
<< std::string(Offset
*2, ' ') << "BasicBlockPass Manager\n";
131 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
132 BasicBlockPass
*BP
= getContainedPass(Index
);
133 BP
->dumpPassStructure(Offset
+ 1);
134 dumpLastUses(BP
, Offset
+1);
138 BasicBlockPass
*getContainedPass(unsigned N
) {
139 assert(N
< PassVector
.size() && "Pass number out of range!");
140 BasicBlockPass
*BP
= static_cast<BasicBlockPass
*>(PassVector
[N
]);
144 virtual PassManagerType
getPassManagerType() const {
145 return PMT_BasicBlockPassManager
;
149 char BBPassManager::ID
= 0;
154 //===----------------------------------------------------------------------===//
155 // FunctionPassManagerImpl
157 /// FunctionPassManagerImpl manages FPPassManagers
158 class FunctionPassManagerImpl
: public Pass
,
159 public PMDataManager
,
160 public PMTopLevelManager
{
163 explicit FunctionPassManagerImpl(int Depth
) :
164 Pass(&ID
), PMDataManager(Depth
),
165 PMTopLevelManager(TLM_Function
) { }
167 /// add - Add a pass to the queue of passes to run. This passes ownership of
168 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
169 /// will be destroyed as well, so there is no need to delete the pass. This
170 /// implies that all passes MUST be allocated with 'new'.
175 /// run - Execute all of the passes scheduled for execution. Keep track of
176 /// whether any of the passes modifies the module, and if so, return true.
177 bool run(Function
&F
);
179 /// doInitialization - Run all of the initializers for the function passes.
181 bool doInitialization(Module
&M
);
183 /// doFinalization - Run all of the finalizers for the function passes.
185 bool doFinalization(Module
&M
);
187 /// Pass Manager itself does not invalidate any analysis info.
188 void getAnalysisUsage(AnalysisUsage
&Info
) const {
189 Info
.setPreservesAll();
192 inline void addTopLevelPass(Pass
*P
) {
194 if (ImmutablePass
*IP
= dynamic_cast<ImmutablePass
*> (P
)) {
196 // P is a immutable pass and it will be managed by this
197 // top level manager. Set up analysis resolver to connect them.
198 AnalysisResolver
*AR
= new AnalysisResolver(*this);
200 initializeAnalysisImpl(P
);
201 addImmutablePass(IP
);
202 recordAvailableAnalysis(IP
);
204 P
->assignPassManager(activeStack
);
209 FPPassManager
*getContainedManager(unsigned N
) {
210 assert(N
< PassManagers
.size() && "Pass number out of range!");
211 FPPassManager
*FP
= static_cast<FPPassManager
*>(PassManagers
[N
]);
216 char FunctionPassManagerImpl::ID
= 0;
217 //===----------------------------------------------------------------------===//
220 /// MPPassManager manages ModulePasses and function pass managers.
221 /// It batches all Module passes and function pass managers together and
222 /// sequences them to process one module.
223 class MPPassManager
: public Pass
, public PMDataManager
{
226 explicit MPPassManager(int Depth
) :
227 Pass(&ID
), PMDataManager(Depth
) { }
229 // Delete on the fly managers.
230 virtual ~MPPassManager() {
231 for (std::map
<Pass
*, FunctionPassManagerImpl
*>::iterator
232 I
= OnTheFlyManagers
.begin(), E
= OnTheFlyManagers
.end();
234 FunctionPassManagerImpl
*FPP
= I
->second
;
239 /// run - Execute all of the passes scheduled for execution. Keep track of
240 /// whether any of the passes modifies the module, and if so, return true.
241 bool runOnModule(Module
&M
);
243 /// Pass Manager itself does not invalidate any analysis info.
244 void getAnalysisUsage(AnalysisUsage
&Info
) const {
245 Info
.setPreservesAll();
248 /// Add RequiredPass into list of lower level passes required by pass P.
249 /// RequiredPass is run on the fly by Pass Manager when P requests it
250 /// through getAnalysis interface.
251 virtual void addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
);
253 /// Return function pass corresponding to PassInfo PI, that is
254 /// required by module pass MP. Instantiate analysis pass, by using
255 /// its runOnFunction() for function F.
256 virtual Pass
* getOnTheFlyPass(Pass
*MP
, const PassInfo
*PI
, Function
&F
);
258 virtual const char *getPassName() const {
259 return "Module Pass Manager";
262 // Print passes managed by this manager
263 void dumpPassStructure(unsigned Offset
) {
264 llvm::cerr
<< std::string(Offset
*2, ' ') << "ModulePass Manager\n";
265 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
266 ModulePass
*MP
= getContainedPass(Index
);
267 MP
->dumpPassStructure(Offset
+ 1);
268 if (FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[MP
])
269 FPP
->dumpPassStructure(Offset
+ 2);
270 dumpLastUses(MP
, Offset
+1);
274 ModulePass
*getContainedPass(unsigned N
) {
275 assert(N
< PassVector
.size() && "Pass number out of range!");
276 return static_cast<ModulePass
*>(PassVector
[N
]);
279 virtual PassManagerType
getPassManagerType() const {
280 return PMT_ModulePassManager
;
284 /// Collection of on the fly FPPassManagers. These managers manage
285 /// function passes that are required by module passes.
286 std::map
<Pass
*, FunctionPassManagerImpl
*> OnTheFlyManagers
;
289 char MPPassManager::ID
= 0;
290 //===----------------------------------------------------------------------===//
294 /// PassManagerImpl manages MPPassManagers
295 class PassManagerImpl
: public Pass
,
296 public PMDataManager
,
297 public PMTopLevelManager
{
301 explicit PassManagerImpl(int Depth
) :
302 Pass(&ID
), PMDataManager(Depth
), PMTopLevelManager(TLM_Pass
) { }
304 /// add - Add a pass to the queue of passes to run. This passes ownership of
305 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
306 /// will be destroyed as well, so there is no need to delete the pass. This
307 /// implies that all passes MUST be allocated with 'new'.
312 /// run - Execute all of the passes scheduled for execution. Keep track of
313 /// whether any of the passes modifies the module, and if so, return true.
316 /// Pass Manager itself does not invalidate any analysis info.
317 void getAnalysisUsage(AnalysisUsage
&Info
) const {
318 Info
.setPreservesAll();
321 inline void addTopLevelPass(Pass
*P
) {
322 if (ImmutablePass
*IP
= dynamic_cast<ImmutablePass
*> (P
)) {
324 // P is a immutable pass and it will be managed by this
325 // top level manager. Set up analysis resolver to connect them.
326 AnalysisResolver
*AR
= new AnalysisResolver(*this);
328 initializeAnalysisImpl(P
);
329 addImmutablePass(IP
);
330 recordAvailableAnalysis(IP
);
332 P
->assignPassManager(activeStack
);
336 MPPassManager
*getContainedManager(unsigned N
) {
337 assert(N
< PassManagers
.size() && "Pass number out of range!");
338 MPPassManager
*MP
= static_cast<MPPassManager
*>(PassManagers
[N
]);
343 char PassManagerImpl::ID
= 0;
344 } // End of llvm namespace
348 //===----------------------------------------------------------------------===//
349 /// TimingInfo Class - This class is used to calculate information about the
350 /// amount of time each pass takes to execute. This only happens when
351 /// -time-passes is enabled on the command line.
353 class VISIBILITY_HIDDEN TimingInfo
{
354 std::map
<Pass
*, Timer
> TimingData
;
358 // Use 'create' member to get this.
359 TimingInfo() : TG("... Pass execution timing report ...") {}
361 // TimingDtor - Print out information about timing information
363 // Delete all of the timers...
365 // TimerGroup is deleted next, printing the report.
368 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
369 // to a non null value (if the -time-passes option is enabled) or it leaves it
370 // null. It may be called multiple times.
371 static void createTheTimeInfo();
373 void passStarted(Pass
*P
) {
374 if (dynamic_cast<PMDataManager
*>(P
))
377 std::map
<Pass
*, Timer
>::iterator I
= TimingData
.find(P
);
378 if (I
== TimingData
.end())
379 I
=TimingData
.insert(std::make_pair(P
, Timer(P
->getPassName(), TG
))).first
;
380 I
->second
.startTimer();
382 void passEnded(Pass
*P
) {
383 if (dynamic_cast<PMDataManager
*>(P
))
386 std::map
<Pass
*, Timer
>::iterator I
= TimingData
.find(P
);
387 assert(I
!= TimingData
.end() && "passStarted/passEnded not nested right!");
388 I
->second
.stopTimer();
392 } // End of anon namespace
394 static TimingInfo
*TheTimeInfo
;
396 //===----------------------------------------------------------------------===//
397 // PMTopLevelManager implementation
399 /// Initialize top level manager. Create first pass manager.
400 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t
) {
402 MPPassManager
*MPP
= new MPPassManager(1);
403 MPP
->setTopLevelManager(this);
405 activeStack
.push(MPP
);
406 } else if (t
== TLM_Function
) {
407 FPPassManager
*FPP
= new FPPassManager(1);
408 FPP
->setTopLevelManager(this);
410 activeStack
.push(FPP
);
414 /// Set pass P as the last user of the given analysis passes.
415 void PMTopLevelManager::setLastUser(SmallVector
<Pass
*, 12> &AnalysisPasses
,
417 for (SmallVector
<Pass
*, 12>::iterator I
= AnalysisPasses
.begin(),
418 E
= AnalysisPasses
.end(); I
!= E
; ++I
) {
425 // If AP is the last user of other passes then make P last user of
427 for (DenseMap
<Pass
*, Pass
*>::iterator LUI
= LastUser
.begin(),
428 LUE
= LastUser
.end(); LUI
!= LUE
; ++LUI
) {
429 if (LUI
->second
== AP
)
430 // DenseMap iterator is not invalidated here because
431 // this is just updating exisitng entry.
432 LastUser
[LUI
->first
] = P
;
437 /// Collect passes whose last user is P
438 void PMTopLevelManager::collectLastUses(SmallVector
<Pass
*, 12> &LastUses
,
440 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> >::iterator DMI
=
441 InversedLastUser
.find(P
);
442 if (DMI
== InversedLastUser
.end())
445 SmallPtrSet
<Pass
*, 8> &LU
= DMI
->second
;
446 for (SmallPtrSet
<Pass
*, 8>::iterator I
= LU
.begin(),
447 E
= LU
.end(); I
!= E
; ++I
) {
448 LastUses
.push_back(*I
);
453 AnalysisUsage
*PMTopLevelManager::findAnalysisUsage(Pass
*P
) {
454 AnalysisUsage
*AnUsage
= NULL
;
455 DenseMap
<Pass
*, AnalysisUsage
*>::iterator DMI
= AnUsageMap
.find(P
);
456 if (DMI
!= AnUsageMap
.end())
457 AnUsage
= DMI
->second
;
459 AnUsage
= new AnalysisUsage();
460 P
->getAnalysisUsage(*AnUsage
);
461 AnUsageMap
[P
] = AnUsage
;
466 /// Schedule pass P for execution. Make sure that passes required by
467 /// P are run before P is run. Update analysis info maintained by
468 /// the manager. Remove dead passes. This is a recursive function.
469 void PMTopLevelManager::schedulePass(Pass
*P
) {
471 // TODO : Allocate function manager for this pass, other wise required set
472 // may be inserted into previous function manager
474 // Give pass a chance to prepare the stage.
475 P
->preparePassManager(activeStack
);
477 // If P is an analysis pass and it is available then do not
478 // generate the analysis again. Stale analysis info should not be
479 // available at this point.
480 if (P
->getPassInfo() &&
481 P
->getPassInfo()->isAnalysis() && findAnalysisPass(P
->getPassInfo())) {
486 AnalysisUsage
*AnUsage
= findAnalysisUsage(P
);
488 bool checkAnalysis
= true;
489 while (checkAnalysis
) {
490 checkAnalysis
= false;
492 const AnalysisUsage::VectorType
&RequiredSet
= AnUsage
->getRequiredSet();
493 for (AnalysisUsage::VectorType::const_iterator I
= RequiredSet
.begin(),
494 E
= RequiredSet
.end(); I
!= E
; ++I
) {
496 Pass
*AnalysisPass
= findAnalysisPass(*I
);
498 AnalysisPass
= (*I
)->createPass();
499 if (P
->getPotentialPassManagerType () ==
500 AnalysisPass
->getPotentialPassManagerType())
501 // Schedule analysis pass that is managed by the same pass manager.
502 schedulePass(AnalysisPass
);
503 else if (P
->getPotentialPassManagerType () >
504 AnalysisPass
->getPotentialPassManagerType()) {
505 // Schedule analysis pass that is managed by a new manager.
506 schedulePass(AnalysisPass
);
507 // Recheck analysis passes to ensure that required analysises that
508 // are already checked are still available.
509 checkAnalysis
= true;
512 // Do not schedule this analysis. Lower level analsyis
513 // passes are run on the fly.
519 // Now all required passes are available.
523 /// Find the pass that implements Analysis AID. Search immutable
524 /// passes and all pass managers. If desired pass is not found
525 /// then return NULL.
526 Pass
*PMTopLevelManager::findAnalysisPass(AnalysisID AID
) {
529 // Check pass managers
530 for (SmallVector
<PMDataManager
*, 8>::iterator I
= PassManagers
.begin(),
531 E
= PassManagers
.end(); P
== NULL
&& I
!= E
; ++I
) {
532 PMDataManager
*PMD
= *I
;
533 P
= PMD
->findAnalysisPass(AID
, false);
536 // Check other pass managers
537 for (SmallVector
<PMDataManager
*, 8>::iterator
538 I
= IndirectPassManagers
.begin(),
539 E
= IndirectPassManagers
.end(); P
== NULL
&& I
!= E
; ++I
)
540 P
= (*I
)->findAnalysisPass(AID
, false);
542 for (SmallVector
<ImmutablePass
*, 8>::iterator I
= ImmutablePasses
.begin(),
543 E
= ImmutablePasses
.end(); P
== NULL
&& I
!= E
; ++I
) {
544 const PassInfo
*PI
= (*I
)->getPassInfo();
548 // If Pass not found then check the interfaces implemented by Immutable Pass
550 const std::vector
<const PassInfo
*> &ImmPI
=
551 PI
->getInterfacesImplemented();
552 if (std::find(ImmPI
.begin(), ImmPI
.end(), AID
) != ImmPI
.end())
560 // Print passes managed by this top level manager.
561 void PMTopLevelManager::dumpPasses() const {
563 if (PassDebugging
< Structure
)
566 // Print out the immutable passes
567 for (unsigned i
= 0, e
= ImmutablePasses
.size(); i
!= e
; ++i
) {
568 ImmutablePasses
[i
]->dumpPassStructure(0);
571 // Every class that derives from PMDataManager also derives from Pass
572 // (sometimes indirectly), but there's no inheritance relationship
573 // between PMDataManager and Pass, so we have to dynamic_cast to get
574 // from a PMDataManager* to a Pass*.
575 for (SmallVector
<PMDataManager
*, 8>::const_iterator I
= PassManagers
.begin(),
576 E
= PassManagers
.end(); I
!= E
; ++I
)
577 dynamic_cast<Pass
*>(*I
)->dumpPassStructure(1);
580 void PMTopLevelManager::dumpArguments() const {
582 if (PassDebugging
< Arguments
)
585 cerr
<< "Pass Arguments: ";
586 for (SmallVector
<PMDataManager
*, 8>::const_iterator I
= PassManagers
.begin(),
587 E
= PassManagers
.end(); I
!= E
; ++I
)
588 (*I
)->dumpPassArguments();
592 void PMTopLevelManager::initializeAllAnalysisInfo() {
593 for (SmallVector
<PMDataManager
*, 8>::iterator I
= PassManagers
.begin(),
594 E
= PassManagers
.end(); I
!= E
; ++I
)
595 (*I
)->initializeAnalysisInfo();
597 // Initailize other pass managers
598 for (SmallVector
<PMDataManager
*, 8>::iterator I
= IndirectPassManagers
.begin(),
599 E
= IndirectPassManagers
.end(); I
!= E
; ++I
)
600 (*I
)->initializeAnalysisInfo();
602 for (DenseMap
<Pass
*, Pass
*>::iterator DMI
= LastUser
.begin(),
603 DME
= LastUser
.end(); DMI
!= DME
; ++DMI
) {
604 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> >::iterator InvDMI
=
605 InversedLastUser
.find(DMI
->second
);
606 if (InvDMI
!= InversedLastUser
.end()) {
607 SmallPtrSet
<Pass
*, 8> &L
= InvDMI
->second
;
608 L
.insert(DMI
->first
);
610 SmallPtrSet
<Pass
*, 8> L
; L
.insert(DMI
->first
);
611 InversedLastUser
[DMI
->second
] = L
;
617 PMTopLevelManager::~PMTopLevelManager() {
618 for (SmallVector
<PMDataManager
*, 8>::iterator I
= PassManagers
.begin(),
619 E
= PassManagers
.end(); I
!= E
; ++I
)
622 for (SmallVector
<ImmutablePass
*, 8>::iterator
623 I
= ImmutablePasses
.begin(), E
= ImmutablePasses
.end(); I
!= E
; ++I
)
626 for (DenseMap
<Pass
*, AnalysisUsage
*>::iterator DMI
= AnUsageMap
.begin(),
627 DME
= AnUsageMap
.end(); DMI
!= DME
; ++DMI
)
631 //===----------------------------------------------------------------------===//
632 // PMDataManager implementation
634 /// Augement AvailableAnalysis by adding analysis made available by pass P.
635 void PMDataManager::recordAvailableAnalysis(Pass
*P
) {
636 const PassInfo
*PI
= P
->getPassInfo();
639 AvailableAnalysis
[PI
] = P
;
641 //This pass is the current implementation of all of the interfaces it
642 //implements as well.
643 const std::vector
<const PassInfo
*> &II
= PI
->getInterfacesImplemented();
644 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
)
645 AvailableAnalysis
[II
[i
]] = P
;
648 // Return true if P preserves high level analysis used by other
649 // passes managed by this manager
650 bool PMDataManager::preserveHigherLevelAnalysis(Pass
*P
) {
651 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
652 if (AnUsage
->getPreservesAll())
655 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
656 for (SmallVector
<Pass
*, 8>::iterator I
= HigherLevelAnalysis
.begin(),
657 E
= HigherLevelAnalysis
.end(); I
!= E
; ++I
) {
659 if (!dynamic_cast<ImmutablePass
*>(P1
) &&
660 std::find(PreservedSet
.begin(), PreservedSet
.end(),
661 P1
->getPassInfo()) ==
669 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
670 void PMDataManager::verifyPreservedAnalysis(Pass
*P
) {
671 // Don't do this unless assertions are enabled.
675 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
676 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
678 // Verify preserved analysis
679 for (AnalysisUsage::VectorType::const_iterator I
= PreservedSet
.begin(),
680 E
= PreservedSet
.end(); I
!= E
; ++I
) {
682 if (Pass
*AP
= findAnalysisPass(AID
, true))
683 AP
->verifyAnalysis();
687 /// verifyDomInfo - Verify dominator information if it is available.
688 void PMDataManager::verifyDomInfo(Pass
&P
, Function
&F
) {
689 if (!VerifyDomInfo
|| !P
.getResolver())
692 DominatorTree
*DT
= P
.getAnalysisIfAvailable
<DominatorTree
>();
696 DominatorTree OtherDT
;
697 OtherDT
.getBase().recalculate(F
);
698 if (DT
->compare(OtherDT
)) {
699 cerr
<< "Dominator Information for " << F
.getNameStart() << "\n";
700 cerr
<< "Pass '" << P
.getPassName() << "'\n";
701 cerr
<< "----- Valid -----\n";
703 cerr
<< "----- Invalid -----\n";
705 assert(0 && "Invalid dominator info");
708 DominanceFrontier
*DF
= P
.getAnalysisIfAvailable
<DominanceFrontier
>();
712 DominanceFrontier OtherDF
;
713 std::vector
<BasicBlock
*> DTRoots
= DT
->getRoots();
714 OtherDF
.calculate(*DT
, DT
->getNode(DTRoots
[0]));
715 if (DF
->compare(OtherDF
)) {
716 cerr
<< "Dominator Information for " << F
.getNameStart() << "\n";
717 cerr
<< "Pass '" << P
.getPassName() << "'\n";
718 cerr
<< "----- Valid -----\n";
720 cerr
<< "----- Invalid -----\n";
722 assert(0 && "Invalid dominator info");
726 /// Remove Analysis not preserved by Pass P
727 void PMDataManager::removeNotPreservedAnalysis(Pass
*P
) {
728 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
729 if (AnUsage
->getPreservesAll())
732 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
733 for (std::map
<AnalysisID
, Pass
*>::iterator I
= AvailableAnalysis
.begin(),
734 E
= AvailableAnalysis
.end(); I
!= E
; ) {
735 std::map
<AnalysisID
, Pass
*>::iterator Info
= I
++;
736 if (!dynamic_cast<ImmutablePass
*>(Info
->second
)
737 && std::find(PreservedSet
.begin(), PreservedSet
.end(), Info
->first
) ==
738 PreservedSet
.end()) {
739 // Remove this analysis
740 if (PassDebugging
>= Details
) {
741 Pass
*S
= Info
->second
;
742 cerr
<< " -- '" << P
->getPassName() << "' is not preserving '";
743 cerr
<< S
->getPassName() << "'\n";
745 AvailableAnalysis
.erase(Info
);
749 // Check inherited analysis also. If P is not preserving analysis
750 // provided by parent manager then remove it here.
751 for (unsigned Index
= 0; Index
< PMT_Last
; ++Index
) {
753 if (!InheritedAnalysis
[Index
])
756 for (std::map
<AnalysisID
, Pass
*>::iterator
757 I
= InheritedAnalysis
[Index
]->begin(),
758 E
= InheritedAnalysis
[Index
]->end(); I
!= E
; ) {
759 std::map
<AnalysisID
, Pass
*>::iterator Info
= I
++;
760 if (!dynamic_cast<ImmutablePass
*>(Info
->second
) &&
761 std::find(PreservedSet
.begin(), PreservedSet
.end(), Info
->first
) ==
763 // Remove this analysis
764 InheritedAnalysis
[Index
]->erase(Info
);
769 /// Remove analysis passes that are not used any longer
770 void PMDataManager::removeDeadPasses(Pass
*P
, const char *Msg
,
771 enum PassDebuggingString DBG_STR
) {
773 SmallVector
<Pass
*, 12> DeadPasses
;
775 // If this is a on the fly manager then it does not have TPM.
779 TPM
->collectLastUses(DeadPasses
, P
);
781 if (PassDebugging
>= Details
&& !DeadPasses
.empty()) {
782 cerr
<< " -*- '" << P
->getPassName();
783 cerr
<< "' is the last user of following pass instances.";
784 cerr
<< " Free these instances\n";
787 for (SmallVector
<Pass
*, 12>::iterator I
= DeadPasses
.begin(),
788 E
= DeadPasses
.end(); I
!= E
; ++I
) {
790 dumpPassInfo(*I
, FREEING_MSG
, DBG_STR
, Msg
);
793 // If the pass crashes releasing memory, remember this.
794 PassManagerPrettyStackEntry
X(*I
);
796 if (TheTimeInfo
) TheTimeInfo
->passStarted(*I
);
797 (*I
)->releaseMemory();
798 if (TheTimeInfo
) TheTimeInfo
->passEnded(*I
);
800 if (const PassInfo
*PI
= (*I
)->getPassInfo()) {
801 std::map
<AnalysisID
, Pass
*>::iterator Pos
=
802 AvailableAnalysis
.find(PI
);
804 // It is possible that pass is already removed from the AvailableAnalysis
805 if (Pos
!= AvailableAnalysis
.end())
806 AvailableAnalysis
.erase(Pos
);
808 // Remove all interfaces this pass implements, for which it is also
809 // listed as the available implementation.
810 const std::vector
<const PassInfo
*> &II
= PI
->getInterfacesImplemented();
811 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
) {
812 Pos
= AvailableAnalysis
.find(II
[i
]);
813 if (Pos
!= AvailableAnalysis
.end() && Pos
->second
== *I
)
814 AvailableAnalysis
.erase(Pos
);
820 /// Add pass P into the PassVector. Update
821 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
822 void PMDataManager::add(Pass
*P
, bool ProcessAnalysis
) {
823 // This manager is going to manage pass P. Set up analysis resolver
825 AnalysisResolver
*AR
= new AnalysisResolver(*this);
828 // If a FunctionPass F is the last user of ModulePass info M
829 // then the F's manager, not F, records itself as a last user of M.
830 SmallVector
<Pass
*, 12> TransferLastUses
;
832 if (!ProcessAnalysis
) {
834 PassVector
.push_back(P
);
838 // At the moment, this pass is the last user of all required passes.
839 SmallVector
<Pass
*, 12> LastUses
;
840 SmallVector
<Pass
*, 8> RequiredPasses
;
841 SmallVector
<AnalysisID
, 8> ReqAnalysisNotAvailable
;
843 unsigned PDepth
= this->getDepth();
845 collectRequiredAnalysis(RequiredPasses
,
846 ReqAnalysisNotAvailable
, P
);
847 for (SmallVector
<Pass
*, 8>::iterator I
= RequiredPasses
.begin(),
848 E
= RequiredPasses
.end(); I
!= E
; ++I
) {
849 Pass
*PRequired
= *I
;
852 assert(PRequired
->getResolver() && "Analysis Resolver is not set");
853 PMDataManager
&DM
= PRequired
->getResolver()->getPMDataManager();
854 RDepth
= DM
.getDepth();
856 if (PDepth
== RDepth
)
857 LastUses
.push_back(PRequired
);
858 else if (PDepth
> RDepth
) {
859 // Let the parent claim responsibility of last use
860 TransferLastUses
.push_back(PRequired
);
861 // Keep track of higher level analysis used by this manager.
862 HigherLevelAnalysis
.push_back(PRequired
);
864 assert(0 && "Unable to accomodate Required Pass");
867 // Set P as P's last user until someone starts using P.
868 // However, if P is a Pass Manager then it does not need
869 // to record its last user.
870 if (!dynamic_cast<PMDataManager
*>(P
))
871 LastUses
.push_back(P
);
872 TPM
->setLastUser(LastUses
, P
);
874 if (!TransferLastUses
.empty()) {
875 Pass
*My_PM
= dynamic_cast<Pass
*>(this);
876 TPM
->setLastUser(TransferLastUses
, My_PM
);
877 TransferLastUses
.clear();
880 // Now, take care of required analysises that are not available.
881 for (SmallVector
<AnalysisID
, 8>::iterator
882 I
= ReqAnalysisNotAvailable
.begin(),
883 E
= ReqAnalysisNotAvailable
.end() ;I
!= E
; ++I
) {
884 Pass
*AnalysisPass
= (*I
)->createPass();
885 this->addLowerLevelRequiredPass(P
, AnalysisPass
);
888 // Take a note of analysis required and made available by this pass.
889 // Remove the analysis not preserved by this pass
890 removeNotPreservedAnalysis(P
);
891 recordAvailableAnalysis(P
);
894 PassVector
.push_back(P
);
898 /// Populate RP with analysis pass that are required by
899 /// pass P and are available. Populate RP_NotAvail with analysis
900 /// pass that are required by pass P but are not available.
901 void PMDataManager::collectRequiredAnalysis(SmallVector
<Pass
*, 8>&RP
,
902 SmallVector
<AnalysisID
, 8> &RP_NotAvail
,
904 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
905 const AnalysisUsage::VectorType
&RequiredSet
= AnUsage
->getRequiredSet();
906 for (AnalysisUsage::VectorType::const_iterator
907 I
= RequiredSet
.begin(), E
= RequiredSet
.end(); I
!= E
; ++I
) {
908 if (Pass
*AnalysisPass
= findAnalysisPass(*I
, true))
909 RP
.push_back(AnalysisPass
);
911 RP_NotAvail
.push_back(*I
);
914 const AnalysisUsage::VectorType
&IDs
= AnUsage
->getRequiredTransitiveSet();
915 for (AnalysisUsage::VectorType::const_iterator I
= IDs
.begin(),
916 E
= IDs
.end(); I
!= E
; ++I
) {
917 if (Pass
*AnalysisPass
= findAnalysisPass(*I
, true))
918 RP
.push_back(AnalysisPass
);
920 RP_NotAvail
.push_back(*I
);
924 // All Required analyses should be available to the pass as it runs! Here
925 // we fill in the AnalysisImpls member of the pass so that it can
926 // successfully use the getAnalysis() method to retrieve the
927 // implementations it needs.
929 void PMDataManager::initializeAnalysisImpl(Pass
*P
) {
930 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
932 for (AnalysisUsage::VectorType::const_iterator
933 I
= AnUsage
->getRequiredSet().begin(),
934 E
= AnUsage
->getRequiredSet().end(); I
!= E
; ++I
) {
935 Pass
*Impl
= findAnalysisPass(*I
, true);
937 // This may be analysis pass that is initialized on the fly.
938 // If that is not the case then it will raise an assert when it is used.
940 AnalysisResolver
*AR
= P
->getResolver();
941 assert(AR
&& "Analysis Resolver is not set");
942 AR
->addAnalysisImplsPair(*I
, Impl
);
946 /// Find the pass that implements Analysis AID. If desired pass is not found
947 /// then return NULL.
948 Pass
*PMDataManager::findAnalysisPass(AnalysisID AID
, bool SearchParent
) {
950 // Check if AvailableAnalysis map has one entry.
951 std::map
<AnalysisID
, Pass
*>::const_iterator I
= AvailableAnalysis
.find(AID
);
953 if (I
!= AvailableAnalysis
.end())
956 // Search Parents through TopLevelManager
958 return TPM
->findAnalysisPass(AID
);
963 // Print list of passes that are last used by P.
964 void PMDataManager::dumpLastUses(Pass
*P
, unsigned Offset
) const{
966 SmallVector
<Pass
*, 12> LUses
;
968 // If this is a on the fly manager then it does not have TPM.
972 TPM
->collectLastUses(LUses
, P
);
974 for (SmallVector
<Pass
*, 12>::iterator I
= LUses
.begin(),
975 E
= LUses
.end(); I
!= E
; ++I
) {
976 llvm::cerr
<< "--" << std::string(Offset
*2, ' ');
977 (*I
)->dumpPassStructure(0);
981 void PMDataManager::dumpPassArguments() const {
982 for (SmallVector
<Pass
*, 8>::const_iterator I
= PassVector
.begin(),
983 E
= PassVector
.end(); I
!= E
; ++I
) {
984 if (PMDataManager
*PMD
= dynamic_cast<PMDataManager
*>(*I
))
985 PMD
->dumpPassArguments();
987 if (const PassInfo
*PI
= (*I
)->getPassInfo())
988 if (!PI
->isAnalysisGroup())
989 cerr
<< " -" << PI
->getPassArgument();
993 void PMDataManager::dumpPassInfo(Pass
*P
, enum PassDebuggingString S1
,
994 enum PassDebuggingString S2
,
996 if (PassDebugging
< Executions
)
998 cerr
<< (void*)this << std::string(getDepth()*2+1, ' ');
1001 cerr
<< "Executing Pass '" << P
->getPassName();
1003 case MODIFICATION_MSG
:
1004 cerr
<< "Made Modification '" << P
->getPassName();
1007 cerr
<< " Freeing Pass '" << P
->getPassName();
1013 case ON_BASICBLOCK_MSG
:
1014 cerr
<< "' on BasicBlock '" << Msg
<< "'...\n";
1016 case ON_FUNCTION_MSG
:
1017 cerr
<< "' on Function '" << Msg
<< "'...\n";
1020 cerr
<< "' on Module '" << Msg
<< "'...\n";
1023 cerr
<< "' on Loop " << Msg
<< "'...\n";
1026 cerr
<< "' on Call Graph " << Msg
<< "'...\n";
1033 void PMDataManager::dumpRequiredSet(const Pass
*P
) const {
1034 if (PassDebugging
< Details
)
1037 AnalysisUsage analysisUsage
;
1038 P
->getAnalysisUsage(analysisUsage
);
1039 dumpAnalysisUsage("Required", P
, analysisUsage
.getRequiredSet());
1042 void PMDataManager::dumpPreservedSet(const Pass
*P
) const {
1043 if (PassDebugging
< Details
)
1046 AnalysisUsage analysisUsage
;
1047 P
->getAnalysisUsage(analysisUsage
);
1048 dumpAnalysisUsage("Preserved", P
, analysisUsage
.getPreservedSet());
1051 void PMDataManager::dumpAnalysisUsage(const char *Msg
, const Pass
*P
,
1052 const AnalysisUsage::VectorType
&Set
) const {
1053 assert(PassDebugging
>= Details
);
1056 cerr
<< (void*)P
<< std::string(getDepth()*2+3, ' ') << Msg
<< " Analyses:";
1057 for (unsigned i
= 0; i
!= Set
.size(); ++i
) {
1059 cerr
<< " " << Set
[i
]->getPassName();
1064 /// Add RequiredPass into list of lower level passes required by pass P.
1065 /// RequiredPass is run on the fly by Pass Manager when P requests it
1066 /// through getAnalysis interface.
1067 /// This should be handled by specific pass manager.
1068 void PMDataManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1070 TPM
->dumpArguments();
1074 // Module Level pass may required Function Level analysis info
1075 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1076 // to provide this on demand. In that case, in Pass manager terminology,
1077 // module level pass is requiring lower level analysis info managed by
1078 // lower level pass manager.
1080 // When Pass manager is not able to order required analysis info, Pass manager
1081 // checks whether any lower level manager will be able to provide this
1082 // analysis info on demand or not.
1084 cerr
<< "Unable to schedule '" << RequiredPass
->getPassName();
1085 cerr
<< "' required by '" << P
->getPassName() << "'\n";
1087 assert(0 && "Unable to schedule pass");
1091 PMDataManager::~PMDataManager() {
1092 for (SmallVector
<Pass
*, 8>::iterator I
= PassVector
.begin(),
1093 E
= PassVector
.end(); I
!= E
; ++I
)
1097 //===----------------------------------------------------------------------===//
1098 // NOTE: Is this the right place to define this method ?
1099 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1100 Pass
*AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID
, bool dir
) const {
1101 return PM
.findAnalysisPass(ID
, dir
);
1104 Pass
*AnalysisResolver::findImplPass(Pass
*P
, const PassInfo
*AnalysisPI
,
1106 return PM
.getOnTheFlyPass(P
, AnalysisPI
, F
);
1109 //===----------------------------------------------------------------------===//
1110 // BBPassManager implementation
1112 /// Execute all of the passes scheduled for execution by invoking
1113 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1114 /// the function, and if so, return true.
1115 bool BBPassManager::runOnFunction(Function
&F
) {
1116 if (F
.isDeclaration())
1119 bool Changed
= doInitialization(F
);
1121 for (Function::iterator I
= F
.begin(), E
= F
.end(); I
!= E
; ++I
)
1122 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1123 BasicBlockPass
*BP
= getContainedPass(Index
);
1125 dumpPassInfo(BP
, EXECUTION_MSG
, ON_BASICBLOCK_MSG
, I
->getNameStart());
1126 dumpRequiredSet(BP
);
1128 initializeAnalysisImpl(BP
);
1131 // If the pass crashes, remember this.
1132 PassManagerPrettyStackEntry
X(BP
, *I
);
1134 if (TheTimeInfo
) TheTimeInfo
->passStarted(BP
);
1135 Changed
|= BP
->runOnBasicBlock(*I
);
1136 if (TheTimeInfo
) TheTimeInfo
->passEnded(BP
);
1140 dumpPassInfo(BP
, MODIFICATION_MSG
, ON_BASICBLOCK_MSG
,
1142 dumpPreservedSet(BP
);
1144 verifyPreservedAnalysis(BP
);
1145 removeNotPreservedAnalysis(BP
);
1146 recordAvailableAnalysis(BP
);
1147 removeDeadPasses(BP
, I
->getNameStart(), ON_BASICBLOCK_MSG
);
1150 return Changed
|= doFinalization(F
);
1153 // Implement doInitialization and doFinalization
1154 bool BBPassManager::doInitialization(Module
&M
) {
1155 bool Changed
= false;
1157 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1158 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1163 bool BBPassManager::doFinalization(Module
&M
) {
1164 bool Changed
= false;
1166 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1167 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1172 bool BBPassManager::doInitialization(Function
&F
) {
1173 bool Changed
= false;
1175 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1176 BasicBlockPass
*BP
= getContainedPass(Index
);
1177 Changed
|= BP
->doInitialization(F
);
1183 bool BBPassManager::doFinalization(Function
&F
) {
1184 bool Changed
= false;
1186 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1187 BasicBlockPass
*BP
= getContainedPass(Index
);
1188 Changed
|= BP
->doFinalization(F
);
1195 //===----------------------------------------------------------------------===//
1196 // FunctionPassManager implementation
1198 /// Create new Function pass manager
1199 FunctionPassManager::FunctionPassManager(ModuleProvider
*P
) {
1200 FPM
= new FunctionPassManagerImpl(0);
1201 // FPM is the top level manager.
1202 FPM
->setTopLevelManager(FPM
);
1204 AnalysisResolver
*AR
= new AnalysisResolver(*FPM
);
1205 FPM
->setResolver(AR
);
1210 FunctionPassManager::~FunctionPassManager() {
1214 /// add - Add a pass to the queue of passes to run. This passes
1215 /// ownership of the Pass to the PassManager. When the
1216 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1217 /// there is no need to delete the pass. (TODO delete passes.)
1218 /// This implies that all passes MUST be allocated with 'new'.
1219 void FunctionPassManager::add(Pass
*P
) {
1223 /// run - Execute all of the passes scheduled for execution. Keep
1224 /// track of whether any of the passes modifies the function, and if
1225 /// so, return true.
1227 bool FunctionPassManager::run(Function
&F
) {
1229 if (MP
->materializeFunction(&F
, &errstr
)) {
1230 cerr
<< "Error reading bitcode file: " << errstr
<< "\n";
1237 /// doInitialization - Run all of the initializers for the function passes.
1239 bool FunctionPassManager::doInitialization() {
1240 return FPM
->doInitialization(*MP
->getModule());
1243 /// doFinalization - Run all of the finalizers for the function passes.
1245 bool FunctionPassManager::doFinalization() {
1246 return FPM
->doFinalization(*MP
->getModule());
1249 //===----------------------------------------------------------------------===//
1250 // FunctionPassManagerImpl implementation
1252 bool FunctionPassManagerImpl::doInitialization(Module
&M
) {
1253 bool Changed
= false;
1255 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1256 Changed
|= getContainedManager(Index
)->doInitialization(M
);
1261 bool FunctionPassManagerImpl::doFinalization(Module
&M
) {
1262 bool Changed
= false;
1264 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1265 Changed
|= getContainedManager(Index
)->doFinalization(M
);
1270 /// cleanup - After running all passes, clean up pass manager cache.
1271 void FPPassManager::cleanup() {
1272 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1273 FunctionPass
*FP
= getContainedPass(Index
);
1274 AnalysisResolver
*AR
= FP
->getResolver();
1275 assert(AR
&& "Analysis Resolver is not set");
1276 AR
->clearAnalysisImpls();
1280 // Execute all the passes managed by this top level manager.
1281 // Return true if any function is modified by a pass.
1282 bool FunctionPassManagerImpl::run(Function
&F
) {
1283 bool Changed
= false;
1284 TimingInfo::createTheTimeInfo();
1289 initializeAllAnalysisInfo();
1290 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1291 Changed
|= getContainedManager(Index
)->runOnFunction(F
);
1293 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1294 getContainedManager(Index
)->cleanup();
1299 //===----------------------------------------------------------------------===//
1300 // FPPassManager implementation
1302 char FPPassManager::ID
= 0;
1303 /// Print passes managed by this manager
1304 void FPPassManager::dumpPassStructure(unsigned Offset
) {
1305 llvm::cerr
<< std::string(Offset
*2, ' ') << "FunctionPass Manager\n";
1306 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1307 FunctionPass
*FP
= getContainedPass(Index
);
1308 FP
->dumpPassStructure(Offset
+ 1);
1309 dumpLastUses(FP
, Offset
+1);
1314 /// Execute all of the passes scheduled for execution by invoking
1315 /// runOnFunction method. Keep track of whether any of the passes modifies
1316 /// the function, and if so, return true.
1317 bool FPPassManager::runOnFunction(Function
&F
) {
1318 if (F
.isDeclaration())
1321 bool Changed
= false;
1323 // Collect inherited analysis from Module level pass manager.
1324 populateInheritedAnalysis(TPM
->activeStack
);
1326 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1327 FunctionPass
*FP
= getContainedPass(Index
);
1329 dumpPassInfo(FP
, EXECUTION_MSG
, ON_FUNCTION_MSG
, F
.getNameStart());
1330 dumpRequiredSet(FP
);
1332 initializeAnalysisImpl(FP
);
1335 PassManagerPrettyStackEntry
X(FP
, F
);
1337 if (TheTimeInfo
) TheTimeInfo
->passStarted(FP
);
1338 Changed
|= FP
->runOnFunction(F
);
1339 if (TheTimeInfo
) TheTimeInfo
->passEnded(FP
);
1343 dumpPassInfo(FP
, MODIFICATION_MSG
, ON_FUNCTION_MSG
, F
.getNameStart());
1344 dumpPreservedSet(FP
);
1346 verifyPreservedAnalysis(FP
);
1347 removeNotPreservedAnalysis(FP
);
1348 recordAvailableAnalysis(FP
);
1349 removeDeadPasses(FP
, F
.getNameStart(), ON_FUNCTION_MSG
);
1351 // If dominator information is available then verify the info if requested.
1352 verifyDomInfo(*FP
, F
);
1357 bool FPPassManager::runOnModule(Module
&M
) {
1358 bool Changed
= doInitialization(M
);
1360 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
)
1363 return Changed
|= doFinalization(M
);
1366 bool FPPassManager::doInitialization(Module
&M
) {
1367 bool Changed
= false;
1369 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1370 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1375 bool FPPassManager::doFinalization(Module
&M
) {
1376 bool Changed
= false;
1378 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1379 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1384 //===----------------------------------------------------------------------===//
1385 // MPPassManager implementation
1387 /// Execute all of the passes scheduled for execution by invoking
1388 /// runOnModule method. Keep track of whether any of the passes modifies
1389 /// the module, and if so, return true.
1391 MPPassManager::runOnModule(Module
&M
) {
1392 bool Changed
= false;
1394 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1395 ModulePass
*MP
= getContainedPass(Index
);
1397 dumpPassInfo(MP
, EXECUTION_MSG
, ON_MODULE_MSG
,
1398 M
.getModuleIdentifier().c_str());
1399 dumpRequiredSet(MP
);
1401 initializeAnalysisImpl(MP
);
1404 PassManagerPrettyStackEntry
X(MP
, M
);
1405 if (TheTimeInfo
) TheTimeInfo
->passStarted(MP
);
1406 Changed
|= MP
->runOnModule(M
);
1407 if (TheTimeInfo
) TheTimeInfo
->passEnded(MP
);
1411 dumpPassInfo(MP
, MODIFICATION_MSG
, ON_MODULE_MSG
,
1412 M
.getModuleIdentifier().c_str());
1413 dumpPreservedSet(MP
);
1415 verifyPreservedAnalysis(MP
);
1416 removeNotPreservedAnalysis(MP
);
1417 recordAvailableAnalysis(MP
);
1418 removeDeadPasses(MP
, M
.getModuleIdentifier().c_str(), ON_MODULE_MSG
);
1423 /// Add RequiredPass into list of lower level passes required by pass P.
1424 /// RequiredPass is run on the fly by Pass Manager when P requests it
1425 /// through getAnalysis interface.
1426 void MPPassManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1427 assert(P
->getPotentialPassManagerType() == PMT_ModulePassManager
&&
1428 "Unable to handle Pass that requires lower level Analysis pass");
1429 assert((P
->getPotentialPassManagerType() <
1430 RequiredPass
->getPotentialPassManagerType()) &&
1431 "Unable to handle Pass that requires lower level Analysis pass");
1433 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[P
];
1435 FPP
= new FunctionPassManagerImpl(0);
1436 // FPP is the top level manager.
1437 FPP
->setTopLevelManager(FPP
);
1439 OnTheFlyManagers
[P
] = FPP
;
1441 FPP
->add(RequiredPass
);
1443 // Register P as the last user of RequiredPass.
1444 SmallVector
<Pass
*, 12> LU
;
1445 LU
.push_back(RequiredPass
);
1446 FPP
->setLastUser(LU
, P
);
1449 /// Return function pass corresponding to PassInfo PI, that is
1450 /// required by module pass MP. Instantiate analysis pass, by using
1451 /// its runOnFunction() for function F.
1452 Pass
* MPPassManager::getOnTheFlyPass(Pass
*MP
, const PassInfo
*PI
, Function
&F
){
1453 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[MP
];
1454 assert(FPP
&& "Unable to find on the fly pass");
1457 return (dynamic_cast<PMTopLevelManager
*>(FPP
))->findAnalysisPass(PI
);
1461 //===----------------------------------------------------------------------===//
1462 // PassManagerImpl implementation
1464 /// run - Execute all of the passes scheduled for execution. Keep track of
1465 /// whether any of the passes modifies the module, and if so, return true.
1466 bool PassManagerImpl::run(Module
&M
) {
1467 bool Changed
= false;
1468 TimingInfo::createTheTimeInfo();
1473 initializeAllAnalysisInfo();
1474 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1475 Changed
|= getContainedManager(Index
)->runOnModule(M
);
1479 //===----------------------------------------------------------------------===//
1480 // PassManager implementation
1482 /// Create new pass manager
1483 PassManager::PassManager() {
1484 PM
= new PassManagerImpl(0);
1485 // PM is the top level manager
1486 PM
->setTopLevelManager(PM
);
1489 PassManager::~PassManager() {
1493 /// add - Add a pass to the queue of passes to run. This passes ownership of
1494 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1495 /// will be destroyed as well, so there is no need to delete the pass. This
1496 /// implies that all passes MUST be allocated with 'new'.
1497 void PassManager::add(Pass
*P
) {
1501 /// run - Execute all of the passes scheduled for execution. Keep track of
1502 /// whether any of the passes modifies the module, and if so, return true.
1503 bool PassManager::run(Module
&M
) {
1507 //===----------------------------------------------------------------------===//
1508 // TimingInfo Class - This class is used to calculate information about the
1509 // amount of time each pass takes to execute. This only happens with
1510 // -time-passes is enabled on the command line.
1512 bool llvm::TimePassesIsEnabled
= false;
1513 static cl::opt
<bool,true>
1514 EnableTiming("time-passes", cl::location(TimePassesIsEnabled
),
1515 cl::desc("Time each pass, printing elapsed time for each on exit"));
1517 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1518 // a non null value (if the -time-passes option is enabled) or it leaves it
1519 // null. It may be called multiple times.
1520 void TimingInfo::createTheTimeInfo() {
1521 if (!TimePassesIsEnabled
|| TheTimeInfo
) return;
1523 // Constructed the first time this is called, iff -time-passes is enabled.
1524 // This guarantees that the object will be constructed before static globals,
1525 // thus it will be destroyed before them.
1526 static ManagedStatic
<TimingInfo
> TTI
;
1527 TheTimeInfo
= &*TTI
;
1530 /// If TimingInfo is enabled then start pass timer.
1531 void StartPassTimer(Pass
*P
) {
1533 TheTimeInfo
->passStarted(P
);
1536 /// If TimingInfo is enabled then stop pass timer.
1537 void StopPassTimer(Pass
*P
) {
1539 TheTimeInfo
->passEnded(P
);
1542 //===----------------------------------------------------------------------===//
1543 // PMStack implementation
1546 // Pop Pass Manager from the stack and clear its analysis info.
1547 void PMStack::pop() {
1549 PMDataManager
*Top
= this->top();
1550 Top
->initializeAnalysisInfo();
1555 // Push PM on the stack and set its top level manager.
1556 void PMStack::push(PMDataManager
*PM
) {
1557 assert(PM
&& "Unable to push. Pass Manager expected");
1559 if (!this->empty()) {
1560 PMTopLevelManager
*TPM
= this->top()->getTopLevelManager();
1562 assert(TPM
&& "Unable to find top level manager");
1563 TPM
->addIndirectPassManager(PM
);
1564 PM
->setTopLevelManager(TPM
);
1570 // Dump content of the pass manager stack.
1571 void PMStack::dump() {
1572 for (std::deque
<PMDataManager
*>::iterator I
= S
.begin(),
1573 E
= S
.end(); I
!= E
; ++I
)
1574 printf("%s ", dynamic_cast<Pass
*>(*I
)->getPassName());
1580 /// Find appropriate Module Pass Manager in the PM Stack and
1581 /// add self into that manager.
1582 void ModulePass::assignPassManager(PMStack
&PMS
,
1583 PassManagerType PreferredType
) {
1584 // Find Module Pass Manager
1585 while(!PMS
.empty()) {
1586 PassManagerType TopPMType
= PMS
.top()->getPassManagerType();
1587 if (TopPMType
== PreferredType
)
1588 break; // We found desired pass manager
1589 else if (TopPMType
> PMT_ModulePassManager
)
1590 PMS
.pop(); // Pop children pass managers
1594 assert(!PMS
.empty() && "Unable to find appropriate Pass Manager");
1595 PMS
.top()->add(this);
1598 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1599 /// in the PM Stack and add self into that manager.
1600 void FunctionPass::assignPassManager(PMStack
&PMS
,
1601 PassManagerType PreferredType
) {
1603 // Find Module Pass Manager
1604 while(!PMS
.empty()) {
1605 if (PMS
.top()->getPassManagerType() > PMT_FunctionPassManager
)
1610 FPPassManager
*FPP
= dynamic_cast<FPPassManager
*>(PMS
.top());
1612 // Create new Function Pass Manager
1614 assert(!PMS
.empty() && "Unable to create Function Pass Manager");
1615 PMDataManager
*PMD
= PMS
.top();
1617 // [1] Create new Function Pass Manager
1618 FPP
= new FPPassManager(PMD
->getDepth() + 1);
1619 FPP
->populateInheritedAnalysis(PMS
);
1621 // [2] Set up new manager's top level manager
1622 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
1623 TPM
->addIndirectPassManager(FPP
);
1625 // [3] Assign manager to manage this new manager. This may create
1626 // and push new managers into PMS
1627 FPP
->assignPassManager(PMS
, PMD
->getPassManagerType());
1629 // [4] Push new manager into PMS
1633 // Assign FPP as the manager of this pass.
1637 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1638 /// in the PM Stack and add self into that manager.
1639 void BasicBlockPass::assignPassManager(PMStack
&PMS
,
1640 PassManagerType PreferredType
) {
1641 BBPassManager
*BBP
= NULL
;
1643 // Basic Pass Manager is a leaf pass manager. It does not handle
1644 // any other pass manager.
1646 BBP
= dynamic_cast<BBPassManager
*>(PMS
.top());
1648 // If leaf manager is not Basic Block Pass manager then create new
1649 // basic Block Pass manager.
1652 assert(!PMS
.empty() && "Unable to create BasicBlock Pass Manager");
1653 PMDataManager
*PMD
= PMS
.top();
1655 // [1] Create new Basic Block Manager
1656 BBP
= new BBPassManager(PMD
->getDepth() + 1);
1658 // [2] Set up new manager's top level manager
1659 // Basic Block Pass Manager does not live by itself
1660 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
1661 TPM
->addIndirectPassManager(BBP
);
1663 // [3] Assign manager to manage this new manager. This may create
1664 // and push new managers into PMS
1665 BBP
->assignPassManager(PMS
);
1667 // [4] Push new manager into PMS
1671 // Assign BBP as the manager of this pass.
1675 PassManagerBase::~PassManagerBase() {}
1677 /*===-- C Bindings --------------------------------------------------------===*/
1679 LLVMPassManagerRef
LLVMCreatePassManager() {
1680 return wrap(new PassManager());
1683 LLVMPassManagerRef
LLVMCreateFunctionPassManager(LLVMModuleProviderRef P
) {
1684 return wrap(new FunctionPassManager(unwrap(P
)));
1687 int LLVMRunPassManager(LLVMPassManagerRef PM
, LLVMModuleRef M
) {
1688 return unwrap
<PassManager
>(PM
)->run(*unwrap(M
));
1691 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM
) {
1692 return unwrap
<FunctionPassManager
>(FPM
)->doInitialization();
1695 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM
, LLVMValueRef F
) {
1696 return unwrap
<FunctionPassManager
>(FPM
)->run(*unwrap
<Function
>(F
));
1699 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM
) {
1700 return unwrap
<FunctionPassManager
>(FPM
)->doFinalization();
1703 void LLVMDisposePassManager(LLVMPassManagerRef PM
) {