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