6e5fcbdd3e282887347d0112eb9a8c4f221cf578
[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 <string>
20 #include <algorithm>
21 class Annotable;
22
23 //===----------------------------------------------------------------------===//
24 // PMDebug class - a set of debugging functions, that are not to be
25 // instantiated by the template.
26 //
27 struct PMDebug {
28   // If compiled in debug mode, these functions can be enabled by setting
29   // -debug-pass on the command line of the tool being used.
30   //
31   static void PrintPassStructure(Pass *P);
32   static void PrintPassInformation(unsigned,const char*,Pass *, Annotable *);
33   static void PrintAnalysisSetInfo(unsigned,const char*,Pass *P,
34                                    const std::vector<AnalysisID> &);
35 };
36
37
38 //===----------------------------------------------------------------------===//
39 // TimingInfo Class - This class is used to calculate information about the
40 // amount of time each pass takes to execute.  This only happens when
41 // -time-passes is enabled on the command line.
42 //
43 class TimingInfo {
44   std::map<Pass*, double> TimingData;
45   TimingInfo() {}   // Private ctor, must use create member
46 public:
47   // Create method.  If Timing is enabled, this creates and returns a new timing
48   // object, otherwise it returns null.
49   //
50   static TimingInfo *create();
51
52   // TimingDtor - Print out information about timing information
53   ~TimingInfo();
54
55   void passStarted(Pass *P);
56   void passEnded(Pass *P);
57 };
58
59
60
61 //===----------------------------------------------------------------------===//
62 // Declare the PassManagerTraits which will be specialized...
63 //
64 template<class UnitType> class PassManagerTraits;   // Do not define.
65
66
67 //===----------------------------------------------------------------------===//
68 // PassManagerT - Container object for passes.  The PassManagerT destructor
69 // deletes all passes contained inside of the PassManagerT, so you shouldn't 
70 // delete passes manually, and all passes should be dynamically allocated.
71 //
72 template<typename UnitType>
73 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
74   typedef PassManagerTraits<UnitType> Traits;
75   typedef typename Traits::PassClass       PassClass;
76   typedef typename Traits::SubPassClass SubPassClass;
77   typedef typename Traits::BatcherClass BatcherClass;
78   typedef typename Traits::ParentClass   ParentClass;
79
80   friend typename Traits::PassClass;
81   friend typename Traits::SubPassClass;  
82   friend class Traits;
83
84   std::vector<PassClass*> Passes;    // List of passes to run
85
86   // The parent of this pass manager...
87   ParentClass * const Parent;
88
89   // The current batcher if one is in use, or null
90   BatcherClass *Batcher;
91
92   // CurrentAnalyses - As the passes are being run, this map contains the
93   // analyses that are available to the current pass for use.  This is accessed
94   // through the getAnalysis() function in this class and in Pass.
95   //
96   std::map<AnalysisID, Pass*> CurrentAnalyses;
97
98   // LastUseOf - This map keeps track of the last usage in our pipeline of a
99   // particular pass.  When executing passes, the memory for .first is free'd
100   // after .second is run.
101   //
102   std::map<Pass*, Pass*> LastUseOf;
103
104 public:
105   PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
106   ~PassManagerT() {
107     // Delete all of the contained passes...
108     for (typename std::vector<PassClass*>::iterator
109            I = Passes.begin(), E = Passes.end(); I != E; ++I)
110       delete *I;
111   }
112
113   // run - Run all of the queued passes on the specified module in an optimal
114   // way.
115   virtual bool runOnUnit(UnitType *M) {
116     bool MadeChanges = false;
117     closeBatcher();
118     CurrentAnalyses.clear();
119
120     // LastUserOf - This contains the inverted LastUseOfMap...
121     std::map<Pass *, std::vector<Pass*> > LastUserOf;
122     for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
123                                           E = LastUseOf.end(); I != E; ++I)
124       LastUserOf[I->second].push_back(I->first);
125
126
127     // Output debug information...
128     if (Parent == 0) PMDebug::PrintPassStructure(this);
129
130     // Run all of the passes
131     for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
132       PassClass *P = Passes[i];
133       
134       PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
135                                     (Annotable*)M);
136
137       // Get information about what analyses the pass uses...
138       AnalysisUsage AnUsage;
139       P->getAnalysisUsage(AnUsage);
140       PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
141                                     AnUsage.getRequiredSet());
142
143 #ifndef NDEBUG
144       // All Required analyses should be available to the pass as it runs!
145       for (std::vector<AnalysisID>::const_iterator
146              I = AnUsage.getRequiredSet().begin(), 
147              E = AnUsage.getRequiredSet().end(); I != E; ++I) {
148         assert(getAnalysisOrNullUp(*I) && "Analysis used but not available!");
149       }
150 #endif
151
152       // Run the sub pass!
153       startPass(P);
154       bool Changed = runPass(P, M);
155       endPass(P);
156       MadeChanges |= Changed;
157
158       if (Changed)
159         PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
160                                       (Annotable*)M);
161       PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
162                                     AnUsage.getPreservedSet());
163
164
165       // Erase all analyses not in the preserved set...
166       if (!AnUsage.preservesAll()) {
167         const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
168         for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
169                E = CurrentAnalyses.end(); I != E; )
170           if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
171               PreservedSet.end())
172             ++I; // This analysis is preserved, leave it in the available set...
173           else {
174 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
175             I = CurrentAnalyses.erase(I);   // Analysis not preserved!
176 #else
177             // GCC 2.95.3 STL doesn't have correct erase member!
178             CurrentAnalyses.erase(I);
179             I = CurrentAnalyses.begin();
180 #endif
181           }
182       }
183
184       // Add the current pass to the set of passes that have been run, and are
185       // thus available to users.
186       //
187       if (const PassInfo *PI = P->getPassInfo())
188         CurrentAnalyses[PI] = P;
189
190       // Free memory for any passes that we are the last use of...
191       std::vector<Pass*> &DeadPass = LastUserOf[P];
192       for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
193            I != E; ++I) {
194         PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
195                                       (Annotable*)M);
196         (*I)->releaseMemory();
197       }
198     }
199     return MadeChanges;
200   }
201
202   // dumpPassStructure - Implement the -debug-passes=PassStructure option
203   virtual void dumpPassStructure(unsigned Offset = 0) {
204     std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
205               << " Pass Manager\n";
206     for (typename std::vector<PassClass*>::iterator
207            I = Passes.begin(), E = Passes.end(); I != E; ++I) {
208       PassClass *P = *I;
209       P->dumpPassStructure(Offset+1);
210
211       // Loop through and see which classes are destroyed after this one...
212       for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
213                                             E = LastUseOf.end(); I != E; ++I) {
214         if (P == I->second) {
215           std::cerr << "--" << std::string(Offset*2, ' ');
216           I->first->dumpPassStructure(0);
217         }
218       }
219     }
220   }
221
222   Pass *getAnalysisOrNullDown(AnalysisID ID) const {
223     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
224     if (I == CurrentAnalyses.end()) {
225       if (Batcher)
226         return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
227       return 0;
228     }
229     return I->second;
230   }
231
232   Pass *getAnalysisOrNullUp(AnalysisID ID) const {
233     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
234     if (I == CurrentAnalyses.end()) {
235       if (Parent)
236         return Parent->getAnalysisOrNullUp(ID);
237       return 0;
238     }
239     return I->second;
240   }
241
242   // {start/end}Pass - Called when a pass is started, it just propogates
243   // information up to the top level PassManagerT object to tell it that a pass
244   // has started or ended.  This is used to gather timing information about
245   // passes.
246   //
247   void startPass(Pass *P) {
248     if (Parent) Parent->startPass(P);
249     else PassStarted(P);
250   }
251   void endPass(Pass *P) {
252     if (Parent) Parent->endPass(P);
253     else PassEnded(P);
254   }
255
256   // markPassUsed - Inform higher level pass managers (and ourselves)
257   // that these analyses are being used by this pass.  This is used to
258   // make sure that analyses are not free'd before we have to use
259   // them...
260   //
261   void markPassUsed(AnalysisID P, Pass *User) {
262     std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.find(P);
263     if (I != CurrentAnalyses.end()) {
264       LastUseOf[I->second] = User;    // Local pass, extend the lifetime
265     } else {
266       // Pass not in current available set, must be a higher level pass
267       // available to us, propogate to parent pass manager...  We tell the
268       // parent that we (the passmanager) are using the analysis so that it
269       // frees the analysis AFTER this pass manager runs.
270       //
271       assert(Parent != 0 && "Pass available but not found! "
272              "Did your analysis pass 'Provide' itself?");
273       Parent->markPassUsed(P, this);
274     }
275   }
276
277   // Return the number of parent PassManagers that exist
278   virtual unsigned getDepth() const {
279     if (Parent == 0) return 0;
280     return 1 + Parent->getDepth();
281   }
282
283   // add - Add a pass to the queue of passes to run.  This passes ownership of
284   // the Pass to the PassManager.  When the PassManager is destroyed, the pass
285   // will be destroyed as well, so there is no need to delete the pass.  This
286   // implies that all passes MUST be new'd.
287   //
288   void add(PassClass *P) {
289     // Get information about what analyses the pass uses...
290     AnalysisUsage AnUsage;
291     P->getAnalysisUsage(AnUsage);
292     const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
293
294     // Loop over all of the analyses used by this pass,
295     for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
296            E = Required.end(); I != E; ++I) {
297       if (getAnalysisOrNullDown(*I) == 0)
298         add((PassClass*)(*I)->createPass());
299     }
300
301     // Tell the pass to add itself to this PassManager... the way it does so
302     // depends on the class of the pass, and is critical to laying out passes in
303     // an optimal order..
304     //
305     P->addToPassManager(this, AnUsage);
306   }
307
308 private:
309
310   // addPass - These functions are used to implement the subclass specific
311   // behaviors present in PassManager.  Basically the add(Pass*) method ends up
312   // reflecting its behavior into a Pass::addToPassManager call.  Subclasses of
313   // Pass override it specifically so that they can reflect the type
314   // information inherent in "this" back to the PassManager.
315   //
316   // For generic Pass subclasses (which are interprocedural passes), we simply
317   // add the pass to the end of the pass list and terminate any accumulation of
318   // FunctionPass's that are present.
319   //
320   void addPass(PassClass *P, AnalysisUsage &AnUsage) {
321     const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
322
323     // FIXME: If this pass being added isn't killed by any of the passes in the
324     // batcher class then we can reorder to pass to execute before the batcher
325     // does, which will potentially allow us to batch more passes!
326     //
327     //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
328     if (Batcher /*&& ProvidedSet.empty()*/)
329       closeBatcher();                     // This pass cannot be batched!
330     
331     // Set the Resolver instance variable in the Pass so that it knows where to 
332     // find this object...
333     //
334     setAnalysisResolver(P, this);
335     Passes.push_back(P);
336
337     // Inform higher level pass managers (and ourselves) that these analyses are
338     // being used by this pass.  This is used to make sure that analyses are not
339     // free'd before we have to use them...
340     //
341     for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
342            E = RequiredSet.end(); I != E; ++I)
343       markPassUsed(*I, P);     // Mark *I as used by P
344
345     // Erase all analyses not in the preserved set...
346     if (!AnUsage.preservesAll()) {
347       const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
348       for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
349              E = CurrentAnalyses.end(); I != E; )
350         if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
351             PreservedSet.end())
352           ++I;  // This analysis is preserved, leave it in the available set...
353         else {
354 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
355           I = CurrentAnalyses.erase(I);   // Analysis not preserved!
356 #else
357           CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
358           I = CurrentAnalyses.begin();
359 #endif
360         }
361     }
362
363     // Add this pass to the currently available set...
364     if (const PassInfo *PI = P->getPassInfo())
365       CurrentAnalyses[PI] = P;
366
367     // For now assume that our results are never used...
368     LastUseOf[P] = P;
369   }
370   
371   // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
372   // together in a BatcherClass object so that all of the analyses are run
373   // together a function at a time.
374   //
375   void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
376     if (Batcher == 0) // If we don't have a batcher yet, make one now.
377       Batcher = new BatcherClass(this);
378     // The Batcher will queue the passes up
379     MP->addToPassManager(Batcher, AnUsage);
380   }
381
382   // closeBatcher - Terminate the batcher that is being worked on.
383   void closeBatcher() {
384     if (Batcher) {
385       Passes.push_back(Batcher);
386       Batcher = 0;
387     }
388   }
389 };
390
391
392
393 //===----------------------------------------------------------------------===//
394 // PassManagerTraits<BasicBlock> Specialization
395 //
396 // This pass manager is used to group together all of the BasicBlockPass's
397 // into a single unit.
398 //
399 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
400   // PassClass - The type of passes tracked by this PassManager
401   typedef BasicBlockPass PassClass;
402
403   // SubPassClass - The types of classes that should be collated together
404   // This is impossible to match, so BasicBlock instantiations of PassManagerT
405   // do not collate.
406   //
407   typedef PassManagerT<Module> SubPassClass;
408
409   // BatcherClass - The type to use for collation of subtypes... This class is
410   // never instantiated for the PassManager<BasicBlock>, but it must be an 
411   // instance of PassClass to typecheck.
412   //
413   typedef PassClass BatcherClass;
414
415   // ParentClass - The type of the parent PassManager...
416   typedef PassManagerT<Function> ParentClass;
417
418   // PMType - The type of the passmanager that subclasses this class
419   typedef PassManagerT<BasicBlock> PMType;
420
421   // runPass - Specify how the pass should be run on the UnitType
422   static bool runPass(PassClass *P, BasicBlock *M) {
423     // todo, init and finalize
424     return P->runOnBasicBlock(*M);
425   }
426
427   // Dummy implementation of PassStarted/PassEnded
428   static void PassStarted(Pass *P) {}
429   static void PassEnded(Pass *P) {}
430
431   // getPMName() - Return the name of the unit the PassManager operates on for
432   // debugging.
433   const char *getPMName() const { return "BasicBlock"; }
434   virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
435
436   // Implement the BasicBlockPass interface...
437   virtual bool doInitialization(Module &M);
438   virtual bool runOnBasicBlock(BasicBlock &BB);
439   virtual bool doFinalization(Module &M);
440
441   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
442     AU.setPreservesAll();
443   }
444 };
445
446
447
448 //===----------------------------------------------------------------------===//
449 // PassManagerTraits<Function> Specialization
450 //
451 // This pass manager is used to group together all of the FunctionPass's
452 // into a single unit.
453 //
454 template<> struct PassManagerTraits<Function> : public FunctionPass {
455   // PassClass - The type of passes tracked by this PassManager
456   typedef FunctionPass PassClass;
457
458   // SubPassClass - The types of classes that should be collated together
459   typedef BasicBlockPass SubPassClass;
460
461   // BatcherClass - The type to use for collation of subtypes...
462   typedef PassManagerT<BasicBlock> BatcherClass;
463
464   // ParentClass - The type of the parent PassManager...
465   typedef PassManagerT<Module> ParentClass;
466
467   // PMType - The type of the passmanager that subclasses this class
468   typedef PassManagerT<Function> PMType;
469
470   // runPass - Specify how the pass should be run on the UnitType
471   static bool runPass(PassClass *P, Function *F) {
472     return P->runOnFunction(*F);
473   }
474
475   // Dummy implementation of PassStarted/PassEnded
476   static void PassStarted(Pass *P) {}
477   static void PassEnded(Pass *P) {}
478
479   // getPMName() - Return the name of the unit the PassManager operates on for
480   // debugging.
481   const char *getPMName() const { return "Function"; }
482   virtual const char *getPassName() const { return "Function Pass Manager"; }
483
484   // Implement the FunctionPass interface...
485   virtual bool doInitialization(Module &M);
486   virtual bool runOnFunction(Function &F);
487   virtual bool doFinalization(Module &M);
488
489   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
490     AU.setPreservesAll();
491   }
492 };
493
494
495
496 //===----------------------------------------------------------------------===//
497 // PassManagerTraits<Module> Specialization
498 //
499 // This is the top level PassManager implementation that holds generic passes.
500 //
501 template<> struct PassManagerTraits<Module> : public Pass {
502   // PassClass - The type of passes tracked by this PassManager
503   typedef Pass PassClass;
504
505   // SubPassClass - The types of classes that should be collated together
506   typedef FunctionPass SubPassClass;
507
508   // BatcherClass - The type to use for collation of subtypes...
509   typedef PassManagerT<Function> BatcherClass;
510
511   // ParentClass - The type of the parent PassManager...
512   typedef AnalysisResolver ParentClass;
513
514   // runPass - Specify how the pass should be run on the UnitType
515   static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
516
517   // getPMName() - Return the name of the unit the PassManager operates on for
518   // debugging.
519   const char *getPMName() const { return "Module"; }
520   virtual const char *getPassName() const { return "Module Pass Manager"; }
521
522   // TimingInformation - This data member maintains timing information for each
523   // of the passes that is executed.
524   //
525   TimingInfo *TimeInfo;
526
527   // PassStarted/Ended - This callback is notified any time a pass is started
528   // or stops.  This is used to collect timing information about the different
529   // passes being executed.
530   //
531   void PassStarted(Pass *P) {
532     if (TimeInfo) TimeInfo->passStarted(P);
533   }
534   void PassEnded(Pass *P) {
535     if (TimeInfo) TimeInfo->passEnded(P);
536   }
537
538   // run - Implement the PassManager interface...
539   bool run(Module &M) {
540     TimeInfo = TimingInfo::create();
541     bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
542     if (TimeInfo) {
543       delete TimeInfo;
544       TimeInfo = 0;
545     }
546     return Result;
547   }
548
549   // PassManagerTraits constructor - Create a timing info object if the user
550   // specified timing info should be collected on the command line.
551   //
552   PassManagerTraits() : TimeInfo(0) {}
553 };
554
555
556
557 //===----------------------------------------------------------------------===//
558 // PassManagerTraits Method Implementations
559 //
560
561 // PassManagerTraits<BasicBlock> Implementations
562 //
563 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
564   bool Changed = false;
565   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
566     ((PMType*)this)->Passes[i]->doInitialization(M);
567   return Changed;
568 }
569
570 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
571   return ((PMType*)this)->runOnUnit(&BB);
572 }
573
574 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
575   bool Changed = false;
576   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
577     ((PMType*)this)->Passes[i]->doFinalization(M);
578   return Changed;
579 }
580
581
582 // PassManagerTraits<Function> Implementations
583 //
584 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
585   bool Changed = false;
586   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
587     ((PMType*)this)->Passes[i]->doInitialization(M);
588   return Changed;
589 }
590
591 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
592   return ((PMType*)this)->runOnUnit(&F);
593 }
594
595 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
596   bool Changed = false;
597   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
598     ((PMType*)this)->Passes[i]->doFinalization(M);
599   return Changed;
600 }
601
602 #endif