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