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"
23 //===----------------------------------------------------------------------===//
24 // Pass debugging information. Often it is useful to find out what pass is
25 // running when a crash occurs in a utility. When this library is compiled with
26 // debugging on, a command line option (--debug-pass) is enabled that causes the
27 // pass name to be printed before it executes.
30 // Different debug levels that can be enabled...
32 None, Structure, Executions, Details
35 static cl::opt<enum PassDebugLevel>
36 PassDebugging("debug-pass", cl::Hidden,
37 cl::desc("Print PassManager debugging information"),
39 clEnumVal(None , "disable debug output"),
40 // TODO: add option to print out pass names "PassOptions"
41 clEnumVal(Structure , "print pass structure before run()"),
42 clEnumVal(Executions, "print pass name before it is executed"),
43 clEnumVal(Details , "print pass details when it is executed"),
46 //===----------------------------------------------------------------------===//
47 // PMDebug class - a set of debugging functions, that are not to be
48 // instantiated by the template.
51 // If compiled in debug mode, these functions can be enabled by setting
52 // -debug-pass on the command line of the tool being used.
54 static void PrintPassStructure(Pass *P) {
55 if (PassDebugging >= Structure)
56 P->dumpPassStructure();
58 static void PrintPassInformation(unsigned,const char*,Pass *, Annotable *);
59 static void PrintAnalysisSetInfo(unsigned,const char*,Pass *P,
60 const std::vector<AnalysisID> &);
64 //===----------------------------------------------------------------------===//
65 // TimingInfo Class - This class is used to calculate information about the
66 // amount of time each pass takes to execute. This only happens when
67 // -time-passes is enabled on the command line.
70 std::map<Pass*, double> TimingData;
71 TimingInfo() {} // Private ctor, must use create member
73 // Create method. If Timing is enabled, this creates and returns a new timing
74 // object, otherwise it returns null.
76 static TimingInfo *create();
78 // TimingDtor - Print out information about timing information
81 void passStarted(Pass *P);
82 void passEnded(Pass *P);
87 //===----------------------------------------------------------------------===//
88 // Declare the PassManagerTraits which will be specialized...
90 template<class UnitType> class PassManagerTraits; // Do not define.
93 //===----------------------------------------------------------------------===//
94 // PassManagerT - Container object for passes. The PassManagerT destructor
95 // deletes all passes contained inside of the PassManagerT, so you shouldn't
96 // delete passes manually, and all passes should be dynamically allocated.
98 template<typename UnitType>
99 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
100 typedef PassManagerTraits<UnitType> Traits;
101 typedef typename Traits::PassClass PassClass;
102 typedef typename Traits::SubPassClass SubPassClass;
103 typedef typename Traits::BatcherClass BatcherClass;
104 typedef typename Traits::ParentClass ParentClass;
106 friend typename Traits::PassClass;
107 friend typename Traits::SubPassClass;
110 std::vector<PassClass*> Passes; // List of passes to run
112 // The parent of this pass manager...
113 ParentClass * const Parent;
115 // The current batcher if one is in use, or null
116 BatcherClass *Batcher;
118 // CurrentAnalyses - As the passes are being run, this map contains the
119 // analyses that are available to the current pass for use. This is accessed
120 // through the getAnalysis() function in this class and in Pass.
122 std::map<AnalysisID, Pass*> CurrentAnalyses;
124 // LastUseOf - This map keeps track of the last usage in our pipeline of a
125 // particular pass. When executing passes, the memory for .first is free'd
126 // after .second is run.
128 std::map<Pass*, Pass*> LastUseOf;
131 PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
133 // Delete all of the contained passes...
134 for (typename std::vector<PassClass*>::iterator
135 I = Passes.begin(), E = Passes.end(); I != E; ++I)
139 // run - Run all of the queued passes on the specified module in an optimal
141 virtual bool runOnUnit(UnitType *M) {
142 bool MadeChanges = false;
144 CurrentAnalyses.clear();
146 // LastUserOf - This contains the inverted LastUseOfMap...
147 std::map<Pass *, std::vector<Pass*> > LastUserOf;
148 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
149 E = LastUseOf.end(); I != E; ++I)
150 LastUserOf[I->second].push_back(I->first);
153 // Output debug information...
154 if (Parent == 0) PMDebug::PrintPassStructure(this);
156 // Run all of the passes
157 for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
158 PassClass *P = Passes[i];
160 PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
163 // Get information about what analyses the pass uses...
164 AnalysisUsage AnUsage;
165 P->getAnalysisUsage(AnUsage);
166 PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
167 AnUsage.getRequiredSet());
170 // All Required analyses should be available to the pass as it runs!
171 for (std::vector<AnalysisID>::const_iterator
172 I = AnUsage.getRequiredSet().begin(),
173 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
174 assert(getAnalysisOrNullUp(*I) && "Analysis used but not available!");
180 bool Changed = runPass(P, M);
182 MadeChanges |= Changed;
185 PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
187 PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
188 AnUsage.getPreservedSet());
191 // Erase all analyses not in the preserved set...
192 if (!AnUsage.preservesAll()) {
193 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
194 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
195 E = CurrentAnalyses.end(); I != E; )
196 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
198 ++I; // This analysis is preserved, leave it in the available set...
200 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
201 I = CurrentAnalyses.erase(I); // Analysis not preserved!
203 // GCC 2.95.3 STL doesn't have correct erase member!
204 CurrentAnalyses.erase(I);
205 I = CurrentAnalyses.begin();
210 // Add the current pass to the set of passes that have been run, and are
211 // thus available to users.
213 if (const PassInfo *PI = P->getPassInfo())
214 CurrentAnalyses[PI] = P;
216 // Free memory for any passes that we are the last use of...
217 std::vector<Pass*> &DeadPass = LastUserOf[P];
218 for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
220 PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
222 (*I)->releaseMemory();
228 // dumpPassStructure - Implement the -debug-passes=PassStructure option
229 virtual void dumpPassStructure(unsigned Offset = 0) {
230 std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
231 << " Pass Manager\n";
232 for (typename std::vector<PassClass*>::iterator
233 I = Passes.begin(), E = Passes.end(); I != E; ++I) {
235 P->dumpPassStructure(Offset+1);
237 // Loop through and see which classes are destroyed after this one...
238 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
239 E = LastUseOf.end(); I != E; ++I) {
240 if (P == I->second) {
241 std::cerr << "--" << std::string(Offset*2, ' ');
242 I->first->dumpPassStructure(0);
248 Pass *getAnalysisOrNullDown(AnalysisID ID) const {
249 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
250 if (I == CurrentAnalyses.end()) {
252 return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
258 Pass *getAnalysisOrNullUp(AnalysisID ID) const {
259 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
260 if (I == CurrentAnalyses.end()) {
262 return Parent->getAnalysisOrNullUp(ID);
268 // {start/end}Pass - Called when a pass is started, it just propogates
269 // information up to the top level PassManagerT object to tell it that a pass
270 // has started or ended. This is used to gather timing information about
273 void startPass(Pass *P) {
274 if (Parent) Parent->startPass(P);
277 void endPass(Pass *P) {
278 if (Parent) Parent->endPass(P);
282 // markPassUsed - Inform higher level pass managers (and ourselves)
283 // that these analyses are being used by this pass. This is used to
284 // make sure that analyses are not free'd before we have to use
287 void markPassUsed(AnalysisID P, Pass *User) {
288 std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.find(P);
289 if (I != CurrentAnalyses.end()) {
290 LastUseOf[I->second] = User; // Local pass, extend the lifetime
292 // Pass not in current available set, must be a higher level pass
293 // available to us, propogate to parent pass manager... We tell the
294 // parent that we (the passmanager) are using the analysis so that it
295 // frees the analysis AFTER this pass manager runs.
297 assert(Parent != 0 && "Pass available but not found! "
298 "Did your analysis pass 'Provide' itself?");
299 Parent->markPassUsed(P, this);
303 // Return the number of parent PassManagers that exist
304 virtual unsigned getDepth() const {
305 if (Parent == 0) return 0;
306 return 1 + Parent->getDepth();
309 // add - Add a pass to the queue of passes to run. This passes ownership of
310 // the Pass to the PassManager. When the PassManager is destroyed, the pass
311 // will be destroyed as well, so there is no need to delete the pass. This
312 // implies that all passes MUST be new'd.
314 void add(PassClass *P) {
315 // Get information about what analyses the pass uses...
316 AnalysisUsage AnUsage;
317 P->getAnalysisUsage(AnUsage);
318 const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
320 // Loop over all of the analyses used by this pass,
321 for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
322 E = Required.end(); I != E; ++I) {
323 if (getAnalysisOrNullDown(*I) == 0)
324 add((PassClass*)(*I)->createPass());
327 // Tell the pass to add itself to this PassManager... the way it does so
328 // depends on the class of the pass, and is critical to laying out passes in
329 // an optimal order..
331 P->addToPassManager(this, AnUsage);
336 // addPass - These functions are used to implement the subclass specific
337 // behaviors present in PassManager. Basically the add(Pass*) method ends up
338 // reflecting its behavior into a Pass::addToPassManager call. Subclasses of
339 // Pass override it specifically so that they can reflect the type
340 // information inherent in "this" back to the PassManager.
342 // For generic Pass subclasses (which are interprocedural passes), we simply
343 // add the pass to the end of the pass list and terminate any accumulation of
344 // FunctionPass's that are present.
346 void addPass(PassClass *P, AnalysisUsage &AnUsage) {
347 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
349 // FIXME: If this pass being added isn't killed by any of the passes in the
350 // batcher class then we can reorder to pass to execute before the batcher
351 // does, which will potentially allow us to batch more passes!
353 //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
354 if (Batcher /*&& ProvidedSet.empty()*/)
355 closeBatcher(); // This pass cannot be batched!
357 // Set the Resolver instance variable in the Pass so that it knows where to
358 // find this object...
360 setAnalysisResolver(P, this);
363 // Inform higher level pass managers (and ourselves) that these analyses are
364 // being used by this pass. This is used to make sure that analyses are not
365 // free'd before we have to use them...
367 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
368 E = RequiredSet.end(); I != E; ++I)
369 markPassUsed(*I, P); // Mark *I as used by P
371 // Erase all analyses not in the preserved set...
372 if (!AnUsage.preservesAll()) {
373 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
374 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
375 E = CurrentAnalyses.end(); I != E; )
376 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
378 ++I; // This analysis is preserved, leave it in the available set...
380 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
381 I = CurrentAnalyses.erase(I); // Analysis not preserved!
383 CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
384 I = CurrentAnalyses.begin();
389 // Add this pass to the currently available set...
390 if (const PassInfo *PI = P->getPassInfo())
391 CurrentAnalyses[PI] = P;
393 // For now assume that our results are never used...
397 // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
398 // together in a BatcherClass object so that all of the analyses are run
399 // together a function at a time.
401 void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
402 if (Batcher == 0) // If we don't have a batcher yet, make one now.
403 Batcher = new BatcherClass(this);
404 // The Batcher will queue the passes up
405 MP->addToPassManager(Batcher, AnUsage);
408 // closeBatcher - Terminate the batcher that is being worked on.
409 void closeBatcher() {
411 Passes.push_back(Batcher);
419 //===----------------------------------------------------------------------===//
420 // PassManagerTraits<BasicBlock> Specialization
422 // This pass manager is used to group together all of the BasicBlockPass's
423 // into a single unit.
425 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
426 // PassClass - The type of passes tracked by this PassManager
427 typedef BasicBlockPass PassClass;
429 // SubPassClass - The types of classes that should be collated together
430 // This is impossible to match, so BasicBlock instantiations of PassManagerT
433 typedef PassManagerT<Module> SubPassClass;
435 // BatcherClass - The type to use for collation of subtypes... This class is
436 // never instantiated for the PassManager<BasicBlock>, but it must be an
437 // instance of PassClass to typecheck.
439 typedef PassClass BatcherClass;
441 // ParentClass - The type of the parent PassManager...
442 typedef PassManagerT<Function> ParentClass;
444 // PMType - The type of the passmanager that subclasses this class
445 typedef PassManagerT<BasicBlock> PMType;
447 // runPass - Specify how the pass should be run on the UnitType
448 static bool runPass(PassClass *P, BasicBlock *M) {
449 // todo, init and finalize
450 return P->runOnBasicBlock(*M);
453 // Dummy implementation of PassStarted/PassEnded
454 static void PassStarted(Pass *P) {}
455 static void PassEnded(Pass *P) {}
457 // getPMName() - Return the name of the unit the PassManager operates on for
459 const char *getPMName() const { return "BasicBlock"; }
460 virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
462 // Implement the BasicBlockPass interface...
463 virtual bool doInitialization(Module &M);
464 virtual bool runOnBasicBlock(BasicBlock &BB);
465 virtual bool doFinalization(Module &M);
467 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
468 AU.setPreservesAll();
474 //===----------------------------------------------------------------------===//
475 // PassManagerTraits<Function> Specialization
477 // This pass manager is used to group together all of the FunctionPass's
478 // into a single unit.
480 template<> struct PassManagerTraits<Function> : public FunctionPass {
481 // PassClass - The type of passes tracked by this PassManager
482 typedef FunctionPass PassClass;
484 // SubPassClass - The types of classes that should be collated together
485 typedef BasicBlockPass SubPassClass;
487 // BatcherClass - The type to use for collation of subtypes...
488 typedef PassManagerT<BasicBlock> BatcherClass;
490 // ParentClass - The type of the parent PassManager...
491 typedef PassManagerT<Module> ParentClass;
493 // PMType - The type of the passmanager that subclasses this class
494 typedef PassManagerT<Function> PMType;
496 // runPass - Specify how the pass should be run on the UnitType
497 static bool runPass(PassClass *P, Function *F) {
498 return P->runOnFunction(*F);
501 // Dummy implementation of PassStarted/PassEnded
502 static void PassStarted(Pass *P) {}
503 static void PassEnded(Pass *P) {}
505 // getPMName() - Return the name of the unit the PassManager operates on for
507 const char *getPMName() const { return "Function"; }
508 virtual const char *getPassName() const { return "Function Pass Manager"; }
510 // Implement the FunctionPass interface...
511 virtual bool doInitialization(Module &M);
512 virtual bool runOnFunction(Function &F);
513 virtual bool doFinalization(Module &M);
515 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
516 AU.setPreservesAll();
522 //===----------------------------------------------------------------------===//
523 // PassManagerTraits<Module> Specialization
525 // This is the top level PassManager implementation that holds generic passes.
527 template<> struct PassManagerTraits<Module> : public Pass {
528 // PassClass - The type of passes tracked by this PassManager
529 typedef Pass PassClass;
531 // SubPassClass - The types of classes that should be collated together
532 typedef FunctionPass SubPassClass;
534 // BatcherClass - The type to use for collation of subtypes...
535 typedef PassManagerT<Function> BatcherClass;
537 // ParentClass - The type of the parent PassManager...
538 typedef AnalysisResolver ParentClass;
540 // runPass - Specify how the pass should be run on the UnitType
541 static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
543 // getPMName() - Return the name of the unit the PassManager operates on for
545 const char *getPMName() const { return "Module"; }
546 virtual const char *getPassName() const { return "Module Pass Manager"; }
548 // TimingInformation - This data member maintains timing information for each
549 // of the passes that is executed.
551 TimingInfo *TimeInfo;
553 // PassStarted/Ended - This callback is notified any time a pass is started
554 // or stops. This is used to collect timing information about the different
555 // passes being executed.
557 void PassStarted(Pass *P) {
558 if (TimeInfo) TimeInfo->passStarted(P);
560 void PassEnded(Pass *P) {
561 if (TimeInfo) TimeInfo->passEnded(P);
564 // run - Implement the PassManager interface...
565 bool run(Module &M) {
566 TimeInfo = TimingInfo::create();
567 bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
575 // PassManagerTraits constructor - Create a timing info object if the user
576 // specified timing info should be collected on the command line.
578 PassManagerTraits() : TimeInfo(0) {}
583 //===----------------------------------------------------------------------===//
584 // PassManagerTraits Method Implementations
587 // PassManagerTraits<BasicBlock> Implementations
589 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
590 bool Changed = false;
591 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
592 ((PMType*)this)->Passes[i]->doInitialization(M);
596 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
597 return ((PMType*)this)->runOnUnit(&BB);
600 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
601 bool Changed = false;
602 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
603 ((PMType*)this)->Passes[i]->doFinalization(M);
608 // PassManagerTraits<Function> Implementations
610 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
611 bool Changed = false;
612 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
613 ((PMType*)this)->Passes[i]->doInitialization(M);
617 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
618 return ((PMType*)this)->runOnUnit(&F);
621 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
622 bool Changed = false;
623 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
624 ((PMType*)this)->Passes[i]->doFinalization(M);