PassManager.cpp revision 19fe8f907e4addad1a33b7590b3f05893c39b3a6
1//===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Devang Patel and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LLVM Pass Manager infrastructure.
11//
12//===----------------------------------------------------------------------===//
13
14
15#include "llvm/PassManagers.h"
16#include "llvm/Support/CommandLine.h"
17#include "llvm/Support/Timer.h"
18#include "llvm/Module.h"
19#include "llvm/ModuleProvider.h"
20#include "llvm/Support/Streams.h"
21#include "llvm/Support/ManagedStatic.h"
22#include <algorithm>
23#include <vector>
24#include <map>
25
26// See PassManagers.h for Pass Manager infrastructure overview.
27
28namespace llvm {
29
30//===----------------------------------------------------------------------===//
31// Pass debugging information.  Often it is useful to find out what pass is
32// running when a crash occurs in a utility.  When this library is compiled with
33// debugging on, a command line option (--debug-pass) is enabled that causes the
34// pass name to be printed before it executes.
35//
36
37// Different debug levels that can be enabled...
38enum PassDebugLevel {
39  None, Arguments, Structure, Executions, Details
40};
41
42static cl::opt<enum PassDebugLevel>
43PassDebugging("debug-pass", cl::Hidden,
44                  cl::desc("Print PassManager debugging information"),
45                  cl::values(
46  clEnumVal(None      , "disable debug output"),
47  clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
48  clEnumVal(Structure , "print pass structure before run()"),
49  clEnumVal(Executions, "print pass name before it is executed"),
50  clEnumVal(Details   , "print pass details when it is executed"),
51                             clEnumValEnd));
52} // End of llvm namespace
53
54namespace {
55
56//===----------------------------------------------------------------------===//
57// BBPassManager
58//
59/// BBPassManager manages BasicBlockPass. It batches all the
60/// pass together and sequence them to process one basic block before
61/// processing next basic block.
62class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
63                                        public FunctionPass {
64
65public:
66  static char ID;
67  BBPassManager(int Depth)
68    : PMDataManager(Depth), FunctionPass((intptr_t)&ID) {}
69
70  /// Execute all of the passes scheduled for execution.  Keep track of
71  /// whether any of the passes modifies the function, and if so, return true.
72  bool runOnFunction(Function &F);
73
74  /// Pass Manager itself does not invalidate any analysis info.
75  void getAnalysisUsage(AnalysisUsage &Info) const {
76    Info.setPreservesAll();
77  }
78
79  bool doInitialization(Module &M);
80  bool doInitialization(Function &F);
81  bool doFinalization(Module &M);
82  bool doFinalization(Function &F);
83
84  virtual const char *getPassName() const {
85    return "BasicBlock Pass  Manager";
86  }
87
88  // Print passes managed by this manager
89  void dumpPassStructure(unsigned Offset) {
90    llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
91    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
92      BasicBlockPass *BP = getContainedPass(Index);
93      BP->dumpPassStructure(Offset + 1);
94      dumpLastUses(BP, Offset+1);
95    }
96  }
97
98  BasicBlockPass *getContainedPass(unsigned N) {
99    assert ( N < PassVector.size() && "Pass number out of range!");
100    BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
101    return BP;
102  }
103
104  virtual PassManagerType getPassManagerType() const {
105    return PMT_BasicBlockPassManager;
106  }
107};
108
109char BBPassManager::ID = 0;
110}
111
112namespace llvm {
113
114//===----------------------------------------------------------------------===//
115// FunctionPassManagerImpl
116//
117/// FunctionPassManagerImpl manages FPPassManagers
118class FunctionPassManagerImpl : public Pass,
119                                public PMDataManager,
120                                public PMTopLevelManager {
121public:
122  static char ID;
123  FunctionPassManagerImpl(int Depth) :
124    Pass((intptr_t)&ID), PMDataManager(Depth),
125    PMTopLevelManager(TLM_Function) { }
126
127  /// add - Add a pass to the queue of passes to run.  This passes ownership of
128  /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
129  /// will be destroyed as well, so there is no need to delete the pass.  This
130  /// implies that all passes MUST be allocated with 'new'.
131  void add(Pass *P) {
132    schedulePass(P);
133  }
134
135  /// run - Execute all of the passes scheduled for execution.  Keep track of
136  /// whether any of the passes modifies the module, and if so, return true.
137  bool run(Function &F);
138
139  /// doInitialization - Run all of the initializers for the function passes.
140  ///
141  bool doInitialization(Module &M);
142
143  /// doFinalization - Run all of the initializers for the function passes.
144  ///
145  bool doFinalization(Module &M);
146
147  /// Pass Manager itself does not invalidate any analysis info.
148  void getAnalysisUsage(AnalysisUsage &Info) const {
149    Info.setPreservesAll();
150  }
151
152  inline void addTopLevelPass(Pass *P) {
153
154    if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
155
156      // P is a immutable pass and it will be managed by this
157      // top level manager. Set up analysis resolver to connect them.
158      AnalysisResolver *AR = new AnalysisResolver(*this);
159      P->setResolver(AR);
160      initializeAnalysisImpl(P);
161      addImmutablePass(IP);
162      recordAvailableAnalysis(IP);
163    } else {
164      P->assignPassManager(activeStack);
165    }
166
167  }
168
169  FPPassManager *getContainedManager(unsigned N) {
170    assert ( N < PassManagers.size() && "Pass number out of range!");
171    FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
172    return FP;
173  }
174};
175
176char FunctionPassManagerImpl::ID = 0;
177//===----------------------------------------------------------------------===//
178// MPPassManager
179//
180/// MPPassManager manages ModulePasses and function pass managers.
181/// It batches all Module passes  passes and function pass managers together and
182/// sequence them to process one module.
183class MPPassManager : public Pass, public PMDataManager {
184
185public:
186  static char ID;
187  MPPassManager(int Depth) : Pass((intptr_t)&ID), PMDataManager(Depth) { }
188
189  // Delete on the fly managers.
190  virtual ~MPPassManager() {
191    for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
192           I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
193         I != E; ++I) {
194      FunctionPassManagerImpl *FPP = I->second;
195      delete FPP;
196    }
197  }
198
199  /// run - Execute all of the passes scheduled for execution.  Keep track of
200  /// whether any of the passes modifies the module, and if so, return true.
201  bool runOnModule(Module &M);
202
203  /// Pass Manager itself does not invalidate any analysis info.
204  void getAnalysisUsage(AnalysisUsage &Info) const {
205    Info.setPreservesAll();
206  }
207
208  /// Add RequiredPass into list of lower level passes required by pass P.
209  /// RequiredPass is run on the fly by Pass Manager when P requests it
210  /// through getAnalysis interface.
211  virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
212
213  /// Return function pass corresponding to PassInfo PI, that is
214  /// required by module pass MP. Instantiate analysis pass, by using
215  /// its runOnFunction() for function F.
216  virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
217
218  virtual const char *getPassName() const {
219    return "Module Pass Manager";
220  }
221
222  // Print passes managed by this manager
223  void dumpPassStructure(unsigned Offset) {
224    llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
225    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
226      ModulePass *MP = getContainedPass(Index);
227      MP->dumpPassStructure(Offset + 1);
228      if (FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP])
229        FPP->dumpPassStructure(Offset + 2);
230      dumpLastUses(MP, Offset+1);
231    }
232  }
233
234  ModulePass *getContainedPass(unsigned N) {
235    assert ( N < PassVector.size() && "Pass number out of range!");
236    ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
237    return MP;
238  }
239
240  virtual PassManagerType getPassManagerType() const {
241    return PMT_ModulePassManager;
242  }
243
244 private:
245  /// Collection of on the fly FPPassManagers. These managers manage
246  /// function passes that are required by module passes.
247  std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
248};
249
250char MPPassManager::ID = 0;
251//===----------------------------------------------------------------------===//
252// PassManagerImpl
253//
254
255/// PassManagerImpl manages MPPassManagers
256class PassManagerImpl : public Pass,
257                        public PMDataManager,
258                        public PMTopLevelManager {
259
260public:
261  static char ID;
262  PassManagerImpl(int Depth) : Pass((intptr_t)&ID), PMDataManager(Depth),
263                               PMTopLevelManager(TLM_Pass) { }
264
265  /// add - Add a pass to the queue of passes to run.  This passes ownership of
266  /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
267  /// will be destroyed as well, so there is no need to delete the pass.  This
268  /// implies that all passes MUST be allocated with 'new'.
269  void add(Pass *P) {
270    schedulePass(P);
271  }
272
273  /// run - Execute all of the passes scheduled for execution.  Keep track of
274  /// whether any of the passes modifies the module, and if so, return true.
275  bool run(Module &M);
276
277  /// Pass Manager itself does not invalidate any analysis info.
278  void getAnalysisUsage(AnalysisUsage &Info) const {
279    Info.setPreservesAll();
280  }
281
282  inline void addTopLevelPass(Pass *P) {
283
284    if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
285
286      // P is a immutable pass and it will be managed by this
287      // top level manager. Set up analysis resolver to connect them.
288      AnalysisResolver *AR = new AnalysisResolver(*this);
289      P->setResolver(AR);
290      initializeAnalysisImpl(P);
291      addImmutablePass(IP);
292      recordAvailableAnalysis(IP);
293    } else {
294      P->assignPassManager(activeStack);
295    }
296
297  }
298
299  MPPassManager *getContainedManager(unsigned N) {
300    assert ( N < PassManagers.size() && "Pass number out of range!");
301    MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
302    return MP;
303  }
304
305};
306
307char PassManagerImpl::ID = 0;
308} // End of llvm namespace
309
310namespace {
311
312//===----------------------------------------------------------------------===//
313// TimingInfo Class - This class is used to calculate information about the
314// amount of time each pass takes to execute.  This only happens when
315// -time-passes is enabled on the command line.
316//
317
318class VISIBILITY_HIDDEN TimingInfo {
319  std::map<Pass*, Timer> TimingData;
320  TimerGroup TG;
321
322public:
323  // Use 'create' member to get this.
324  TimingInfo() : TG("... Pass execution timing report ...") {}
325
326  // TimingDtor - Print out information about timing information
327  ~TimingInfo() {
328    // Delete all of the timers...
329    TimingData.clear();
330    // TimerGroup is deleted next, printing the report.
331  }
332
333  // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
334  // to a non null value (if the -time-passes option is enabled) or it leaves it
335  // null.  It may be called multiple times.
336  static void createTheTimeInfo();
337
338  void passStarted(Pass *P) {
339
340    if (dynamic_cast<PMDataManager *>(P))
341      return;
342
343    std::map<Pass*, Timer>::iterator I = TimingData.find(P);
344    if (I == TimingData.end())
345      I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
346    I->second.startTimer();
347  }
348  void passEnded(Pass *P) {
349
350    if (dynamic_cast<PMDataManager *>(P))
351      return;
352
353    std::map<Pass*, Timer>::iterator I = TimingData.find(P);
354    assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
355    I->second.stopTimer();
356  }
357};
358
359static TimingInfo *TheTimeInfo;
360
361} // End of anon namespace
362
363//===----------------------------------------------------------------------===//
364// PMTopLevelManager implementation
365
366/// Initialize top level manager. Create first pass manager.
367PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
368
369  if (t == TLM_Pass) {
370    MPPassManager *MPP = new MPPassManager(1);
371    MPP->setTopLevelManager(this);
372    addPassManager(MPP);
373    activeStack.push(MPP);
374  }
375  else if (t == TLM_Function) {
376    FPPassManager *FPP = new FPPassManager(1);
377    FPP->setTopLevelManager(this);
378    addPassManager(FPP);
379    activeStack.push(FPP);
380  }
381}
382
383/// Set pass P as the last user of the given analysis passes.
384void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
385                                    Pass *P) {
386
387  for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
388         E = AnalysisPasses.end(); I != E; ++I) {
389    Pass *AP = *I;
390    LastUser[AP] = P;
391
392    if (P == AP)
393      continue;
394
395    // If AP is the last user of other passes then make P last user of
396    // such passes.
397    for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
398           LUE = LastUser.end(); LUI != LUE; ++LUI) {
399      if (LUI->second == AP)
400        LastUser[LUI->first] = P;
401    }
402  }
403}
404
405/// Collect passes whose last user is P
406void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
407                                            Pass *P) {
408   for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
409          LUE = LastUser.end(); LUI != LUE; ++LUI)
410      if (LUI->second == P)
411        LastUses.push_back(LUI->first);
412}
413
414/// Schedule pass P for execution. Make sure that passes required by
415/// P are run before P is run. Update analysis info maintained by
416/// the manager. Remove dead passes. This is a recursive function.
417void PMTopLevelManager::schedulePass(Pass *P) {
418
419  // TODO : Allocate function manager for this pass, other wise required set
420  // may be inserted into previous function manager
421
422  // Give pass a chance to prepare the stage.
423  P->preparePassManager(activeStack);
424
425  AnalysisUsage AnUsage;
426  P->getAnalysisUsage(AnUsage);
427  const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
428  for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
429         E = RequiredSet.end(); I != E; ++I) {
430
431    Pass *AnalysisPass = findAnalysisPass(*I);
432    if (!AnalysisPass) {
433      AnalysisPass = (*I)->createPass();
434      // Schedule this analysis run first only if it is not a lower level
435      // analysis pass. Lower level analsyis passes are run on the fly.
436      if (P->getPotentialPassManagerType () >=
437          AnalysisPass->getPotentialPassManagerType())
438        schedulePass(AnalysisPass);
439      else
440        delete AnalysisPass;
441    }
442  }
443
444  // Now all required passes are available.
445  addTopLevelPass(P);
446}
447
448/// Find the pass that implements Analysis AID. Search immutable
449/// passes and all pass managers. If desired pass is not found
450/// then return NULL.
451Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
452
453  Pass *P = NULL;
454  // Check pass managers
455  for (std::vector<Pass *>::iterator I = PassManagers.begin(),
456         E = PassManagers.end(); P == NULL && I != E; ++I) {
457    PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
458    assert(PMD && "This is not a PassManager");
459    P = PMD->findAnalysisPass(AID, false);
460  }
461
462  // Check other pass managers
463  for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
464         E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
465    P = (*I)->findAnalysisPass(AID, false);
466
467  for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
468         E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
469    const PassInfo *PI = (*I)->getPassInfo();
470    if (PI == AID)
471      P = *I;
472
473    // If Pass not found then check the interfaces implemented by Immutable Pass
474    if (!P) {
475      const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
476      if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
477        P = *I;
478    }
479  }
480
481  return P;
482}
483
484// Print passes managed by this top level manager.
485void PMTopLevelManager::dumpPasses() const {
486
487  if (PassDebugging < Structure)
488    return;
489
490  // Print out the immutable passes
491  for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
492    ImmutablePasses[i]->dumpPassStructure(0);
493  }
494
495  for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
496         E = PassManagers.end(); I != E; ++I)
497    (*I)->dumpPassStructure(1);
498}
499
500void PMTopLevelManager::dumpArguments() const {
501
502  if (PassDebugging < Arguments)
503    return;
504
505  cerr << "Pass Arguments: ";
506  for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
507         E = PassManagers.end(); I != E; ++I) {
508    PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
509    assert(PMD && "This is not a PassManager");
510    PMD->dumpPassArguments();
511  }
512  cerr << "\n";
513}
514
515void PMTopLevelManager::initializeAllAnalysisInfo() {
516
517  for (std::vector<Pass *>::iterator I = PassManagers.begin(),
518         E = PassManagers.end(); I != E; ++I) {
519    PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
520    assert(PMD && "This is not a PassManager");
521    PMD->initializeAnalysisInfo();
522  }
523
524  // Initailize other pass managers
525  for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
526         E = IndirectPassManagers.end(); I != E; ++I)
527    (*I)->initializeAnalysisInfo();
528}
529
530/// Destructor
531PMTopLevelManager::~PMTopLevelManager() {
532  for (std::vector<Pass *>::iterator I = PassManagers.begin(),
533         E = PassManagers.end(); I != E; ++I)
534    delete *I;
535
536  for (std::vector<ImmutablePass *>::iterator
537         I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
538    delete *I;
539
540  PassManagers.clear();
541}
542
543//===----------------------------------------------------------------------===//
544// PMDataManager implementation
545
546/// Return true IFF pass P's required analysis set does not required new
547/// manager.
548bool PMDataManager::manageablePass(Pass *P) {
549
550  // TODO
551  // If this pass is not preserving information that is required by a
552  // pass maintained by higher level pass manager then do not insert
553  // this pass into current manager. Use new manager. For example,
554  // For example, If FunctionPass F is not preserving ModulePass Info M1
555  // that is used by another ModulePass M2 then do not insert F in
556  // current function pass manager.
557  return true;
558}
559
560/// Augement AvailableAnalysis by adding analysis made available by pass P.
561void PMDataManager::recordAvailableAnalysis(Pass *P) {
562
563  if (const PassInfo *PI = P->getPassInfo()) {
564    AvailableAnalysis[PI] = P;
565
566    //This pass is the current implementation of all of the interfaces it
567    //implements as well.
568    const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
569    for (unsigned i = 0, e = II.size(); i != e; ++i)
570      AvailableAnalysis[II[i]] = P;
571  }
572}
573
574// Return true if P preserves high level analysis used by other
575// passes managed by this manager
576bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
577
578  AnalysisUsage AnUsage;
579  P->getAnalysisUsage(AnUsage);
580
581  if (AnUsage.getPreservesAll())
582    return true;
583
584  const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
585  for (std::vector<Pass *>::iterator I = HigherLevelAnalysis.begin(),
586         E = HigherLevelAnalysis.end(); I  != E; ++I) {
587    Pass *P1 = *I;
588    if (!dynamic_cast<ImmutablePass*>(P1)
589        && std::find(PreservedSet.begin(), PreservedSet.end(), P1->getPassInfo()) ==
590           PreservedSet.end())
591      return false;
592  }
593
594  return true;
595}
596
597/// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
598void PMDataManager::verifyPreservedAnalysis(Pass *P) {
599  AnalysisUsage AnUsage;
600  P->getAnalysisUsage(AnUsage);
601  const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
602
603  // Verify preserved analysis
604  for (std::vector<AnalysisID>::const_iterator I = PreservedSet.begin(),
605         E = PreservedSet.end(); I != E; ++I) {
606    AnalysisID AID = *I;
607    Pass *AP = findAnalysisPass(AID, true);
608    if (AP)
609      AP->verifyAnalysis();
610  }
611}
612
613/// Remove Analyss not preserved by Pass P
614void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
615  AnalysisUsage AnUsage;
616  P->getAnalysisUsage(AnUsage);
617  if (AnUsage.getPreservesAll())
618    return;
619
620  const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
621  for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
622         E = AvailableAnalysis.end(); I != E; ) {
623    std::map<AnalysisID, Pass*>::iterator Info = I++;
624    if (!dynamic_cast<ImmutablePass*>(Info->second)
625        && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
626           PreservedSet.end())
627      // Remove this analysis
628      AvailableAnalysis.erase(Info);
629  }
630
631  // Check inherited analysis also. If P is not preserving analysis
632  // provided by parent manager then remove it here.
633  for (unsigned Index = 0; Index < PMT_Last; ++Index) {
634
635    if (!InheritedAnalysis[Index])
636      continue;
637
638    for (std::map<AnalysisID, Pass*>::iterator
639           I = InheritedAnalysis[Index]->begin(),
640           E = InheritedAnalysis[Index]->end(); I != E; ) {
641      std::map<AnalysisID, Pass *>::iterator Info = I++;
642      if (!dynamic_cast<ImmutablePass*>(Info->second)
643          && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
644             PreservedSet.end())
645        // Remove this analysis
646        InheritedAnalysis[Index]->erase(Info);
647    }
648  }
649
650}
651
652/// Remove analysis passes that are not used any longer
653void PMDataManager::removeDeadPasses(Pass *P, std::string Msg,
654                                     enum PassDebuggingString DBG_STR) {
655
656  SmallVector<Pass *, 12> DeadPasses;
657
658  // If this is a on the fly manager then it does not have TPM.
659  if (!TPM)
660    return;
661
662  TPM->collectLastUses(DeadPasses, P);
663
664  for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
665         E = DeadPasses.end(); I != E; ++I) {
666
667    dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
668
669    if (TheTimeInfo) TheTimeInfo->passStarted(*I);
670    (*I)->releaseMemory();
671    if (TheTimeInfo) TheTimeInfo->passEnded(*I);
672
673    std::map<AnalysisID, Pass*>::iterator Pos =
674      AvailableAnalysis.find((*I)->getPassInfo());
675
676    // It is possible that pass is already removed from the AvailableAnalysis
677    if (Pos != AvailableAnalysis.end())
678      AvailableAnalysis.erase(Pos);
679  }
680}
681
682/// Add pass P into the PassVector. Update
683/// AvailableAnalysis appropriately if ProcessAnalysis is true.
684void PMDataManager::add(Pass *P,
685                        bool ProcessAnalysis) {
686
687  // This manager is going to manage pass P. Set up analysis resolver
688  // to connect them.
689  AnalysisResolver *AR = new AnalysisResolver(*this);
690  P->setResolver(AR);
691
692  // If a FunctionPass F is the last user of ModulePass info M
693  // then the F's manager, not F, records itself as a last user of M.
694  SmallVector<Pass *, 12> TransferLastUses;
695
696  if (ProcessAnalysis) {
697
698    // At the moment, this pass is the last user of all required passes.
699    SmallVector<Pass *, 12> LastUses;
700    SmallVector<Pass *, 8> RequiredPasses;
701    SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
702
703    unsigned PDepth = this->getDepth();
704
705    collectRequiredAnalysis(RequiredPasses,
706                            ReqAnalysisNotAvailable, P);
707    for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
708           E = RequiredPasses.end(); I != E; ++I) {
709      Pass *PRequired = *I;
710      unsigned RDepth = 0;
711
712      PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
713      RDepth = DM.getDepth();
714
715      if (PDepth == RDepth)
716        LastUses.push_back(PRequired);
717      else if (PDepth >  RDepth) {
718        // Let the parent claim responsibility of last use
719        TransferLastUses.push_back(PRequired);
720        // Keep track of higher level analysis used by this manager.
721        HigherLevelAnalysis.push_back(PRequired);
722      } else
723        assert (0 && "Unable to accomodate Required Pass");
724    }
725
726    // Set P as P's last user until someone starts using P.
727    // However, if P is a Pass Manager then it does not need
728    // to record its last user.
729    if (!dynamic_cast<PMDataManager *>(P))
730      LastUses.push_back(P);
731    TPM->setLastUser(LastUses, P);
732
733    if (!TransferLastUses.empty()) {
734      Pass *My_PM = dynamic_cast<Pass *>(this);
735      TPM->setLastUser(TransferLastUses, My_PM);
736      TransferLastUses.clear();
737    }
738
739    // Now, take care of required analysises that are not available.
740    for (SmallVector<AnalysisID, 8>::iterator
741           I = ReqAnalysisNotAvailable.begin(),
742           E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
743      Pass *AnalysisPass = (*I)->createPass();
744      this->addLowerLevelRequiredPass(P, AnalysisPass);
745    }
746
747    // Take a note of analysis required and made available by this pass.
748    // Remove the analysis not preserved by this pass
749    removeNotPreservedAnalysis(P);
750    recordAvailableAnalysis(P);
751  }
752
753  // Add pass
754  PassVector.push_back(P);
755}
756
757
758/// Populate RP with analysis pass that are required by
759/// pass P and are available. Populate RP_NotAvail with analysis
760/// pass that are required by pass P but are not available.
761void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
762                                       SmallVector<AnalysisID, 8> &RP_NotAvail,
763                                            Pass *P) {
764  AnalysisUsage AnUsage;
765  P->getAnalysisUsage(AnUsage);
766  const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
767  for (std::vector<AnalysisID>::const_iterator
768         I = RequiredSet.begin(), E = RequiredSet.end();
769       I != E; ++I) {
770    AnalysisID AID = *I;
771    if (Pass *AnalysisPass = findAnalysisPass(*I, true))
772      RP.push_back(AnalysisPass);
773    else
774      RP_NotAvail.push_back(AID);
775  }
776
777  const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
778  for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
779         E = IDs.end(); I != E; ++I) {
780    AnalysisID AID = *I;
781    if (Pass *AnalysisPass = findAnalysisPass(*I, true))
782      RP.push_back(AnalysisPass);
783    else
784      RP_NotAvail.push_back(AID);
785  }
786}
787
788// All Required analyses should be available to the pass as it runs!  Here
789// we fill in the AnalysisImpls member of the pass so that it can
790// successfully use the getAnalysis() method to retrieve the
791// implementations it needs.
792//
793void PMDataManager::initializeAnalysisImpl(Pass *P) {
794  AnalysisUsage AnUsage;
795  P->getAnalysisUsage(AnUsage);
796
797  for (std::vector<const PassInfo *>::const_iterator
798         I = AnUsage.getRequiredSet().begin(),
799         E = AnUsage.getRequiredSet().end(); I != E; ++I) {
800    Pass *Impl = findAnalysisPass(*I, true);
801    if (Impl == 0)
802      // This may be analysis pass that is initialized on the fly.
803      // If that is not the case then it will raise an assert when it is used.
804      continue;
805    AnalysisResolver *AR = P->getResolver();
806    AR->addAnalysisImplsPair(*I, Impl);
807  }
808}
809
810/// Find the pass that implements Analysis AID. If desired pass is not found
811/// then return NULL.
812Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
813
814  // Check if AvailableAnalysis map has one entry.
815  std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
816
817  if (I != AvailableAnalysis.end())
818    return I->second;
819
820  // Search Parents through TopLevelManager
821  if (SearchParent)
822    return TPM->findAnalysisPass(AID);
823
824  return NULL;
825}
826
827// Print list of passes that are last used by P.
828void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
829
830  SmallVector<Pass *, 12> LUses;
831
832  // If this is a on the fly manager then it does not have TPM.
833  if (!TPM)
834    return;
835
836  TPM->collectLastUses(LUses, P);
837
838  for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
839         E = LUses.end(); I != E; ++I) {
840    llvm::cerr << "--" << std::string(Offset*2, ' ');
841    (*I)->dumpPassStructure(0);
842  }
843}
844
845void PMDataManager::dumpPassArguments() const {
846  for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
847        E = PassVector.end(); I != E; ++I) {
848    if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
849      PMD->dumpPassArguments();
850    else
851      if (const PassInfo *PI = (*I)->getPassInfo())
852        if (!PI->isAnalysisGroup())
853          cerr << " -" << PI->getPassArgument();
854  }
855}
856
857void PMDataManager:: dumpPassInfo(Pass *P, enum PassDebuggingString S1,
858                                  enum PassDebuggingString S2,
859                                  std::string Msg) {
860  if (PassDebugging < Executions)
861    return;
862  cerr << (void*)this << std::string(getDepth()*2+1, ' ');
863  switch (S1) {
864  case EXECUTION_MSG:
865    cerr << "Executing Pass '" << P->getPassName();
866    break;
867  case MODIFICATION_MSG:
868    cerr << "Made Modification '" << P->getPassName();
869    break;
870  case FREEING_MSG:
871    cerr << " Freeing Pass '" << P->getPassName();
872    break;
873  default:
874    break;
875  }
876  switch (S2) {
877  case ON_BASICBLOCK_MSG:
878    cerr << "' on BasicBlock '" << Msg << "'...\n";
879    break;
880  case ON_FUNCTION_MSG:
881    cerr << "' on Function '" << Msg << "'...\n";
882    break;
883  case ON_MODULE_MSG:
884    cerr << "' on Module '"  << Msg << "'...\n";
885    break;
886  case ON_LOOP_MSG:
887    cerr << "' on Loop " << Msg << "'...\n";
888    break;
889  case ON_CG_MSG:
890    cerr << "' on Call Graph " << Msg << "'...\n";
891    break;
892  default:
893    break;
894  }
895}
896
897void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
898                                        const std::vector<AnalysisID> &Set)
899  const {
900  if (PassDebugging >= Details && !Set.empty()) {
901    cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
902      for (unsigned i = 0; i != Set.size(); ++i) {
903        if (i) cerr << ",";
904        cerr << " " << Set[i]->getPassName();
905      }
906      cerr << "\n";
907  }
908}
909
910/// Add RequiredPass into list of lower level passes required by pass P.
911/// RequiredPass is run on the fly by Pass Manager when P requests it
912/// through getAnalysis interface.
913/// This should be handled by specific pass manager.
914void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
915  if (TPM) {
916    TPM->dumpArguments();
917    TPM->dumpPasses();
918  }
919  assert (0 && "Unable to handle Pass that requires lower level Analysis pass");
920}
921
922// Destructor
923PMDataManager::~PMDataManager() {
924
925  for (std::vector<Pass *>::iterator I = PassVector.begin(),
926         E = PassVector.end(); I != E; ++I)
927    delete *I;
928
929  PassVector.clear();
930}
931
932//===----------------------------------------------------------------------===//
933// NOTE: Is this the right place to define this method ?
934// getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
935Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
936  return PM.findAnalysisPass(ID, dir);
937}
938
939Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
940                                     Function &F) {
941  return PM.getOnTheFlyPass(P, AnalysisPI, F);
942}
943
944//===----------------------------------------------------------------------===//
945// BBPassManager implementation
946
947/// Execute all of the passes scheduled for execution by invoking
948/// runOnBasicBlock method.  Keep track of whether any of the passes modifies
949/// the function, and if so, return true.
950bool
951BBPassManager::runOnFunction(Function &F) {
952
953  if (F.isDeclaration())
954    return false;
955
956  bool Changed = doInitialization(F);
957
958  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
959    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
960      BasicBlockPass *BP = getContainedPass(Index);
961      AnalysisUsage AnUsage;
962      BP->getAnalysisUsage(AnUsage);
963
964      dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
965      dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
966
967      initializeAnalysisImpl(BP);
968
969      if (TheTimeInfo) TheTimeInfo->passStarted(BP);
970      Changed |= BP->runOnBasicBlock(*I);
971      if (TheTimeInfo) TheTimeInfo->passEnded(BP);
972
973      if (Changed)
974        dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
975      dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
976
977      verifyPreservedAnalysis(BP);
978      removeNotPreservedAnalysis(BP);
979      recordAvailableAnalysis(BP);
980      removeDeadPasses(BP, (*I).getName(), ON_BASICBLOCK_MSG);
981
982    }
983  return Changed |= doFinalization(F);
984}
985
986// Implement doInitialization and doFinalization
987inline bool BBPassManager::doInitialization(Module &M) {
988  bool Changed = false;
989
990  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
991    BasicBlockPass *BP = getContainedPass(Index);
992    Changed |= BP->doInitialization(M);
993  }
994
995  return Changed;
996}
997
998inline bool BBPassManager::doFinalization(Module &M) {
999  bool Changed = false;
1000
1001  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1002    BasicBlockPass *BP = getContainedPass(Index);
1003    Changed |= BP->doFinalization(M);
1004  }
1005
1006  return Changed;
1007}
1008
1009inline bool BBPassManager::doInitialization(Function &F) {
1010  bool Changed = false;
1011
1012  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1013    BasicBlockPass *BP = getContainedPass(Index);
1014    Changed |= BP->doInitialization(F);
1015  }
1016
1017  return Changed;
1018}
1019
1020inline bool BBPassManager::doFinalization(Function &F) {
1021  bool Changed = false;
1022
1023  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1024    BasicBlockPass *BP = getContainedPass(Index);
1025    Changed |= BP->doFinalization(F);
1026  }
1027
1028  return Changed;
1029}
1030
1031
1032//===----------------------------------------------------------------------===//
1033// FunctionPassManager implementation
1034
1035/// Create new Function pass manager
1036FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1037  FPM = new FunctionPassManagerImpl(0);
1038  // FPM is the top level manager.
1039  FPM->setTopLevelManager(FPM);
1040
1041  PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
1042  AnalysisResolver *AR = new AnalysisResolver(*PMD);
1043  FPM->setResolver(AR);
1044
1045  MP = P;
1046}
1047
1048FunctionPassManager::~FunctionPassManager() {
1049  delete FPM;
1050}
1051
1052/// add - Add a pass to the queue of passes to run.  This passes
1053/// ownership of the Pass to the PassManager.  When the
1054/// PassManager_X is destroyed, the pass will be destroyed as well, so
1055/// there is no need to delete the pass. (TODO delete passes.)
1056/// This implies that all passes MUST be allocated with 'new'.
1057void FunctionPassManager::add(Pass *P) {
1058  FPM->add(P);
1059}
1060
1061/// run - Execute all of the passes scheduled for execution.  Keep
1062/// track of whether any of the passes modifies the function, and if
1063/// so, return true.
1064///
1065bool FunctionPassManager::run(Function &F) {
1066  std::string errstr;
1067  if (MP->materializeFunction(&F, &errstr)) {
1068    cerr << "Error reading bitcode file: " << errstr << "\n";
1069    abort();
1070  }
1071  return FPM->run(F);
1072}
1073
1074
1075/// doInitialization - Run all of the initializers for the function passes.
1076///
1077bool FunctionPassManager::doInitialization() {
1078  return FPM->doInitialization(*MP->getModule());
1079}
1080
1081/// doFinalization - Run all of the initializers for the function passes.
1082///
1083bool FunctionPassManager::doFinalization() {
1084  return FPM->doFinalization(*MP->getModule());
1085}
1086
1087//===----------------------------------------------------------------------===//
1088// FunctionPassManagerImpl implementation
1089//
1090inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1091  bool Changed = false;
1092
1093  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1094    FPPassManager *FP = getContainedManager(Index);
1095    Changed |= FP->doInitialization(M);
1096  }
1097
1098  return Changed;
1099}
1100
1101inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1102  bool Changed = false;
1103
1104  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1105    FPPassManager *FP = getContainedManager(Index);
1106    Changed |= FP->doFinalization(M);
1107  }
1108
1109  return Changed;
1110}
1111
1112// Execute all the passes managed by this top level manager.
1113// Return true if any function is modified by a pass.
1114bool FunctionPassManagerImpl::run(Function &F) {
1115
1116  bool Changed = false;
1117
1118  TimingInfo::createTheTimeInfo();
1119
1120  dumpArguments();
1121  dumpPasses();
1122
1123  initializeAllAnalysisInfo();
1124  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1125    FPPassManager *FP = getContainedManager(Index);
1126    Changed |= FP->runOnFunction(F);
1127  }
1128  return Changed;
1129}
1130
1131//===----------------------------------------------------------------------===//
1132// FPPassManager implementation
1133
1134char FPPassManager::ID = 0;
1135/// Print passes managed by this manager
1136void FPPassManager::dumpPassStructure(unsigned Offset) {
1137  llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1138  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1139    FunctionPass *FP = getContainedPass(Index);
1140    FP->dumpPassStructure(Offset + 1);
1141    dumpLastUses(FP, Offset+1);
1142  }
1143}
1144
1145
1146/// Execute all of the passes scheduled for execution by invoking
1147/// runOnFunction method.  Keep track of whether any of the passes modifies
1148/// the function, and if so, return true.
1149bool FPPassManager::runOnFunction(Function &F) {
1150
1151  bool Changed = false;
1152
1153  if (F.isDeclaration())
1154    return false;
1155
1156  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1157    FunctionPass *FP = getContainedPass(Index);
1158
1159    AnalysisUsage AnUsage;
1160    FP->getAnalysisUsage(AnUsage);
1161
1162    dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1163    dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1164
1165    initializeAnalysisImpl(FP);
1166
1167    if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1168    Changed |= FP->runOnFunction(F);
1169    if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1170
1171    if (Changed)
1172      dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1173    dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1174
1175    verifyPreservedAnalysis(FP);
1176    removeNotPreservedAnalysis(FP);
1177    recordAvailableAnalysis(FP);
1178    removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1179  }
1180  return Changed;
1181}
1182
1183bool FPPassManager::runOnModule(Module &M) {
1184
1185  bool Changed = doInitialization(M);
1186
1187  for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1188    this->runOnFunction(*I);
1189
1190  return Changed |= doFinalization(M);
1191}
1192
1193inline bool FPPassManager::doInitialization(Module &M) {
1194  bool Changed = false;
1195
1196  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1197    FunctionPass *FP = getContainedPass(Index);
1198    Changed |= FP->doInitialization(M);
1199  }
1200
1201  return Changed;
1202}
1203
1204inline bool FPPassManager::doFinalization(Module &M) {
1205  bool Changed = false;
1206
1207  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1208    FunctionPass *FP = getContainedPass(Index);
1209    Changed |= FP->doFinalization(M);
1210  }
1211
1212  return Changed;
1213}
1214
1215//===----------------------------------------------------------------------===//
1216// MPPassManager implementation
1217
1218/// Execute all of the passes scheduled for execution by invoking
1219/// runOnModule method.  Keep track of whether any of the passes modifies
1220/// the module, and if so, return true.
1221bool
1222MPPassManager::runOnModule(Module &M) {
1223  bool Changed = false;
1224
1225  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1226    ModulePass *MP = getContainedPass(Index);
1227
1228    AnalysisUsage AnUsage;
1229    MP->getAnalysisUsage(AnUsage);
1230
1231    dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1232    dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1233
1234    initializeAnalysisImpl(MP);
1235
1236    if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1237    Changed |= MP->runOnModule(M);
1238    if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1239
1240    if (Changed)
1241      dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1242                   M.getModuleIdentifier());
1243    dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1244
1245    verifyPreservedAnalysis(MP);
1246    removeNotPreservedAnalysis(MP);
1247    recordAvailableAnalysis(MP);
1248    removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1249  }
1250  return Changed;
1251}
1252
1253/// Add RequiredPass into list of lower level passes required by pass P.
1254/// RequiredPass is run on the fly by Pass Manager when P requests it
1255/// through getAnalysis interface.
1256void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1257
1258  assert (P->getPotentialPassManagerType() == PMT_ModulePassManager
1259          && "Unable to handle Pass that requires lower level Analysis pass");
1260  assert ((P->getPotentialPassManagerType() <
1261           RequiredPass->getPotentialPassManagerType())
1262          && "Unable to handle Pass that requires lower level Analysis pass");
1263
1264  FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1265  if (!FPP) {
1266    FPP = new FunctionPassManagerImpl(0);
1267    // FPP is the top level manager.
1268    FPP->setTopLevelManager(FPP);
1269
1270    OnTheFlyManagers[P] = FPP;
1271  }
1272  FPP->add(RequiredPass);
1273
1274  // Register P as the last user of RequiredPass.
1275  SmallVector<Pass *, 12> LU;
1276  LU.push_back(RequiredPass);
1277  FPP->setLastUser(LU,  P);
1278}
1279
1280/// Return function pass corresponding to PassInfo PI, that is
1281/// required by module pass MP. Instantiate analysis pass, by using
1282/// its runOnFunction() for function F.
1283Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI,
1284                                     Function &F) {
1285   AnalysisID AID = PI;
1286  FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1287  assert (FPP && "Unable to find on the fly pass");
1288
1289  FPP->run(F);
1290  return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(AID);
1291}
1292
1293
1294//===----------------------------------------------------------------------===//
1295// PassManagerImpl implementation
1296//
1297/// run - Execute all of the passes scheduled for execution.  Keep track of
1298/// whether any of the passes modifies the module, and if so, return true.
1299bool PassManagerImpl::run(Module &M) {
1300
1301  bool Changed = false;
1302
1303  TimingInfo::createTheTimeInfo();
1304
1305  dumpArguments();
1306  dumpPasses();
1307
1308  initializeAllAnalysisInfo();
1309  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1310    MPPassManager *MP = getContainedManager(Index);
1311    Changed |= MP->runOnModule(M);
1312  }
1313  return Changed;
1314}
1315
1316//===----------------------------------------------------------------------===//
1317// PassManager implementation
1318
1319/// Create new pass manager
1320PassManager::PassManager() {
1321  PM = new PassManagerImpl(0);
1322  // PM is the top level manager
1323  PM->setTopLevelManager(PM);
1324}
1325
1326PassManager::~PassManager() {
1327  delete PM;
1328}
1329
1330/// add - Add a pass to the queue of passes to run.  This passes ownership of
1331/// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1332/// will be destroyed as well, so there is no need to delete the pass.  This
1333/// implies that all passes MUST be allocated with 'new'.
1334void
1335PassManager::add(Pass *P) {
1336  PM->add(P);
1337}
1338
1339/// run - Execute all of the passes scheduled for execution.  Keep track of
1340/// whether any of the passes modifies the module, and if so, return true.
1341bool
1342PassManager::run(Module &M) {
1343  return PM->run(M);
1344}
1345
1346//===----------------------------------------------------------------------===//
1347// TimingInfo Class - This class is used to calculate information about the
1348// amount of time each pass takes to execute.  This only happens with
1349// -time-passes is enabled on the command line.
1350//
1351bool llvm::TimePassesIsEnabled = false;
1352static cl::opt<bool,true>
1353EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1354            cl::desc("Time each pass, printing elapsed time for each on exit"));
1355
1356// createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1357// a non null value (if the -time-passes option is enabled) or it leaves it
1358// null.  It may be called multiple times.
1359void TimingInfo::createTheTimeInfo() {
1360  if (!TimePassesIsEnabled || TheTimeInfo) return;
1361
1362  // Constructed the first time this is called, iff -time-passes is enabled.
1363  // This guarantees that the object will be constructed before static globals,
1364  // thus it will be destroyed before them.
1365  static ManagedStatic<TimingInfo> TTI;
1366  TheTimeInfo = &*TTI;
1367}
1368
1369/// If TimingInfo is enabled then start pass timer.
1370void StartPassTimer(Pass *P) {
1371  if (TheTimeInfo)
1372    TheTimeInfo->passStarted(P);
1373}
1374
1375/// If TimingInfo is enabled then stop pass timer.
1376void StopPassTimer(Pass *P) {
1377  if (TheTimeInfo)
1378    TheTimeInfo->passEnded(P);
1379}
1380
1381//===----------------------------------------------------------------------===//
1382// PMStack implementation
1383//
1384
1385// Pop Pass Manager from the stack and clear its analysis info.
1386void PMStack::pop() {
1387
1388  PMDataManager *Top = this->top();
1389  Top->initializeAnalysisInfo();
1390
1391  S.pop_back();
1392}
1393
1394// Push PM on the stack and set its top level manager.
1395void PMStack::push(Pass *P) {
1396
1397  PMDataManager *Top = NULL;
1398  PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1399  assert (PM && "Unable to push. Pass Manager expected");
1400
1401  if (this->empty()) {
1402    Top = PM;
1403  }
1404  else {
1405    Top = this->top();
1406    PMTopLevelManager *TPM = Top->getTopLevelManager();
1407
1408    assert (TPM && "Unable to find top level manager");
1409    TPM->addIndirectPassManager(PM);
1410    PM->setTopLevelManager(TPM);
1411  }
1412
1413  S.push_back(PM);
1414}
1415
1416// Dump content of the pass manager stack.
1417void PMStack::dump() {
1418  for(std::deque<PMDataManager *>::iterator I = S.begin(),
1419        E = S.end(); I != E; ++I) {
1420    Pass *P = dynamic_cast<Pass *>(*I);
1421    printf ("%s ", P->getPassName());
1422  }
1423  if (!S.empty())
1424    printf ("\n");
1425}
1426
1427/// Find appropriate Module Pass Manager in the PM Stack and
1428/// add self into that manager.
1429void ModulePass::assignPassManager(PMStack &PMS,
1430                                   PassManagerType PreferredType) {
1431
1432  // Find Module Pass Manager
1433  while(!PMS.empty()) {
1434    PassManagerType TopPMType = PMS.top()->getPassManagerType();
1435    if (TopPMType == PreferredType)
1436      break; // We found desired pass manager
1437    else if (TopPMType > PMT_ModulePassManager)
1438      PMS.pop();    // Pop children pass managers
1439    else
1440      break;
1441  }
1442
1443  PMS.top()->add(this);
1444}
1445
1446/// Find appropriate Function Pass Manager or Call Graph Pass Manager
1447/// in the PM Stack and add self into that manager.
1448void FunctionPass::assignPassManager(PMStack &PMS,
1449                                     PassManagerType PreferredType) {
1450
1451  // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1452  while(!PMS.empty()) {
1453    if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1454      PMS.pop();
1455    else
1456      break;
1457  }
1458  FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1459
1460  // Create new Function Pass Manager
1461  if (!FPP) {
1462    assert(!PMS.empty() && "Unable to create Function Pass Manager");
1463    PMDataManager *PMD = PMS.top();
1464
1465    // [1] Create new Function Pass Manager
1466    FPP = new FPPassManager(PMD->getDepth() + 1);
1467
1468    // [2] Set up new manager's top level manager
1469    PMTopLevelManager *TPM = PMD->getTopLevelManager();
1470    TPM->addIndirectPassManager(FPP);
1471
1472    // [3] Assign manager to manage this new manager. This may create
1473    // and push new managers into PMS
1474    Pass *P = dynamic_cast<Pass *>(FPP);
1475
1476    // If Call Graph Pass Manager is active then use it to manage
1477    // this new Function Pass manager.
1478    if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1479      P->assignPassManager(PMS, PMT_CallGraphPassManager);
1480    else
1481      P->assignPassManager(PMS);
1482
1483    // [4] Push new manager into PMS
1484    PMS.push(FPP);
1485  }
1486
1487  // Assign FPP as the manager of this pass.
1488  FPP->add(this);
1489}
1490
1491/// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1492/// in the PM Stack and add self into that manager.
1493void BasicBlockPass::assignPassManager(PMStack &PMS,
1494                                       PassManagerType PreferredType) {
1495
1496  BBPassManager *BBP = NULL;
1497
1498  // Basic Pass Manager is a leaf pass manager. It does not handle
1499  // any other pass manager.
1500  if (!PMS.empty()) {
1501    BBP = dynamic_cast<BBPassManager *>(PMS.top());
1502  }
1503
1504  // If leaf manager is not Basic Block Pass manager then create new
1505  // basic Block Pass manager.
1506
1507  if (!BBP) {
1508    assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1509    PMDataManager *PMD = PMS.top();
1510
1511    // [1] Create new Basic Block Manager
1512    BBP = new BBPassManager(PMD->getDepth() + 1);
1513
1514    // [2] Set up new manager's top level manager
1515    // Basic Block Pass Manager does not live by itself
1516    PMTopLevelManager *TPM = PMD->getTopLevelManager();
1517    TPM->addIndirectPassManager(BBP);
1518
1519    // [3] Assign manager to manage this new manager. This may create
1520    // and push new managers into PMS
1521    Pass *P = dynamic_cast<Pass *>(BBP);
1522    P->assignPassManager(PMS);
1523
1524    // [4] Push new manager into PMS
1525    PMS.push(BBP);
1526  }
1527
1528  // Assign BBP as the manager of this pass.
1529  BBP->add(this);
1530}
1531
1532
1533