555bcaae1062ff60e41df5b3b1c278405d59bc6d
[oota-llvm.git] / lib / VMCore / PassManagerT.h
1 //===- PassManagerT.h - Container for Passes ---------------------*- C++ -*--=//
2 //
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.
7 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_PASSMANAGER_T_H
16 #define LLVM_PASSMANAGER_T_H
17
18 #include "llvm/Pass.h"
19 #include "Support/CommandLine.h"
20 #include <algorithm>
21 class Annotable;
22
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.
28 //
29
30 // Different debug levels that can be enabled...
31 enum PassDebugLevel {
32   None, Structure, Executions, Details
33 };
34
35 static cl::opt<enum PassDebugLevel>
36 PassDebugging("debug-pass", cl::Hidden,
37               cl::desc("Print PassManager debugging information"),
38               cl::values(
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"),
44                          0));
45
46 //===----------------------------------------------------------------------===//
47 // PMDebug class - a set of debugging functions, that are not to be
48 // instantiated by the template.
49 //
50 struct PMDebug {
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.
53   //
54   static void PrintPassStructure(Pass *P) {
55     if (PassDebugging >= Structure)
56       P->dumpPassStructure();
57   }
58   static void PrintPassInformation(unsigned,const char*,Pass *, Annotable *);
59   static void PrintAnalysisSetInfo(unsigned,const char*,Pass *P,
60                                    const std::vector<AnalysisID> &);
61 };
62
63
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.
68 //
69 class TimingInfo {
70   std::map<Pass*, double> TimingData;
71   TimingInfo() {}   // Private ctor, must use create member
72 public:
73   // Create method.  If Timing is enabled, this creates and returns a new timing
74   // object, otherwise it returns null.
75   //
76   static TimingInfo *create();
77
78   // TimingDtor - Print out information about timing information
79   ~TimingInfo();
80
81   void passStarted(Pass *P);
82   void passEnded(Pass *P);
83 };
84
85
86
87 //===----------------------------------------------------------------------===//
88 // Declare the PassManagerTraits which will be specialized...
89 //
90 template<class UnitType> class PassManagerTraits;   // Do not define.
91
92
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.
97 //
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;
105
106   friend typename Traits::PassClass;
107   friend typename Traits::SubPassClass;  
108   friend class Traits;
109
110   std::vector<PassClass*> Passes;    // List of passes to run
111
112   // The parent of this pass manager...
113   ParentClass * const Parent;
114
115   // The current batcher if one is in use, or null
116   BatcherClass *Batcher;
117
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.
121   //
122   std::map<AnalysisID, Pass*> CurrentAnalyses;
123
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.
127   //
128   std::map<Pass*, Pass*> LastUseOf;
129
130 public:
131   PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
132   ~PassManagerT() {
133     // Delete all of the contained passes...
134     for (typename std::vector<PassClass*>::iterator
135            I = Passes.begin(), E = Passes.end(); I != E; ++I)
136       delete *I;
137   }
138
139   // run - Run all of the queued passes on the specified module in an optimal
140   // way.
141   virtual bool runOnUnit(UnitType *M) {
142     bool MadeChanges = false;
143     closeBatcher();
144     CurrentAnalyses.clear();
145
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);
151
152
153     // Output debug information...
154     if (Parent == 0) PMDebug::PrintPassStructure(this);
155
156     // Run all of the passes
157     for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
158       PassClass *P = Passes[i];
159       
160       PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
161                                     (Annotable*)M);
162
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());
168
169 #ifndef NDEBUG
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!");
175       }
176 #endif
177
178       // Run the sub pass!
179       startPass(P);
180       bool Changed = runPass(P, M);
181       endPass(P);
182       MadeChanges |= Changed;
183
184       if (Changed)
185         PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
186                                       (Annotable*)M);
187       PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
188                                     AnUsage.getPreservedSet());
189
190
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) !=
197               PreservedSet.end())
198             ++I; // This analysis is preserved, leave it in the available set...
199           else {
200 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
201             I = CurrentAnalyses.erase(I);   // Analysis not preserved!
202 #else
203             // GCC 2.95.3 STL doesn't have correct erase member!
204             CurrentAnalyses.erase(I);
205             I = CurrentAnalyses.begin();
206 #endif
207           }
208       }
209
210       // Add the current pass to the set of passes that have been run, and are
211       // thus available to users.
212       //
213       if (const PassInfo *PI = P->getPassInfo())
214         CurrentAnalyses[PI] = P;
215
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();
219            I != E; ++I) {
220         PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
221                                       (Annotable*)M);
222         (*I)->releaseMemory();
223       }
224     }
225     return MadeChanges;
226   }
227
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) {
234       PassClass *P = *I;
235       P->dumpPassStructure(Offset+1);
236
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);
243         }
244       }
245     }
246   }
247
248   Pass *getAnalysisOrNullDown(AnalysisID ID) const {
249     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
250     if (I == CurrentAnalyses.end()) {
251       if (Batcher)
252         return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
253       return 0;
254     }
255     return I->second;
256   }
257
258   Pass *getAnalysisOrNullUp(AnalysisID ID) const {
259     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
260     if (I == CurrentAnalyses.end()) {
261       if (Parent)
262         return Parent->getAnalysisOrNullUp(ID);
263       return 0;
264     }
265     return I->second;
266   }
267
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
271   // passes.
272   //
273   void startPass(Pass *P) {
274     if (Parent) Parent->startPass(P);
275     else PassStarted(P);
276   }
277   void endPass(Pass *P) {
278     if (Parent) Parent->endPass(P);
279     else PassEnded(P);
280   }
281
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
285   // them...
286   //
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
291     } else {
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.
296       //
297       assert(Parent != 0 && "Pass available but not found! "
298              "Did your analysis pass 'Provide' itself?");
299       Parent->markPassUsed(P, this);
300     }
301   }
302
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();
307   }
308
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.
313   //
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();
319
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());
325     }
326
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..
330     //
331     P->addToPassManager(this, AnUsage);
332   }
333
334 private:
335
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.
341   //
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.
345   //
346   void addPass(PassClass *P, AnalysisUsage &AnUsage) {
347     const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
348
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!
352     //
353     //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
354     if (Batcher /*&& ProvidedSet.empty()*/)
355       closeBatcher();                     // This pass cannot be batched!
356     
357     // Set the Resolver instance variable in the Pass so that it knows where to 
358     // find this object...
359     //
360     setAnalysisResolver(P, this);
361     Passes.push_back(P);
362
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...
366     //
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
370
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) !=
377             PreservedSet.end())
378           ++I;  // This analysis is preserved, leave it in the available set...
379         else {
380 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
381           I = CurrentAnalyses.erase(I);   // Analysis not preserved!
382 #else
383           CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
384           I = CurrentAnalyses.begin();
385 #endif
386         }
387     }
388
389     // Add this pass to the currently available set...
390     if (const PassInfo *PI = P->getPassInfo())
391       CurrentAnalyses[PI] = P;
392
393     // For now assume that our results are never used...
394     LastUseOf[P] = P;
395   }
396   
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.
400   //
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);
406   }
407
408   // closeBatcher - Terminate the batcher that is being worked on.
409   void closeBatcher() {
410     if (Batcher) {
411       Passes.push_back(Batcher);
412       Batcher = 0;
413     }
414   }
415 };
416
417
418
419 //===----------------------------------------------------------------------===//
420 // PassManagerTraits<BasicBlock> Specialization
421 //
422 // This pass manager is used to group together all of the BasicBlockPass's
423 // into a single unit.
424 //
425 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
426   // PassClass - The type of passes tracked by this PassManager
427   typedef BasicBlockPass PassClass;
428
429   // SubPassClass - The types of classes that should be collated together
430   // This is impossible to match, so BasicBlock instantiations of PassManagerT
431   // do not collate.
432   //
433   typedef PassManagerT<Module> SubPassClass;
434
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.
438   //
439   typedef PassClass BatcherClass;
440
441   // ParentClass - The type of the parent PassManager...
442   typedef PassManagerT<Function> ParentClass;
443
444   // PMType - The type of the passmanager that subclasses this class
445   typedef PassManagerT<BasicBlock> PMType;
446
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);
451   }
452
453   // Dummy implementation of PassStarted/PassEnded
454   static void PassStarted(Pass *P) {}
455   static void PassEnded(Pass *P) {}
456
457   // getPMName() - Return the name of the unit the PassManager operates on for
458   // debugging.
459   const char *getPMName() const { return "BasicBlock"; }
460   virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
461
462   // Implement the BasicBlockPass interface...
463   virtual bool doInitialization(Module &M);
464   virtual bool runOnBasicBlock(BasicBlock &BB);
465   virtual bool doFinalization(Module &M);
466
467   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
468     AU.setPreservesAll();
469   }
470 };
471
472
473
474 //===----------------------------------------------------------------------===//
475 // PassManagerTraits<Function> Specialization
476 //
477 // This pass manager is used to group together all of the FunctionPass's
478 // into a single unit.
479 //
480 template<> struct PassManagerTraits<Function> : public FunctionPass {
481   // PassClass - The type of passes tracked by this PassManager
482   typedef FunctionPass PassClass;
483
484   // SubPassClass - The types of classes that should be collated together
485   typedef BasicBlockPass SubPassClass;
486
487   // BatcherClass - The type to use for collation of subtypes...
488   typedef PassManagerT<BasicBlock> BatcherClass;
489
490   // ParentClass - The type of the parent PassManager...
491   typedef PassManagerT<Module> ParentClass;
492
493   // PMType - The type of the passmanager that subclasses this class
494   typedef PassManagerT<Function> PMType;
495
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);
499   }
500
501   // Dummy implementation of PassStarted/PassEnded
502   static void PassStarted(Pass *P) {}
503   static void PassEnded(Pass *P) {}
504
505   // getPMName() - Return the name of the unit the PassManager operates on for
506   // debugging.
507   const char *getPMName() const { return "Function"; }
508   virtual const char *getPassName() const { return "Function Pass Manager"; }
509
510   // Implement the FunctionPass interface...
511   virtual bool doInitialization(Module &M);
512   virtual bool runOnFunction(Function &F);
513   virtual bool doFinalization(Module &M);
514
515   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
516     AU.setPreservesAll();
517   }
518 };
519
520
521
522 //===----------------------------------------------------------------------===//
523 // PassManagerTraits<Module> Specialization
524 //
525 // This is the top level PassManager implementation that holds generic passes.
526 //
527 template<> struct PassManagerTraits<Module> : public Pass {
528   // PassClass - The type of passes tracked by this PassManager
529   typedef Pass PassClass;
530
531   // SubPassClass - The types of classes that should be collated together
532   typedef FunctionPass SubPassClass;
533
534   // BatcherClass - The type to use for collation of subtypes...
535   typedef PassManagerT<Function> BatcherClass;
536
537   // ParentClass - The type of the parent PassManager...
538   typedef AnalysisResolver ParentClass;
539
540   // runPass - Specify how the pass should be run on the UnitType
541   static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
542
543   // getPMName() - Return the name of the unit the PassManager operates on for
544   // debugging.
545   const char *getPMName() const { return "Module"; }
546   virtual const char *getPassName() const { return "Module Pass Manager"; }
547
548   // TimingInformation - This data member maintains timing information for each
549   // of the passes that is executed.
550   //
551   TimingInfo *TimeInfo;
552
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.
556   //
557   void PassStarted(Pass *P) {
558     if (TimeInfo) TimeInfo->passStarted(P);
559   }
560   void PassEnded(Pass *P) {
561     if (TimeInfo) TimeInfo->passEnded(P);
562   }
563
564   // run - Implement the PassManager interface...
565   bool run(Module &M) {
566     TimeInfo = TimingInfo::create();
567     bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
568     if (TimeInfo) {
569       delete TimeInfo;
570       TimeInfo = 0;
571     }
572     return Result;
573   }
574
575   // PassManagerTraits constructor - Create a timing info object if the user
576   // specified timing info should be collected on the command line.
577   //
578   PassManagerTraits() : TimeInfo(0) {}
579 };
580
581
582
583 //===----------------------------------------------------------------------===//
584 // PassManagerTraits Method Implementations
585 //
586
587 // PassManagerTraits<BasicBlock> Implementations
588 //
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);
593   return Changed;
594 }
595
596 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
597   return ((PMType*)this)->runOnUnit(&BB);
598 }
599
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);
604   return Changed;
605 }
606
607
608 // PassManagerTraits<Function> Implementations
609 //
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);
614   return Changed;
615 }
616
617 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
618   return ((PMType*)this)->runOnUnit(&F);
619 }
620
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);
625   return Changed;
626 }
627
628 #endif