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.
77 struct TimeRecord { // TimeRecord - Data we collect and print for each pass
78 double Elapsed; // Wall clock time elapsed in seconds
79 double UserTime; // User time elapsed
80 double SystemTime; // System time elapsed
81 unsigned long MaxRSS; // Maximum resident set size (in bytes)
82 unsigned long RSSTemp; // Temp for calculating maxrss
84 TimeRecord() : Elapsed(0), UserTime(0), SystemTime(0), MaxRSS(0) {}
85 void passStart(const TimeRecord &T);
86 void passEnd(const TimeRecord &T);
87 void sum(const TimeRecord &TR);
88 bool operator<(const TimeRecord &TR) const;
90 void print(const char *PassName, const TimeRecord &TotalTime) const;
94 std::map<Pass*, TimeRecord> TimingData;
95 TimingInfo() {} // Private ctor, must use create member
97 // Create method. If Timing is enabled, this creates and returns a new timing
98 // object, otherwise it returns null.
100 static TimingInfo *create();
102 // TimingDtor - Print out information about timing information
105 void passStarted(Pass *P);
106 void passEnded(Pass *P);
111 //===----------------------------------------------------------------------===//
112 // Declare the PassManagerTraits which will be specialized...
114 template<class UnitType> class PassManagerTraits; // Do not define.
117 //===----------------------------------------------------------------------===//
118 // PassManagerT - Container object for passes. The PassManagerT destructor
119 // deletes all passes contained inside of the PassManagerT, so you shouldn't
120 // delete passes manually, and all passes should be dynamically allocated.
122 template<typename UnitType>
123 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
124 typedef PassManagerTraits<UnitType> Traits;
125 typedef typename Traits::PassClass PassClass;
126 typedef typename Traits::SubPassClass SubPassClass;
127 typedef typename Traits::BatcherClass BatcherClass;
128 typedef typename Traits::ParentClass ParentClass;
130 friend typename Traits::PassClass;
131 friend typename Traits::SubPassClass;
134 std::vector<PassClass*> Passes; // List of passes to run
136 // The parent of this pass manager...
137 ParentClass * const Parent;
139 // The current batcher if one is in use, or null
140 BatcherClass *Batcher;
142 // CurrentAnalyses - As the passes are being run, this map contains the
143 // analyses that are available to the current pass for use. This is accessed
144 // through the getAnalysis() function in this class and in Pass.
146 std::map<AnalysisID, Pass*> CurrentAnalyses;
148 // LastUseOf - This map keeps track of the last usage in our pipeline of a
149 // particular pass. When executing passes, the memory for .first is free'd
150 // after .second is run.
152 std::map<Pass*, Pass*> LastUseOf;
155 PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
157 // Delete all of the contained passes...
158 for (typename std::vector<PassClass*>::iterator
159 I = Passes.begin(), E = Passes.end(); I != E; ++I)
163 // run - Run all of the queued passes on the specified module in an optimal
165 virtual bool runOnUnit(UnitType *M) {
166 bool MadeChanges = false;
168 CurrentAnalyses.clear();
170 // LastUserOf - This contains the inverted LastUseOfMap...
171 std::map<Pass *, std::vector<Pass*> > LastUserOf;
172 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
173 E = LastUseOf.end(); I != E; ++I)
174 LastUserOf[I->second].push_back(I->first);
177 // Output debug information...
178 if (Parent == 0) PMDebug::PerformPassStartupStuff(this);
180 // Run all of the passes
181 for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
182 PassClass *P = Passes[i];
184 PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
187 // Get information about what analyses the pass uses...
188 AnalysisUsage AnUsage;
189 P->getAnalysisUsage(AnUsage);
190 PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
191 AnUsage.getRequiredSet());
194 // All Required analyses should be available to the pass as it runs!
195 for (std::vector<AnalysisID>::const_iterator
196 I = AnUsage.getRequiredSet().begin(),
197 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
198 assert(getAnalysisOrNullUp(*I) && "Analysis used but not available!");
204 bool Changed = runPass(P, M);
206 MadeChanges |= Changed;
209 PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
211 PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
212 AnUsage.getPreservedSet());
215 // Erase all analyses not in the preserved set...
216 if (!AnUsage.preservesAll()) {
217 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
218 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
219 E = CurrentAnalyses.end(); I != E; )
220 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
222 ++I; // This analysis is preserved, leave it in the available set...
224 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
225 I = CurrentAnalyses.erase(I); // Analysis not preserved!
227 // GCC 2.95.3 STL doesn't have correct erase member!
228 CurrentAnalyses.erase(I);
229 I = CurrentAnalyses.begin();
234 // Add the current pass to the set of passes that have been run, and are
235 // thus available to users.
237 if (const PassInfo *PI = P->getPassInfo())
238 CurrentAnalyses[PI] = P;
240 // Free memory for any passes that we are the last use of...
241 std::vector<Pass*> &DeadPass = LastUserOf[P];
242 for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
244 PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
246 (*I)->releaseMemory();
252 // dumpPassStructure - Implement the -debug-passes=PassStructure option
253 virtual void dumpPassStructure(unsigned Offset = 0) {
254 std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
255 << " Pass Manager\n";
256 for (typename std::vector<PassClass*>::iterator
257 I = Passes.begin(), E = Passes.end(); I != E; ++I) {
259 P->dumpPassStructure(Offset+1);
261 // Loop through and see which classes are destroyed after this one...
262 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
263 E = LastUseOf.end(); I != E; ++I) {
264 if (P == I->second) {
265 std::cerr << "--" << std::string(Offset*2, ' ');
266 I->first->dumpPassStructure(0);
272 Pass *getAnalysisOrNullDown(AnalysisID ID) const {
273 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
274 if (I == CurrentAnalyses.end()) {
276 return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
282 Pass *getAnalysisOrNullUp(AnalysisID ID) const {
283 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
284 if (I == CurrentAnalyses.end()) {
286 return Parent->getAnalysisOrNullUp(ID);
292 // {start/end}Pass - Called when a pass is started, it just propogates
293 // information up to the top level PassManagerT object to tell it that a pass
294 // has started or ended. This is used to gather timing information about
297 void startPass(Pass *P) {
298 if (Parent) Parent->startPass(P);
301 void endPass(Pass *P) {
302 if (Parent) Parent->endPass(P);
306 // markPassUsed - Inform higher level pass managers (and ourselves)
307 // that these analyses are being used by this pass. This is used to
308 // make sure that analyses are not free'd before we have to use
311 void markPassUsed(AnalysisID P, Pass *User) {
312 std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.find(P);
313 if (I != CurrentAnalyses.end()) {
314 LastUseOf[I->second] = User; // Local pass, extend the lifetime
316 // Pass not in current available set, must be a higher level pass
317 // available to us, propogate to parent pass manager... We tell the
318 // parent that we (the passmanager) are using the analysis so that it
319 // frees the analysis AFTER this pass manager runs.
321 assert(Parent != 0 && "Pass available but not found! "
322 "Did your analysis pass 'Provide' itself?");
323 Parent->markPassUsed(P, this);
327 // Return the number of parent PassManagers that exist
328 virtual unsigned getDepth() const {
329 if (Parent == 0) return 0;
330 return 1 + Parent->getDepth();
333 virtual unsigned getNumContainedPasses() const { return Passes.size(); }
334 virtual const Pass *getContainedPass(unsigned N) const {
335 assert(N < Passes.size() && "Pass number out of range!");
339 // add - Add a pass to the queue of passes to run. This passes ownership of
340 // the Pass to the PassManager. When the PassManager is destroyed, the pass
341 // will be destroyed as well, so there is no need to delete the pass. This
342 // implies that all passes MUST be new'd.
344 void add(PassClass *P) {
345 // Get information about what analyses the pass uses...
346 AnalysisUsage AnUsage;
347 P->getAnalysisUsage(AnUsage);
348 const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
350 // Loop over all of the analyses used by this pass,
351 for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
352 E = Required.end(); I != E; ++I) {
353 if (getAnalysisOrNullDown(*I) == 0)
354 add((PassClass*)(*I)->createPass());
357 // Tell the pass to add itself to this PassManager... the way it does so
358 // depends on the class of the pass, and is critical to laying out passes in
359 // an optimal order..
361 P->addToPassManager(this, AnUsage);
366 // addPass - These functions are used to implement the subclass specific
367 // behaviors present in PassManager. Basically the add(Pass*) method ends up
368 // reflecting its behavior into a Pass::addToPassManager call. Subclasses of
369 // Pass override it specifically so that they can reflect the type
370 // information inherent in "this" back to the PassManager.
372 // For generic Pass subclasses (which are interprocedural passes), we simply
373 // add the pass to the end of the pass list and terminate any accumulation of
374 // FunctionPass's that are present.
376 void addPass(PassClass *P, AnalysisUsage &AnUsage) {
377 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
379 // FIXME: If this pass being added isn't killed by any of the passes in the
380 // batcher class then we can reorder to pass to execute before the batcher
381 // does, which will potentially allow us to batch more passes!
383 //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
384 if (Batcher /*&& ProvidedSet.empty()*/)
385 closeBatcher(); // This pass cannot be batched!
387 // Set the Resolver instance variable in the Pass so that it knows where to
388 // find this object...
390 setAnalysisResolver(P, this);
393 // Inform higher level pass managers (and ourselves) that these analyses are
394 // being used by this pass. This is used to make sure that analyses are not
395 // free'd before we have to use them...
397 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
398 E = RequiredSet.end(); I != E; ++I)
399 markPassUsed(*I, P); // Mark *I as used by P
401 // Erase all analyses not in the preserved set...
402 if (!AnUsage.preservesAll()) {
403 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
404 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
405 E = CurrentAnalyses.end(); I != E; )
406 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
408 ++I; // This analysis is preserved, leave it in the available set...
410 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
411 I = CurrentAnalyses.erase(I); // Analysis not preserved!
413 CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
414 I = CurrentAnalyses.begin();
419 // Add this pass to the currently available set...
420 if (const PassInfo *PI = P->getPassInfo())
421 CurrentAnalyses[PI] = P;
423 // For now assume that our results are never used...
427 // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
428 // together in a BatcherClass object so that all of the analyses are run
429 // together a function at a time.
431 void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
432 if (Batcher == 0) // If we don't have a batcher yet, make one now.
433 Batcher = new BatcherClass(this);
434 // The Batcher will queue the passes up
435 MP->addToPassManager(Batcher, AnUsage);
438 // closeBatcher - Terminate the batcher that is being worked on.
439 void closeBatcher() {
441 Passes.push_back(Batcher);
449 //===----------------------------------------------------------------------===//
450 // PassManagerTraits<BasicBlock> Specialization
452 // This pass manager is used to group together all of the BasicBlockPass's
453 // into a single unit.
455 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
456 // PassClass - The type of passes tracked by this PassManager
457 typedef BasicBlockPass PassClass;
459 // SubPassClass - The types of classes that should be collated together
460 // This is impossible to match, so BasicBlock instantiations of PassManagerT
463 typedef PassManagerT<Module> SubPassClass;
465 // BatcherClass - The type to use for collation of subtypes... This class is
466 // never instantiated for the PassManager<BasicBlock>, but it must be an
467 // instance of PassClass to typecheck.
469 typedef PassClass BatcherClass;
471 // ParentClass - The type of the parent PassManager...
472 typedef PassManagerT<Function> ParentClass;
474 // PMType - The type of the passmanager that subclasses this class
475 typedef PassManagerT<BasicBlock> PMType;
477 // runPass - Specify how the pass should be run on the UnitType
478 static bool runPass(PassClass *P, BasicBlock *M) {
479 // todo, init and finalize
480 return P->runOnBasicBlock(*M);
483 // Dummy implementation of PassStarted/PassEnded
484 static void PassStarted(Pass *P) {}
485 static void PassEnded(Pass *P) {}
487 // getPMName() - Return the name of the unit the PassManager operates on for
489 const char *getPMName() const { return "BasicBlock"; }
490 virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
492 // Implement the BasicBlockPass interface...
493 virtual bool doInitialization(Module &M);
494 virtual bool runOnBasicBlock(BasicBlock &BB);
495 virtual bool doFinalization(Module &M);
497 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
498 AU.setPreservesAll();
504 //===----------------------------------------------------------------------===//
505 // PassManagerTraits<Function> Specialization
507 // This pass manager is used to group together all of the FunctionPass's
508 // into a single unit.
510 template<> struct PassManagerTraits<Function> : public FunctionPass {
511 // PassClass - The type of passes tracked by this PassManager
512 typedef FunctionPass PassClass;
514 // SubPassClass - The types of classes that should be collated together
515 typedef BasicBlockPass SubPassClass;
517 // BatcherClass - The type to use for collation of subtypes...
518 typedef PassManagerT<BasicBlock> BatcherClass;
520 // ParentClass - The type of the parent PassManager...
521 typedef PassManagerT<Module> ParentClass;
523 // PMType - The type of the passmanager that subclasses this class
524 typedef PassManagerT<Function> PMType;
526 // runPass - Specify how the pass should be run on the UnitType
527 static bool runPass(PassClass *P, Function *F) {
528 return P->runOnFunction(*F);
531 // Dummy implementation of PassStarted/PassEnded
532 static void PassStarted(Pass *P) {}
533 static void PassEnded(Pass *P) {}
535 // getPMName() - Return the name of the unit the PassManager operates on for
537 const char *getPMName() const { return "Function"; }
538 virtual const char *getPassName() const { return "Function Pass Manager"; }
540 // Implement the FunctionPass interface...
541 virtual bool doInitialization(Module &M);
542 virtual bool runOnFunction(Function &F);
543 virtual bool doFinalization(Module &M);
545 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
546 AU.setPreservesAll();
552 //===----------------------------------------------------------------------===//
553 // PassManagerTraits<Module> Specialization
555 // This is the top level PassManager implementation that holds generic passes.
557 template<> struct PassManagerTraits<Module> : public Pass {
558 // PassClass - The type of passes tracked by this PassManager
559 typedef Pass PassClass;
561 // SubPassClass - The types of classes that should be collated together
562 typedef FunctionPass SubPassClass;
564 // BatcherClass - The type to use for collation of subtypes...
565 typedef PassManagerT<Function> BatcherClass;
567 // ParentClass - The type of the parent PassManager...
568 typedef AnalysisResolver ParentClass;
570 // runPass - Specify how the pass should be run on the UnitType
571 static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
573 // getPMName() - Return the name of the unit the PassManager operates on for
575 const char *getPMName() const { return "Module"; }
576 virtual const char *getPassName() const { return "Module Pass Manager"; }
578 // TimingInformation - This data member maintains timing information for each
579 // of the passes that is executed.
581 TimingInfo *TimeInfo;
583 // PassStarted/Ended - This callback is notified any time a pass is started
584 // or stops. This is used to collect timing information about the different
585 // passes being executed.
587 void PassStarted(Pass *P) {
588 if (TimeInfo) TimeInfo->passStarted(P);
590 void PassEnded(Pass *P) {
591 if (TimeInfo) TimeInfo->passEnded(P);
594 // run - Implement the PassManager interface...
595 bool run(Module &M) {
596 TimeInfo = TimingInfo::create();
597 bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
605 // PassManagerTraits constructor - Create a timing info object if the user
606 // specified timing info should be collected on the command line.
608 PassManagerTraits() : TimeInfo(0) {}
613 //===----------------------------------------------------------------------===//
614 // PassManagerTraits Method Implementations
617 // PassManagerTraits<BasicBlock> Implementations
619 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
620 bool Changed = false;
621 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
622 ((PMType*)this)->Passes[i]->doInitialization(M);
626 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
627 return ((PMType*)this)->runOnUnit(&BB);
630 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
631 bool Changed = false;
632 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
633 ((PMType*)this)->Passes[i]->doFinalization(M);
638 // PassManagerTraits<Function> Implementations
640 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
641 bool Changed = false;
642 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
643 ((PMType*)this)->Passes[i]->doInitialization(M);
647 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
648 return ((PMType*)this)->runOnUnit(&F);
651 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
652 bool Changed = false;
653 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
654 ((PMType*)this)->Passes[i]->doFinalization(M);