7bd9b3488b4ca21b085887f17110bea684d9eaef
[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 "Support/LeakDetector.h"
21 #include "Support/Timer.h"
22 #include <algorithm>
23 #include <iostream>
24 class Annotable;
25
26 //===----------------------------------------------------------------------===//
27 // Pass debugging information.  Often it is useful to find out what pass is
28 // running when a crash occurs in a utility.  When this library is compiled with
29 // debugging on, a command line option (--debug-pass) is enabled that causes the
30 // pass name to be printed before it executes.
31 //
32
33 // Different debug levels that can be enabled...
34 enum PassDebugLevel {
35   None, Arguments, Structure, Executions, Details
36 };
37
38 static cl::opt<enum PassDebugLevel>
39 PassDebugging("debug-pass", cl::Hidden,
40               cl::desc("Print PassManager debugging information"),
41               cl::values(
42   clEnumVal(None      , "disable debug output"),
43   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
44   clEnumVal(Structure , "print pass structure before run()"),
45   clEnumVal(Executions, "print pass name before it is executed"),
46   clEnumVal(Details   , "print pass details when it is executed"),
47                          0));
48
49 //===----------------------------------------------------------------------===//
50 // PMDebug class - a set of debugging functions, that are not to be
51 // instantiated by the template.
52 //
53 struct PMDebug {
54   static void PerformPassStartupStuff(Pass *P) {
55     // If debugging is enabled, print out argument information...
56     if (PassDebugging >= Arguments) {
57       std::cerr << "Pass Arguments: ";
58       PrintArgumentInformation(P);
59       std::cerr << "\n";
60
61       // Print the pass execution structure
62       if (PassDebugging >= Structure)
63         P->dumpPassStructure();
64     }
65   }
66
67   static void PrintArgumentInformation(const Pass *P);
68   static void PrintPassInformation(unsigned,const char*,Pass *, Annotable *);
69   static void PrintAnalysisSetInfo(unsigned,const char*,Pass *P,
70                                    const std::vector<AnalysisID> &);
71 };
72
73
74 //===----------------------------------------------------------------------===//
75 // TimingInfo Class - This class is used to calculate information about the
76 // amount of time each pass takes to execute.  This only happens when
77 // -time-passes is enabled on the command line.
78 //
79
80 class TimingInfo {
81   std::map<Pass*, Timer> TimingData;
82   TimerGroup TG;
83
84   // Private ctor, must use 'create' member
85   TimingInfo() : TG("... Pass execution timing report ...") {}
86 public:
87   // TimingDtor - Print out information about timing information
88   ~TimingInfo() {
89     // Delete all of the timers...
90     TimingData.clear();
91     // TimerGroup is deleted next, printing the report.
92   }
93
94   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
95   // to a non null value (if the -time-passes option is enabled) or it leaves it
96   // null.  It may be called multiple times.
97   static void createTheTimeInfo();
98
99   void passStarted(Pass *P) {
100     if (dynamic_cast<AnalysisResolver*>(P)) return;
101     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
102     if (I == TimingData.end())
103       I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
104     I->second.startTimer();
105   }
106   void passEnded(Pass *P) {
107     if (dynamic_cast<AnalysisResolver*>(P)) return;
108     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
109     assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
110     I->second.stopTimer();
111   }
112 };
113
114 static TimingInfo *TheTimeInfo;
115
116 //===----------------------------------------------------------------------===//
117 // Declare the PassManagerTraits which will be specialized...
118 //
119 template<class UnitType> class PassManagerTraits;   // Do not define.
120
121
122 //===----------------------------------------------------------------------===//
123 // PassManagerT - Container object for passes.  The PassManagerT destructor
124 // deletes all passes contained inside of the PassManagerT, so you shouldn't 
125 // delete passes manually, and all passes should be dynamically allocated.
126 //
127 template<typename UnitType>
128 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
129   typedef PassManagerTraits<UnitType> Traits;
130   typedef typename Traits::PassClass       PassClass;
131   typedef typename Traits::SubPassClass SubPassClass;
132   typedef typename Traits::BatcherClass BatcherClass;
133   typedef typename Traits::ParentClass   ParentClass;
134
135   friend class PassManagerTraits<UnitType>::PassClass;
136   friend class PassManagerTraits<UnitType>::SubPassClass;  
137   friend class Traits;
138   friend class ImmutablePass;
139
140   std::vector<PassClass*> Passes;    // List of passes to run
141   std::vector<ImmutablePass*> ImmutablePasses;  // List of immutable passes
142
143   // The parent of this pass manager...
144   ParentClass * const Parent;
145
146   // The current batcher if one is in use, or null
147   BatcherClass *Batcher;
148
149   // CurrentAnalyses - As the passes are being run, this map contains the
150   // analyses that are available to the current pass for use.  This is accessed
151   // through the getAnalysis() function in this class and in Pass.
152   //
153   std::map<AnalysisID, Pass*> CurrentAnalyses;
154
155   // LastUseOf - This map keeps track of the last usage in our pipeline of a
156   // particular pass.  When executing passes, the memory for .first is free'd
157   // after .second is run.
158   //
159   std::map<Pass*, Pass*> LastUseOf;
160
161 public:
162   PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
163   ~PassManagerT() {
164     // Delete all of the contained passes...
165     for (typename std::vector<PassClass*>::iterator
166            I = Passes.begin(), E = Passes.end(); I != E; ++I)
167       delete *I;
168
169     for (std::vector<ImmutablePass*>::iterator
170            I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
171       delete *I;
172   }
173
174   // run - Run all of the queued passes on the specified module in an optimal
175   // way.
176   virtual bool runOnUnit(UnitType *M) {
177     bool MadeChanges = false;
178     closeBatcher();
179     CurrentAnalyses.clear();
180
181     TimingInfo::createTheTimeInfo();
182
183     // Add any immutable passes to the CurrentAnalyses set...
184     for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
185       ImmutablePass *IPass = ImmutablePasses[i];
186       if (const PassInfo *PI = IPass->getPassInfo()) {
187         CurrentAnalyses[PI] = IPass;
188
189         const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
190         for (unsigned i = 0, e = II.size(); i != e; ++i)
191           CurrentAnalyses[II[i]] = IPass;
192       }
193     }
194
195     // LastUserOf - This contains the inverted LastUseOfMap...
196     std::map<Pass *, std::vector<Pass*> > LastUserOf;
197     for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
198                                           E = LastUseOf.end(); I != E; ++I)
199       LastUserOf[I->second].push_back(I->first);
200
201
202     // Output debug information...
203     if (Parent == 0) PMDebug::PerformPassStartupStuff(this);
204
205     // Run all of the passes
206     for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
207       PassClass *P = Passes[i];
208       
209       PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
210                                     (Annotable*)M);
211
212       // Get information about what analyses the pass uses...
213       AnalysisUsage AnUsage;
214       P->getAnalysisUsage(AnUsage);
215       PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
216                                     AnUsage.getRequiredSet());
217
218       // All Required analyses should be available to the pass as it runs!  Here
219       // we fill in the AnalysisImpls member of the pass so that it can
220       // successfully use the getAnalysis() method to retrieve the
221       // implementations it needs.
222       //
223       P->AnalysisImpls.clear();
224       P->AnalysisImpls.reserve(AnUsage.getRequiredSet().size());
225       for (std::vector<const PassInfo *>::const_iterator
226              I = AnUsage.getRequiredSet().begin(), 
227              E = AnUsage.getRequiredSet().end(); I != E; ++I) {
228         Pass *Impl = getAnalysisOrNullUp(*I);
229         if (Impl == 0) {
230           std::cerr << "Analysis '" << (*I)->getPassName()
231                     << "' used but not available!";
232           assert(0 && "Analysis used but not available!");
233         } else if (PassDebugging == Details) {
234           if ((*I)->getPassName() != std::string(Impl->getPassName()))
235             std::cerr << "    Interface '" << (*I)->getPassName()
236                     << "' implemented by '" << Impl->getPassName() << "'\n";
237         }
238         P->AnalysisImpls.push_back(std::make_pair(*I, Impl));
239       }
240
241       // Run the sub pass!
242       if (TheTimeInfo) TheTimeInfo->passStarted(P);
243       bool Changed = runPass(P, M);
244       if (TheTimeInfo) TheTimeInfo->passEnded(P);
245       MadeChanges |= Changed;
246
247       // Check for memory leaks by the pass...
248       LeakDetector::checkForGarbage(std::string("after running pass '") +
249                                     P->getPassName() + "'");
250
251       if (Changed)
252         PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
253                                       (Annotable*)M);
254       PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
255                                     AnUsage.getPreservedSet());
256
257
258       // Erase all analyses not in the preserved set...
259       if (!AnUsage.getPreservesAll()) {
260         const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
261         for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
262                E = CurrentAnalyses.end(); I != E; )
263           if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
264               PreservedSet.end())
265             ++I; // This analysis is preserved, leave it in the available set...
266           else {
267             if (!dynamic_cast<ImmutablePass*>(I->second)) {
268               std::map<AnalysisID, Pass*>::iterator J = I++;
269               CurrentAnalyses.erase(J);   // Analysis not preserved!
270             } else {
271               ++I;
272             }
273           }
274       }
275
276       // Add the current pass to the set of passes that have been run, and are
277       // thus available to users.
278       //
279       if (const PassInfo *PI = P->getPassInfo()) {
280         CurrentAnalyses[PI] = P;
281
282         // This pass is the current implementation of all of the interfaces it
283         // implements as well.
284         //
285         const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
286         for (unsigned i = 0, e = II.size(); i != e; ++i)
287           CurrentAnalyses[II[i]] = P;
288       }
289
290       // Free memory for any passes that we are the last use of...
291       std::vector<Pass*> &DeadPass = LastUserOf[P];
292       for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
293            I != E; ++I) {
294         PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
295                                       (Annotable*)M);
296         (*I)->releaseMemory();
297       }
298
299       // Make sure to remove dead passes from the CurrentAnalyses list...
300       for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin();
301            I != CurrentAnalyses.end(); ) {
302         std::vector<Pass*>::iterator DPI = std::find(DeadPass.begin(),
303                                                      DeadPass.end(), I->second);
304         if (DPI != DeadPass.end()) {    // This pass is dead now... remove it
305           std::map<AnalysisID, Pass*>::iterator IDead = I++;
306           CurrentAnalyses.erase(IDead);
307         } else {
308           ++I;  // Move on to the next element...
309         }
310       }
311     }
312
313     return MadeChanges;
314   }
315
316   // dumpPassStructure - Implement the -debug-passes=PassStructure option
317   virtual void dumpPassStructure(unsigned Offset = 0) {
318     // Print out the immutable passes...
319     for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i)
320       ImmutablePasses[i]->dumpPassStructure(0);
321
322     std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
323               << " Pass Manager\n";
324     for (typename std::vector<PassClass*>::iterator
325            I = Passes.begin(), E = Passes.end(); I != E; ++I) {
326       PassClass *P = *I;
327       P->dumpPassStructure(Offset+1);
328
329       // Loop through and see which classes are destroyed after this one...
330       for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
331                                             E = LastUseOf.end(); I != E; ++I) {
332         if (P == I->second) {
333           std::cerr << "--" << std::string(Offset*2, ' ');
334           I->first->dumpPassStructure(0);
335         }
336       }
337     }
338   }
339
340   Pass *getImmutablePassOrNull(const PassInfo *ID) const {
341     for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
342       const PassInfo *IPID = ImmutablePasses[i]->getPassInfo();
343       if (IPID == ID)
344         return ImmutablePasses[i];
345       
346       // This pass is the current implementation of all of the interfaces it
347       // implements as well.
348       //
349       const std::vector<const PassInfo*> &II =
350         IPID->getInterfacesImplemented();
351       for (unsigned j = 0, e = II.size(); j != e; ++j)
352         if (II[j] == ID) return ImmutablePasses[i];
353     }
354     return 0;
355   }
356
357   Pass *getAnalysisOrNullDown(const PassInfo *ID) const {
358     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
359
360     if (I != CurrentAnalyses.end())
361       return I->second;  // Found it.
362
363     if (Pass *P = getImmutablePassOrNull(ID))
364       return P;
365
366     if (Batcher)
367       return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
368     return 0;
369   }
370
371   Pass *getAnalysisOrNullUp(const PassInfo *ID) const {
372     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
373     if (I != CurrentAnalyses.end())
374       return I->second;  // Found it.
375
376     if (Parent)          // Try scanning...
377       return Parent->getAnalysisOrNullUp(ID);
378     else if (!ImmutablePasses.empty())
379       return getImmutablePassOrNull(ID);
380     return 0;
381   }
382
383   // markPassUsed - Inform higher level pass managers (and ourselves)
384   // that these analyses are being used by this pass.  This is used to
385   // make sure that analyses are not free'd before we have to use
386   // them...
387   //
388   void markPassUsed(const PassInfo *P, Pass *User) {
389     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(P);
390
391     if (I != CurrentAnalyses.end()) {
392       LastUseOf[I->second] = User;    // Local pass, extend the lifetime
393     } else {
394       // Pass not in current available set, must be a higher level pass
395       // available to us, propagate to parent pass manager...  We tell the
396       // parent that we (the passmanager) are using the analysis so that it
397       // frees the analysis AFTER this pass manager runs.
398       //
399       if (Parent) {
400         Parent->markPassUsed(P, this);
401       } else {
402         assert(getAnalysisOrNullUp(P) && 
403                dynamic_cast<ImmutablePass*>(getAnalysisOrNullUp(P)) &&
404                "Pass available but not found! "
405                "Perhaps this is a module pass requiring a function pass?");
406       }
407     }
408   }
409   
410   // Return the number of parent PassManagers that exist
411   virtual unsigned getDepth() const {
412     if (Parent == 0) return 0;
413     return 1 + Parent->getDepth();
414   }
415
416   virtual unsigned getNumContainedPasses() const { return Passes.size(); }
417   virtual const Pass *getContainedPass(unsigned N) const {
418     assert(N < Passes.size() && "Pass number out of range!");
419     return Passes[N];
420   }
421
422   // add - Add a pass to the queue of passes to run.  This gives ownership of
423   // the Pass to the PassManager.  When the PassManager is destroyed, the pass
424   // will be destroyed as well, so there is no need to delete the pass.  This
425   // implies that all passes MUST be new'd.
426   //
427   void add(PassClass *P) {
428     // Get information about what analyses the pass uses...
429     AnalysisUsage AnUsage;
430     P->getAnalysisUsage(AnUsage);
431     const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
432
433     // Loop over all of the analyses used by this pass,
434     for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
435            E = Required.end(); I != E; ++I) {
436       if (getAnalysisOrNullDown(*I) == 0)
437         add((PassClass*)(*I)->createPass());
438     }
439
440     // Tell the pass to add itself to this PassManager... the way it does so
441     // depends on the class of the pass, and is critical to laying out passes in
442     // an optimal order..
443     //
444     P->addToPassManager(this, AnUsage);
445   }
446
447   // add - H4x0r an ImmutablePass into a PassManager that might not be
448   // expecting one.
449   //
450   void add(ImmutablePass *P) {
451     // Get information about what analyses the pass uses...
452     AnalysisUsage AnUsage;
453     P->getAnalysisUsage(AnUsage);
454     const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
455
456     // Loop over all of the analyses used by this pass,
457     for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
458            E = Required.end(); I != E; ++I) {
459       if (getAnalysisOrNullDown(*I) == 0)
460         add((PassClass*)(*I)->createPass());
461     }
462
463     // Add the ImmutablePass to this PassManager.
464     addPass(P, AnUsage);
465   }
466
467 private:
468   // addPass - These functions are used to implement the subclass specific
469   // behaviors present in PassManager.  Basically the add(Pass*) method ends up
470   // reflecting its behavior into a Pass::addToPassManager call.  Subclasses of
471   // Pass override it specifically so that they can reflect the type
472   // information inherent in "this" back to the PassManager.
473   //
474   // For generic Pass subclasses (which are interprocedural passes), we simply
475   // add the pass to the end of the pass list and terminate any accumulation of
476   // FunctionPass's that are present.
477   //
478   void addPass(PassClass *P, AnalysisUsage &AnUsage) {
479     const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
480
481     // FIXME: If this pass being added isn't killed by any of the passes in the
482     // batcher class then we can reorder to pass to execute before the batcher
483     // does, which will potentially allow us to batch more passes!
484     //
485     //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
486     if (Batcher /*&& ProvidedSet.empty()*/)
487       closeBatcher();                     // This pass cannot be batched!
488     
489     // Set the Resolver instance variable in the Pass so that it knows where to 
490     // find this object...
491     //
492     setAnalysisResolver(P, this);
493     Passes.push_back(P);
494
495     // Inform higher level pass managers (and ourselves) that these analyses are
496     // being used by this pass.  This is used to make sure that analyses are not
497     // free'd before we have to use them...
498     //
499     for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
500            E = RequiredSet.end(); I != E; ++I)
501       markPassUsed(*I, P);     // Mark *I as used by P
502
503     // Erase all analyses not in the preserved set...
504     if (!AnUsage.getPreservesAll()) {
505       const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
506       for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
507              E = CurrentAnalyses.end(); I != E; ) {
508         if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) ==
509             PreservedSet.end()) {             // Analysis not preserved!
510           CurrentAnalyses.erase(I);           // Remove from available analyses
511           I = CurrentAnalyses.begin();
512         } else {
513           ++I;
514         }
515       }
516     }
517
518     // Add this pass to the currently available set...
519     if (const PassInfo *PI = P->getPassInfo()) {
520       CurrentAnalyses[PI] = P;
521
522       // This pass is the current implementation of all of the interfaces it
523       // implements as well.
524       //
525       const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
526       for (unsigned i = 0, e = II.size(); i != e; ++i)
527         CurrentAnalyses[II[i]] = P;
528     }
529
530     // For now assume that our results are never used...
531     LastUseOf[P] = P;
532   }
533   
534   // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
535   // together in a BatcherClass object so that all of the analyses are run
536   // together a function at a time.
537   //
538   void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
539     if (Batcher == 0) // If we don't have a batcher yet, make one now.
540       Batcher = new BatcherClass(this);
541     // The Batcher will queue the passes up
542     MP->addToPassManager(Batcher, AnUsage);
543   }
544
545   // closeBatcher - Terminate the batcher that is being worked on.
546   void closeBatcher() {
547     if (Batcher) {
548       Passes.push_back(Batcher);
549       Batcher = 0;
550     }
551   }
552
553 public:
554   // When an ImmutablePass is added, it gets added to the top level pass
555   // manager.
556   void addPass(ImmutablePass *IP, AnalysisUsage &AU) {
557     if (Parent) { // Make sure this request goes to the top level passmanager...
558       Parent->addPass(IP, AU);
559       return;
560     }
561
562     // Set the Resolver instance variable in the Pass so that it knows where to 
563     // find this object...
564     //
565     setAnalysisResolver(IP, this);
566     ImmutablePasses.push_back(IP);
567
568     // All Required analyses should be available to the pass as it initializes!
569     // Here we fill in the AnalysisImpls member of the pass so that it can
570     // successfully use the getAnalysis() method to retrieve the implementations
571     // it needs.
572     //
573     IP->AnalysisImpls.clear();
574     IP->AnalysisImpls.reserve(AU.getRequiredSet().size());
575     for (std::vector<const PassInfo *>::const_iterator 
576            I = AU.getRequiredSet().begin(),
577            E = AU.getRequiredSet().end(); I != E; ++I) {
578       Pass *Impl = getAnalysisOrNullUp(*I);
579       if (Impl == 0) {
580         std::cerr << "Analysis '" << (*I)->getPassName()
581                   << "' used but not available!";
582         assert(0 && "Analysis used but not available!");
583       } else if (PassDebugging == Details) {
584         if ((*I)->getPassName() != std::string(Impl->getPassName()))
585           std::cerr << "    Interface '" << (*I)->getPassName()
586                     << "' implemented by '" << Impl->getPassName() << "'\n";
587       }
588       IP->AnalysisImpls.push_back(std::make_pair(*I, Impl));
589     }
590     
591     // Initialize the immutable pass...
592     IP->initializePass();
593   }
594 };
595
596
597
598 //===----------------------------------------------------------------------===//
599 // PassManagerTraits<BasicBlock> Specialization
600 //
601 // This pass manager is used to group together all of the BasicBlockPass's
602 // into a single unit.
603 //
604 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
605   // PassClass - The type of passes tracked by this PassManager
606   typedef BasicBlockPass PassClass;
607
608   // SubPassClass - The types of classes that should be collated together
609   // This is impossible to match, so BasicBlock instantiations of PassManagerT
610   // do not collate.
611   //
612   typedef PassManagerT<Module> SubPassClass;
613
614   // BatcherClass - The type to use for collation of subtypes... This class is
615   // never instantiated for the PassManager<BasicBlock>, but it must be an 
616   // instance of PassClass to typecheck.
617   //
618   typedef PassClass BatcherClass;
619
620   // ParentClass - The type of the parent PassManager...
621   typedef PassManagerT<Function> ParentClass;
622
623   // PMType - The type of the passmanager that subclasses this class
624   typedef PassManagerT<BasicBlock> PMType;
625
626   // runPass - Specify how the pass should be run on the UnitType
627   static bool runPass(PassClass *P, BasicBlock *M) {
628     // todo, init and finalize
629     return P->runOnBasicBlock(*M);
630   }
631
632   // getPMName() - Return the name of the unit the PassManager operates on for
633   // debugging.
634   const char *getPMName() const { return "BasicBlock"; }
635   virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
636
637   // Implement the BasicBlockPass interface...
638   virtual bool doInitialization(Module &M);
639   virtual bool doInitialization(Function &F);
640   virtual bool runOnBasicBlock(BasicBlock &BB);
641   virtual bool doFinalization(Function &F);
642   virtual bool doFinalization(Module &M);
643
644   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
645     AU.setPreservesAll();
646   }
647 };
648
649
650
651 //===----------------------------------------------------------------------===//
652 // PassManagerTraits<Function> Specialization
653 //
654 // This pass manager is used to group together all of the FunctionPass's
655 // into a single unit.
656 //
657 template<> struct PassManagerTraits<Function> : public FunctionPass {
658   // PassClass - The type of passes tracked by this PassManager
659   typedef FunctionPass PassClass;
660
661   // SubPassClass - The types of classes that should be collated together
662   typedef BasicBlockPass SubPassClass;
663
664   // BatcherClass - The type to use for collation of subtypes...
665   typedef PassManagerT<BasicBlock> BatcherClass;
666
667   // ParentClass - The type of the parent PassManager...
668   typedef PassManagerT<Module> ParentClass;
669
670   // PMType - The type of the passmanager that subclasses this class
671   typedef PassManagerT<Function> PMType;
672
673   // runPass - Specify how the pass should be run on the UnitType
674   static bool runPass(PassClass *P, Function *F) {
675     return P->runOnFunction(*F);
676   }
677
678   // getPMName() - Return the name of the unit the PassManager operates on for
679   // debugging.
680   const char *getPMName() const { return "Function"; }
681   virtual const char *getPassName() const { return "Function Pass Manager"; }
682
683   // Implement the FunctionPass interface...
684   virtual bool doInitialization(Module &M);
685   virtual bool runOnFunction(Function &F);
686   virtual bool doFinalization(Module &M);
687
688   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
689     AU.setPreservesAll();
690   }
691 };
692
693
694
695 //===----------------------------------------------------------------------===//
696 // PassManagerTraits<Module> Specialization
697 //
698 // This is the top level PassManager implementation that holds generic passes.
699 //
700 template<> struct PassManagerTraits<Module> : public Pass {
701   // PassClass - The type of passes tracked by this PassManager
702   typedef Pass PassClass;
703
704   // SubPassClass - The types of classes that should be collated together
705   typedef FunctionPass SubPassClass;
706
707   // BatcherClass - The type to use for collation of subtypes...
708   typedef PassManagerT<Function> BatcherClass;
709
710   // ParentClass - The type of the parent PassManager...
711   typedef AnalysisResolver ParentClass;
712
713   // runPass - Specify how the pass should be run on the UnitType
714   static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
715
716   // getPMName() - Return the name of the unit the PassManager operates on for
717   // debugging.
718   const char *getPMName() const { return "Module"; }
719   virtual const char *getPassName() const { return "Module Pass Manager"; }
720
721   // run - Implement the PassManager interface...
722   bool run(Module &M) {
723     return ((PassManagerT<Module>*)this)->runOnUnit(&M);
724   }
725 };
726
727
728
729 //===----------------------------------------------------------------------===//
730 // PassManagerTraits Method Implementations
731 //
732
733 // PassManagerTraits<BasicBlock> Implementations
734 //
735 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
736   bool Changed = false;
737   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
738     ((PMType*)this)->Passes[i]->doInitialization(M);
739   return Changed;
740 }
741
742 inline bool PassManagerTraits<BasicBlock>::doInitialization(Function &F) {
743   bool Changed = false;
744   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
745     ((PMType*)this)->Passes[i]->doInitialization(F);
746   return Changed;
747 }
748
749 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
750   return ((PMType*)this)->runOnUnit(&BB);
751 }
752
753 inline bool PassManagerTraits<BasicBlock>::doFinalization(Function &F) {
754   bool Changed = false;
755   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
756     ((PMType*)this)->Passes[i]->doFinalization(F);
757   return Changed;
758 }
759
760 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
761   bool Changed = false;
762   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
763     ((PMType*)this)->Passes[i]->doFinalization(M);
764   return Changed;
765 }
766
767
768 // PassManagerTraits<Function> Implementations
769 //
770 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
771   bool Changed = false;
772   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
773     ((PMType*)this)->Passes[i]->doInitialization(M);
774   return Changed;
775 }
776
777 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
778   return ((PMType*)this)->runOnUnit(&F);
779 }
780
781 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
782   bool Changed = false;
783   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
784     ((PMType*)this)->Passes[i]->doFinalization(M);
785   return Changed;
786 }
787
788 #endif