3f2dc76f5140bb5d567afd6055f9910aac69bbc5
[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 #include <iostream>
22 class Annotable;
23
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.
29 //
30
31 // Different debug levels that can be enabled...
32 enum PassDebugLevel {
33   None, Arguments, Structure, Executions, Details
34 };
35
36 static cl::opt<enum PassDebugLevel>
37 PassDebugging("debug-pass", cl::Hidden,
38               cl::desc("Print PassManager debugging information"),
39               cl::values(
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"),
45                          0));
46
47 //===----------------------------------------------------------------------===//
48 // PMDebug class - a set of debugging functions, that are not to be
49 // instantiated by the template.
50 //
51 struct PMDebug {
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);
57       std::cerr << "\n";
58
59       // Print the pass execution structure
60       if (PassDebugging >= Structure)
61         P->dumpPassStructure();
62     }
63   }
64
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> &);
69 };
70
71
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.
76 //
77 class TimingInfo {
78   std::map<Pass*, double> TimingData;
79   TimingInfo() {}   // Private ctor, must use create member
80 public:
81   // Create method.  If Timing is enabled, this creates and returns a new timing
82   // object, otherwise it returns null.
83   //
84   static TimingInfo *create();
85
86   // TimingDtor - Print out information about timing information
87   ~TimingInfo();
88
89   void passStarted(Pass *P);
90   void passEnded(Pass *P);
91 };
92
93
94
95 //===----------------------------------------------------------------------===//
96 // Declare the PassManagerTraits which will be specialized...
97 //
98 template<class UnitType> class PassManagerTraits;   // Do not define.
99
100
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.
105 //
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;
113
114   friend typename Traits::PassClass;
115   friend typename Traits::SubPassClass;  
116   friend class Traits;
117
118   std::vector<PassClass*> Passes;    // List of passes to run
119
120   // The parent of this pass manager...
121   ParentClass * const Parent;
122
123   // The current batcher if one is in use, or null
124   BatcherClass *Batcher;
125
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.
129   //
130   std::map<AnalysisID, Pass*> CurrentAnalyses;
131
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.
135   //
136   std::map<Pass*, Pass*> LastUseOf;
137
138 public:
139   PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
140   ~PassManagerT() {
141     // Delete all of the contained passes...
142     for (typename std::vector<PassClass*>::iterator
143            I = Passes.begin(), E = Passes.end(); I != E; ++I)
144       delete *I;
145   }
146
147   // run - Run all of the queued passes on the specified module in an optimal
148   // way.
149   virtual bool runOnUnit(UnitType *M) {
150     bool MadeChanges = false;
151     closeBatcher();
152     CurrentAnalyses.clear();
153
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);
159
160
161     // Output debug information...
162     if (Parent == 0) PMDebug::PerformPassStartupStuff(this);
163
164     // Run all of the passes
165     for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
166       PassClass *P = Passes[i];
167       
168       PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
169                                     (Annotable*)M);
170
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());
176
177 #ifndef NDEBUG
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!");
183       }
184 #endif
185
186       // Run the sub pass!
187       startPass(P);
188       bool Changed = runPass(P, M);
189       endPass(P);
190       MadeChanges |= Changed;
191
192       if (Changed)
193         PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
194                                       (Annotable*)M);
195       PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
196                                     AnUsage.getPreservedSet());
197
198
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) !=
205               PreservedSet.end())
206             ++I; // This analysis is preserved, leave it in the available set...
207           else {
208 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
209             I = CurrentAnalyses.erase(I);   // Analysis not preserved!
210 #else
211             // GCC 2.95.3 STL doesn't have correct erase member!
212             CurrentAnalyses.erase(I);
213             I = CurrentAnalyses.begin();
214 #endif
215           }
216       }
217
218       // Add the current pass to the set of passes that have been run, and are
219       // thus available to users.
220       //
221       if (const PassInfo *PI = P->getPassInfo())
222         CurrentAnalyses[PI] = P;
223
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();
227            I != E; ++I) {
228         PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
229                                       (Annotable*)M);
230         (*I)->releaseMemory();
231       }
232     }
233     return MadeChanges;
234   }
235
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) {
242       PassClass *P = *I;
243       P->dumpPassStructure(Offset+1);
244
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);
251         }
252       }
253     }
254   }
255
256   Pass *getAnalysisOrNullDown(AnalysisID ID) const {
257     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
258     if (I == CurrentAnalyses.end()) {
259       if (Batcher)
260         return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
261       return 0;
262     }
263     return I->second;
264   }
265
266   Pass *getAnalysisOrNullUp(AnalysisID ID) const {
267     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
268     if (I == CurrentAnalyses.end()) {
269       if (Parent)
270         return Parent->getAnalysisOrNullUp(ID);
271       return 0;
272     }
273     return I->second;
274   }
275
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
279   // passes.
280   //
281   void startPass(Pass *P) {
282     if (Parent) Parent->startPass(P);
283     else PassStarted(P);
284   }
285   void endPass(Pass *P) {
286     if (Parent) Parent->endPass(P);
287     else PassEnded(P);
288   }
289
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
293   // them...
294   //
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
299     } else {
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.
304       //
305       assert(Parent != 0 && "Pass available but not found! "
306              "Did your analysis pass 'Provide' itself?");
307       Parent->markPassUsed(P, this);
308     }
309   }
310
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();
315   }
316
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!");
320     return Passes[N];
321   }
322
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.
327   //
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();
333
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());
339     }
340
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..
344     //
345     P->addToPassManager(this, AnUsage);
346   }
347
348 private:
349
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.
355   //
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.
359   //
360   void addPass(PassClass *P, AnalysisUsage &AnUsage) {
361     const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
362
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!
366     //
367     //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
368     if (Batcher /*&& ProvidedSet.empty()*/)
369       closeBatcher();                     // This pass cannot be batched!
370     
371     // Set the Resolver instance variable in the Pass so that it knows where to 
372     // find this object...
373     //
374     setAnalysisResolver(P, this);
375     Passes.push_back(P);
376
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...
380     //
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
384
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) !=
391             PreservedSet.end())
392           ++I;  // This analysis is preserved, leave it in the available set...
393         else {
394 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
395           I = CurrentAnalyses.erase(I);   // Analysis not preserved!
396 #else
397           CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
398           I = CurrentAnalyses.begin();
399 #endif
400         }
401     }
402
403     // Add this pass to the currently available set...
404     if (const PassInfo *PI = P->getPassInfo())
405       CurrentAnalyses[PI] = P;
406
407     // For now assume that our results are never used...
408     LastUseOf[P] = P;
409   }
410   
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.
414   //
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);
420   }
421
422   // closeBatcher - Terminate the batcher that is being worked on.
423   void closeBatcher() {
424     if (Batcher) {
425       Passes.push_back(Batcher);
426       Batcher = 0;
427     }
428   }
429 };
430
431
432
433 //===----------------------------------------------------------------------===//
434 // PassManagerTraits<BasicBlock> Specialization
435 //
436 // This pass manager is used to group together all of the BasicBlockPass's
437 // into a single unit.
438 //
439 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
440   // PassClass - The type of passes tracked by this PassManager
441   typedef BasicBlockPass PassClass;
442
443   // SubPassClass - The types of classes that should be collated together
444   // This is impossible to match, so BasicBlock instantiations of PassManagerT
445   // do not collate.
446   //
447   typedef PassManagerT<Module> SubPassClass;
448
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.
452   //
453   typedef PassClass BatcherClass;
454
455   // ParentClass - The type of the parent PassManager...
456   typedef PassManagerT<Function> ParentClass;
457
458   // PMType - The type of the passmanager that subclasses this class
459   typedef PassManagerT<BasicBlock> PMType;
460
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);
465   }
466
467   // Dummy implementation of PassStarted/PassEnded
468   static void PassStarted(Pass *P) {}
469   static void PassEnded(Pass *P) {}
470
471   // getPMName() - Return the name of the unit the PassManager operates on for
472   // debugging.
473   const char *getPMName() const { return "BasicBlock"; }
474   virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
475
476   // Implement the BasicBlockPass interface...
477   virtual bool doInitialization(Module &M);
478   virtual bool runOnBasicBlock(BasicBlock &BB);
479   virtual bool doFinalization(Module &M);
480
481   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
482     AU.setPreservesAll();
483   }
484 };
485
486
487
488 //===----------------------------------------------------------------------===//
489 // PassManagerTraits<Function> Specialization
490 //
491 // This pass manager is used to group together all of the FunctionPass's
492 // into a single unit.
493 //
494 template<> struct PassManagerTraits<Function> : public FunctionPass {
495   // PassClass - The type of passes tracked by this PassManager
496   typedef FunctionPass PassClass;
497
498   // SubPassClass - The types of classes that should be collated together
499   typedef BasicBlockPass SubPassClass;
500
501   // BatcherClass - The type to use for collation of subtypes...
502   typedef PassManagerT<BasicBlock> BatcherClass;
503
504   // ParentClass - The type of the parent PassManager...
505   typedef PassManagerT<Module> ParentClass;
506
507   // PMType - The type of the passmanager that subclasses this class
508   typedef PassManagerT<Function> PMType;
509
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);
513   }
514
515   // Dummy implementation of PassStarted/PassEnded
516   static void PassStarted(Pass *P) {}
517   static void PassEnded(Pass *P) {}
518
519   // getPMName() - Return the name of the unit the PassManager operates on for
520   // debugging.
521   const char *getPMName() const { return "Function"; }
522   virtual const char *getPassName() const { return "Function Pass Manager"; }
523
524   // Implement the FunctionPass interface...
525   virtual bool doInitialization(Module &M);
526   virtual bool runOnFunction(Function &F);
527   virtual bool doFinalization(Module &M);
528
529   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
530     AU.setPreservesAll();
531   }
532 };
533
534
535
536 //===----------------------------------------------------------------------===//
537 // PassManagerTraits<Module> Specialization
538 //
539 // This is the top level PassManager implementation that holds generic passes.
540 //
541 template<> struct PassManagerTraits<Module> : public Pass {
542   // PassClass - The type of passes tracked by this PassManager
543   typedef Pass PassClass;
544
545   // SubPassClass - The types of classes that should be collated together
546   typedef FunctionPass SubPassClass;
547
548   // BatcherClass - The type to use for collation of subtypes...
549   typedef PassManagerT<Function> BatcherClass;
550
551   // ParentClass - The type of the parent PassManager...
552   typedef AnalysisResolver ParentClass;
553
554   // runPass - Specify how the pass should be run on the UnitType
555   static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
556
557   // getPMName() - Return the name of the unit the PassManager operates on for
558   // debugging.
559   const char *getPMName() const { return "Module"; }
560   virtual const char *getPassName() const { return "Module Pass Manager"; }
561
562   // TimingInformation - This data member maintains timing information for each
563   // of the passes that is executed.
564   //
565   TimingInfo *TimeInfo;
566
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.
570   //
571   void PassStarted(Pass *P) {
572     if (TimeInfo) TimeInfo->passStarted(P);
573   }
574   void PassEnded(Pass *P) {
575     if (TimeInfo) TimeInfo->passEnded(P);
576   }
577
578   // run - Implement the PassManager interface...
579   bool run(Module &M) {
580     TimeInfo = TimingInfo::create();
581     bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
582     if (TimeInfo) {
583       delete TimeInfo;
584       TimeInfo = 0;
585     }
586     return Result;
587   }
588
589   // PassManagerTraits constructor - Create a timing info object if the user
590   // specified timing info should be collected on the command line.
591   //
592   PassManagerTraits() : TimeInfo(0) {}
593 };
594
595
596
597 //===----------------------------------------------------------------------===//
598 // PassManagerTraits Method Implementations
599 //
600
601 // PassManagerTraits<BasicBlock> Implementations
602 //
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);
607   return Changed;
608 }
609
610 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
611   return ((PMType*)this)->runOnUnit(&BB);
612 }
613
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);
618   return Changed;
619 }
620
621
622 // PassManagerTraits<Function> Implementations
623 //
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);
628   return Changed;
629 }
630
631 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
632   return ((PMType*)this)->runOnUnit(&F);
633 }
634
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);
639   return Changed;
640 }
641
642 #endif