1 //===- PassManagerT.h - Container for Passes ---------------------*- C++ -*--=//
3 // This file defines the PassManagerT class. This class is used to hold,
4 // maintain, and optimize execution of Pass's. The PassManager class ensures
5 // that analysis results are available before a pass runs, and that Pass's are
6 // destroyed when the PassManager is destroyed.
8 // The PassManagerT template is instantiated three times to do its job. The
9 // public PassManager class is a Pimpl around the PassManagerT<Module> interface
10 // to avoid having all of the PassManager clients being exposed to the
11 // implementation details herein.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_PASSMANAGER_T_H
16 #define LLVM_PASSMANAGER_T_H
18 #include "llvm/Pass.h"
19 #include "Support/CommandLine.h"
24 //===----------------------------------------------------------------------===//
25 // Pass debugging information. Often it is useful to find out what pass is
26 // running when a crash occurs in a utility. When this library is compiled with
27 // debugging on, a command line option (--debug-pass) is enabled that causes the
28 // pass name to be printed before it executes.
31 // Different debug levels that can be enabled...
33 None, Arguments, Structure, Executions, Details
36 static cl::opt<enum PassDebugLevel>
37 PassDebugging("debug-pass", cl::Hidden,
38 cl::desc("Print PassManager debugging information"),
40 clEnumVal(None , "disable debug output"),
41 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
42 clEnumVal(Structure , "print pass structure before run()"),
43 clEnumVal(Executions, "print pass name before it is executed"),
44 clEnumVal(Details , "print pass details when it is executed"),
47 //===----------------------------------------------------------------------===//
48 // PMDebug class - a set of debugging functions, that are not to be
49 // instantiated by the template.
52 static void PerformPassStartupStuff(Pass *P) {
53 // If debugging is enabled, print out argument information...
54 if (PassDebugging >= Arguments) {
55 std::cerr << "Pass Arguments: ";
56 PrintArgumentInformation(P);
59 // Print the pass execution structure
60 if (PassDebugging >= Structure)
61 P->dumpPassStructure();
65 static void PrintArgumentInformation(const Pass *P);
66 static void PrintPassInformation(unsigned,const char*,Pass *, Annotable *);
67 static void PrintAnalysisSetInfo(unsigned,const char*,Pass *P,
68 const std::vector<AnalysisID> &);
72 //===----------------------------------------------------------------------===//
73 // TimingInfo Class - This class is used to calculate information about the
74 // amount of time each pass takes to execute. This only happens when
75 // -time-passes is enabled on the command line.
78 std::map<Pass*, double> TimingData;
79 TimingInfo() {} // Private ctor, must use create member
81 // Create method. If Timing is enabled, this creates and returns a new timing
82 // object, otherwise it returns null.
84 static TimingInfo *create();
86 // TimingDtor - Print out information about timing information
89 void passStarted(Pass *P);
90 void passEnded(Pass *P);
95 //===----------------------------------------------------------------------===//
96 // Declare the PassManagerTraits which will be specialized...
98 template<class UnitType> class PassManagerTraits; // Do not define.
101 //===----------------------------------------------------------------------===//
102 // PassManagerT - Container object for passes. The PassManagerT destructor
103 // deletes all passes contained inside of the PassManagerT, so you shouldn't
104 // delete passes manually, and all passes should be dynamically allocated.
106 template<typename UnitType>
107 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
108 typedef PassManagerTraits<UnitType> Traits;
109 typedef typename Traits::PassClass PassClass;
110 typedef typename Traits::SubPassClass SubPassClass;
111 typedef typename Traits::BatcherClass BatcherClass;
112 typedef typename Traits::ParentClass ParentClass;
114 friend typename Traits::PassClass;
115 friend typename Traits::SubPassClass;
118 std::vector<PassClass*> Passes; // List of passes to run
120 // The parent of this pass manager...
121 ParentClass * const Parent;
123 // The current batcher if one is in use, or null
124 BatcherClass *Batcher;
126 // CurrentAnalyses - As the passes are being run, this map contains the
127 // analyses that are available to the current pass for use. This is accessed
128 // through the getAnalysis() function in this class and in Pass.
130 std::map<AnalysisID, Pass*> CurrentAnalyses;
132 // LastUseOf - This map keeps track of the last usage in our pipeline of a
133 // particular pass. When executing passes, the memory for .first is free'd
134 // after .second is run.
136 std::map<Pass*, Pass*> LastUseOf;
139 PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
141 // Delete all of the contained passes...
142 for (typename std::vector<PassClass*>::iterator
143 I = Passes.begin(), E = Passes.end(); I != E; ++I)
147 // run - Run all of the queued passes on the specified module in an optimal
149 virtual bool runOnUnit(UnitType *M) {
150 bool MadeChanges = false;
152 CurrentAnalyses.clear();
154 // LastUserOf - This contains the inverted LastUseOfMap...
155 std::map<Pass *, std::vector<Pass*> > LastUserOf;
156 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
157 E = LastUseOf.end(); I != E; ++I)
158 LastUserOf[I->second].push_back(I->first);
161 // Output debug information...
162 if (Parent == 0) PMDebug::PerformPassStartupStuff(this);
164 // Run all of the passes
165 for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
166 PassClass *P = Passes[i];
168 PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
171 // Get information about what analyses the pass uses...
172 AnalysisUsage AnUsage;
173 P->getAnalysisUsage(AnUsage);
174 PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
175 AnUsage.getRequiredSet());
178 // All Required analyses should be available to the pass as it runs!
179 for (std::vector<AnalysisID>::const_iterator
180 I = AnUsage.getRequiredSet().begin(),
181 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
182 assert(getAnalysisOrNullUp(*I) && "Analysis used but not available!");
188 bool Changed = runPass(P, M);
190 MadeChanges |= Changed;
193 PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
195 PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
196 AnUsage.getPreservedSet());
199 // Erase all analyses not in the preserved set...
200 if (!AnUsage.preservesAll()) {
201 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
202 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
203 E = CurrentAnalyses.end(); I != E; )
204 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
206 ++I; // This analysis is preserved, leave it in the available set...
208 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
209 I = CurrentAnalyses.erase(I); // Analysis not preserved!
211 // GCC 2.95.3 STL doesn't have correct erase member!
212 CurrentAnalyses.erase(I);
213 I = CurrentAnalyses.begin();
218 // Add the current pass to the set of passes that have been run, and are
219 // thus available to users.
221 if (const PassInfo *PI = P->getPassInfo())
222 CurrentAnalyses[PI] = P;
224 // Free memory for any passes that we are the last use of...
225 std::vector<Pass*> &DeadPass = LastUserOf[P];
226 for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
228 PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
230 (*I)->releaseMemory();
236 // dumpPassStructure - Implement the -debug-passes=PassStructure option
237 virtual void dumpPassStructure(unsigned Offset = 0) {
238 std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
239 << " Pass Manager\n";
240 for (typename std::vector<PassClass*>::iterator
241 I = Passes.begin(), E = Passes.end(); I != E; ++I) {
243 P->dumpPassStructure(Offset+1);
245 // Loop through and see which classes are destroyed after this one...
246 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
247 E = LastUseOf.end(); I != E; ++I) {
248 if (P == I->second) {
249 std::cerr << "--" << std::string(Offset*2, ' ');
250 I->first->dumpPassStructure(0);
256 Pass *getAnalysisOrNullDown(AnalysisID ID) const {
257 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
258 if (I == CurrentAnalyses.end()) {
260 return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
266 Pass *getAnalysisOrNullUp(AnalysisID ID) const {
267 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
268 if (I == CurrentAnalyses.end()) {
270 return Parent->getAnalysisOrNullUp(ID);
276 // {start/end}Pass - Called when a pass is started, it just propogates
277 // information up to the top level PassManagerT object to tell it that a pass
278 // has started or ended. This is used to gather timing information about
281 void startPass(Pass *P) {
282 if (Parent) Parent->startPass(P);
285 void endPass(Pass *P) {
286 if (Parent) Parent->endPass(P);
290 // markPassUsed - Inform higher level pass managers (and ourselves)
291 // that these analyses are being used by this pass. This is used to
292 // make sure that analyses are not free'd before we have to use
295 void markPassUsed(AnalysisID P, Pass *User) {
296 std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.find(P);
297 if (I != CurrentAnalyses.end()) {
298 LastUseOf[I->second] = User; // Local pass, extend the lifetime
300 // Pass not in current available set, must be a higher level pass
301 // available to us, propogate to parent pass manager... We tell the
302 // parent that we (the passmanager) are using the analysis so that it
303 // frees the analysis AFTER this pass manager runs.
305 assert(Parent != 0 && "Pass available but not found! "
306 "Did your analysis pass 'Provide' itself?");
307 Parent->markPassUsed(P, this);
311 // Return the number of parent PassManagers that exist
312 virtual unsigned getDepth() const {
313 if (Parent == 0) return 0;
314 return 1 + Parent->getDepth();
317 virtual unsigned getNumContainedPasses() const { return Passes.size(); }
318 virtual const Pass *getContainedPass(unsigned N) const {
319 assert(N < Passes.size() && "Pass number out of range!");
323 // add - Add a pass to the queue of passes to run. This passes ownership of
324 // the Pass to the PassManager. When the PassManager is destroyed, the pass
325 // will be destroyed as well, so there is no need to delete the pass. This
326 // implies that all passes MUST be new'd.
328 void add(PassClass *P) {
329 // Get information about what analyses the pass uses...
330 AnalysisUsage AnUsage;
331 P->getAnalysisUsage(AnUsage);
332 const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
334 // Loop over all of the analyses used by this pass,
335 for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
336 E = Required.end(); I != E; ++I) {
337 if (getAnalysisOrNullDown(*I) == 0)
338 add((PassClass*)(*I)->createPass());
341 // Tell the pass to add itself to this PassManager... the way it does so
342 // depends on the class of the pass, and is critical to laying out passes in
343 // an optimal order..
345 P->addToPassManager(this, AnUsage);
350 // addPass - These functions are used to implement the subclass specific
351 // behaviors present in PassManager. Basically the add(Pass*) method ends up
352 // reflecting its behavior into a Pass::addToPassManager call. Subclasses of
353 // Pass override it specifically so that they can reflect the type
354 // information inherent in "this" back to the PassManager.
356 // For generic Pass subclasses (which are interprocedural passes), we simply
357 // add the pass to the end of the pass list and terminate any accumulation of
358 // FunctionPass's that are present.
360 void addPass(PassClass *P, AnalysisUsage &AnUsage) {
361 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
363 // FIXME: If this pass being added isn't killed by any of the passes in the
364 // batcher class then we can reorder to pass to execute before the batcher
365 // does, which will potentially allow us to batch more passes!
367 //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
368 if (Batcher /*&& ProvidedSet.empty()*/)
369 closeBatcher(); // This pass cannot be batched!
371 // Set the Resolver instance variable in the Pass so that it knows where to
372 // find this object...
374 setAnalysisResolver(P, this);
377 // Inform higher level pass managers (and ourselves) that these analyses are
378 // being used by this pass. This is used to make sure that analyses are not
379 // free'd before we have to use them...
381 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
382 E = RequiredSet.end(); I != E; ++I)
383 markPassUsed(*I, P); // Mark *I as used by P
385 // Erase all analyses not in the preserved set...
386 if (!AnUsage.preservesAll()) {
387 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
388 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
389 E = CurrentAnalyses.end(); I != E; )
390 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
392 ++I; // This analysis is preserved, leave it in the available set...
394 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
395 I = CurrentAnalyses.erase(I); // Analysis not preserved!
397 CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
398 I = CurrentAnalyses.begin();
403 // Add this pass to the currently available set...
404 if (const PassInfo *PI = P->getPassInfo())
405 CurrentAnalyses[PI] = P;
407 // For now assume that our results are never used...
411 // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
412 // together in a BatcherClass object so that all of the analyses are run
413 // together a function at a time.
415 void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
416 if (Batcher == 0) // If we don't have a batcher yet, make one now.
417 Batcher = new BatcherClass(this);
418 // The Batcher will queue the passes up
419 MP->addToPassManager(Batcher, AnUsage);
422 // closeBatcher - Terminate the batcher that is being worked on.
423 void closeBatcher() {
425 Passes.push_back(Batcher);
433 //===----------------------------------------------------------------------===//
434 // PassManagerTraits<BasicBlock> Specialization
436 // This pass manager is used to group together all of the BasicBlockPass's
437 // into a single unit.
439 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
440 // PassClass - The type of passes tracked by this PassManager
441 typedef BasicBlockPass PassClass;
443 // SubPassClass - The types of classes that should be collated together
444 // This is impossible to match, so BasicBlock instantiations of PassManagerT
447 typedef PassManagerT<Module> SubPassClass;
449 // BatcherClass - The type to use for collation of subtypes... This class is
450 // never instantiated for the PassManager<BasicBlock>, but it must be an
451 // instance of PassClass to typecheck.
453 typedef PassClass BatcherClass;
455 // ParentClass - The type of the parent PassManager...
456 typedef PassManagerT<Function> ParentClass;
458 // PMType - The type of the passmanager that subclasses this class
459 typedef PassManagerT<BasicBlock> PMType;
461 // runPass - Specify how the pass should be run on the UnitType
462 static bool runPass(PassClass *P, BasicBlock *M) {
463 // todo, init and finalize
464 return P->runOnBasicBlock(*M);
467 // Dummy implementation of PassStarted/PassEnded
468 static void PassStarted(Pass *P) {}
469 static void PassEnded(Pass *P) {}
471 // getPMName() - Return the name of the unit the PassManager operates on for
473 const char *getPMName() const { return "BasicBlock"; }
474 virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
476 // Implement the BasicBlockPass interface...
477 virtual bool doInitialization(Module &M);
478 virtual bool runOnBasicBlock(BasicBlock &BB);
479 virtual bool doFinalization(Module &M);
481 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
482 AU.setPreservesAll();
488 //===----------------------------------------------------------------------===//
489 // PassManagerTraits<Function> Specialization
491 // This pass manager is used to group together all of the FunctionPass's
492 // into a single unit.
494 template<> struct PassManagerTraits<Function> : public FunctionPass {
495 // PassClass - The type of passes tracked by this PassManager
496 typedef FunctionPass PassClass;
498 // SubPassClass - The types of classes that should be collated together
499 typedef BasicBlockPass SubPassClass;
501 // BatcherClass - The type to use for collation of subtypes...
502 typedef PassManagerT<BasicBlock> BatcherClass;
504 // ParentClass - The type of the parent PassManager...
505 typedef PassManagerT<Module> ParentClass;
507 // PMType - The type of the passmanager that subclasses this class
508 typedef PassManagerT<Function> PMType;
510 // runPass - Specify how the pass should be run on the UnitType
511 static bool runPass(PassClass *P, Function *F) {
512 return P->runOnFunction(*F);
515 // Dummy implementation of PassStarted/PassEnded
516 static void PassStarted(Pass *P) {}
517 static void PassEnded(Pass *P) {}
519 // getPMName() - Return the name of the unit the PassManager operates on for
521 const char *getPMName() const { return "Function"; }
522 virtual const char *getPassName() const { return "Function Pass Manager"; }
524 // Implement the FunctionPass interface...
525 virtual bool doInitialization(Module &M);
526 virtual bool runOnFunction(Function &F);
527 virtual bool doFinalization(Module &M);
529 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
530 AU.setPreservesAll();
536 //===----------------------------------------------------------------------===//
537 // PassManagerTraits<Module> Specialization
539 // This is the top level PassManager implementation that holds generic passes.
541 template<> struct PassManagerTraits<Module> : public Pass {
542 // PassClass - The type of passes tracked by this PassManager
543 typedef Pass PassClass;
545 // SubPassClass - The types of classes that should be collated together
546 typedef FunctionPass SubPassClass;
548 // BatcherClass - The type to use for collation of subtypes...
549 typedef PassManagerT<Function> BatcherClass;
551 // ParentClass - The type of the parent PassManager...
552 typedef AnalysisResolver ParentClass;
554 // runPass - Specify how the pass should be run on the UnitType
555 static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
557 // getPMName() - Return the name of the unit the PassManager operates on for
559 const char *getPMName() const { return "Module"; }
560 virtual const char *getPassName() const { return "Module Pass Manager"; }
562 // TimingInformation - This data member maintains timing information for each
563 // of the passes that is executed.
565 TimingInfo *TimeInfo;
567 // PassStarted/Ended - This callback is notified any time a pass is started
568 // or stops. This is used to collect timing information about the different
569 // passes being executed.
571 void PassStarted(Pass *P) {
572 if (TimeInfo) TimeInfo->passStarted(P);
574 void PassEnded(Pass *P) {
575 if (TimeInfo) TimeInfo->passEnded(P);
578 // run - Implement the PassManager interface...
579 bool run(Module &M) {
580 TimeInfo = TimingInfo::create();
581 bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
589 // PassManagerTraits constructor - Create a timing info object if the user
590 // specified timing info should be collected on the command line.
592 PassManagerTraits() : TimeInfo(0) {}
597 //===----------------------------------------------------------------------===//
598 // PassManagerTraits Method Implementations
601 // PassManagerTraits<BasicBlock> Implementations
603 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
604 bool Changed = false;
605 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
606 ((PMType*)this)->Passes[i]->doInitialization(M);
610 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
611 return ((PMType*)this)->runOnUnit(&BB);
614 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
615 bool Changed = false;
616 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
617 ((PMType*)this)->Passes[i]->doFinalization(M);
622 // PassManagerTraits<Function> Implementations
624 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
625 bool Changed = false;
626 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
627 ((PMType*)this)->Passes[i]->doInitialization(M);
631 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
632 return ((PMType*)this)->runOnUnit(&F);
635 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
636 bool Changed = false;
637 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
638 ((PMType*)this)->Passes[i]->doFinalization(M);