1249259Sdim//===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
2249259Sdim//
3249259Sdim//                     The LLVM Compiler Infrastructure
4249259Sdim//
5249259Sdim// This file is distributed under the University of Illinois Open Source
6249259Sdim// License. See LICENSE.TXT for details.
7249259Sdim//
8249259Sdim//===----------------------------------------------------------------------===//
9249259Sdim//
10249259Sdim// This file implements the LLVM Pass Manager infrastructure.
11249259Sdim//
12249259Sdim//===----------------------------------------------------------------------===//
13249259Sdim
14249259Sdim
15249259Sdim#include "llvm/PassManagers.h"
16249259Sdim#include "llvm/Assembly/PrintModulePass.h"
17249259Sdim#include "llvm/Assembly/Writer.h"
18249259Sdim#include "llvm/IR/Module.h"
19249259Sdim#include "llvm/PassManager.h"
20249259Sdim#include "llvm/Support/CommandLine.h"
21249259Sdim#include "llvm/Support/Debug.h"
22249259Sdim#include "llvm/Support/ErrorHandling.h"
23249259Sdim#include "llvm/Support/ManagedStatic.h"
24249259Sdim#include "llvm/Support/Mutex.h"
25249259Sdim#include "llvm/Support/PassNameParser.h"
26249259Sdim#include "llvm/Support/Timer.h"
27249259Sdim#include "llvm/Support/raw_ostream.h"
28249259Sdim#include <algorithm>
29249259Sdim#include <map>
30249259Sdimusing namespace llvm;
31249259Sdim
32249259Sdim// See PassManagers.h for Pass Manager infrastructure overview.
33249259Sdim
34249259Sdimnamespace llvm {
35249259Sdim
36249259Sdim//===----------------------------------------------------------------------===//
37249259Sdim// Pass debugging information.  Often it is useful to find out what pass is
38249259Sdim// running when a crash occurs in a utility.  When this library is compiled with
39249259Sdim// debugging on, a command line option (--debug-pass) is enabled that causes the
40249259Sdim// pass name to be printed before it executes.
41249259Sdim//
42249259Sdim
43249259Sdim// Different debug levels that can be enabled...
44249259Sdimenum PassDebugLevel {
45251662Sdim  Disabled, Arguments, Structure, Executions, Details
46249259Sdim};
47249259Sdim
48249259Sdimstatic cl::opt<enum PassDebugLevel>
49249259SdimPassDebugging("debug-pass", cl::Hidden,
50249259Sdim                  cl::desc("Print PassManager debugging information"),
51249259Sdim                  cl::values(
52251662Sdim  clEnumVal(Disabled  , "disable debug output"),
53249259Sdim  clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54249259Sdim  clEnumVal(Structure , "print pass structure before run()"),
55249259Sdim  clEnumVal(Executions, "print pass name before it is executed"),
56249259Sdim  clEnumVal(Details   , "print pass details when it is executed"),
57249259Sdim                             clEnumValEnd));
58249259Sdim
59249259Sdimtypedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
60249259SdimPassOptionList;
61249259Sdim
62249259Sdim// Print IR out before/after specified passes.
63249259Sdimstatic PassOptionList
64249259SdimPrintBefore("print-before",
65249259Sdim            llvm::cl::desc("Print IR before specified passes"),
66249259Sdim            cl::Hidden);
67249259Sdim
68249259Sdimstatic PassOptionList
69249259SdimPrintAfter("print-after",
70249259Sdim           llvm::cl::desc("Print IR after specified passes"),
71249259Sdim           cl::Hidden);
72249259Sdim
73249259Sdimstatic cl::opt<bool>
74249259SdimPrintBeforeAll("print-before-all",
75249259Sdim               llvm::cl::desc("Print IR before each pass"),
76249259Sdim               cl::init(false));
77249259Sdimstatic cl::opt<bool>
78249259SdimPrintAfterAll("print-after-all",
79249259Sdim              llvm::cl::desc("Print IR after each pass"),
80249259Sdim              cl::init(false));
81249259Sdim
82249259Sdim/// This is a helper to determine whether to print IR before or
83249259Sdim/// after a pass.
84249259Sdim
85249259Sdimstatic bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
86249259Sdim                                         PassOptionList &PassesToPrint) {
87249259Sdim  for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
88249259Sdim    const llvm::PassInfo *PassInf = PassesToPrint[i];
89249259Sdim    if (PassInf)
90249259Sdim      if (PassInf->getPassArgument() == PI->getPassArgument()) {
91249259Sdim        return true;
92249259Sdim      }
93249259Sdim  }
94249259Sdim  return false;
95249259Sdim}
96249259Sdim
97249259Sdim/// This is a utility to check whether a pass should have IR dumped
98249259Sdim/// before it.
99249259Sdimstatic bool ShouldPrintBeforePass(const PassInfo *PI) {
100249259Sdim  return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
101249259Sdim}
102249259Sdim
103249259Sdim/// This is a utility to check whether a pass should have IR dumped
104249259Sdim/// after it.
105249259Sdimstatic bool ShouldPrintAfterPass(const PassInfo *PI) {
106249259Sdim  return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
107249259Sdim}
108249259Sdim
109249259Sdim} // End of llvm namespace
110249259Sdim
111249259Sdim/// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
112249259Sdim/// or higher is specified.
113249259Sdimbool PMDataManager::isPassDebuggingExecutionsOrMore() const {
114249259Sdim  return PassDebugging >= Executions;
115249259Sdim}
116249259Sdim
117249259Sdim
118249259Sdim
119249259Sdim
120249259Sdimvoid PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
121249259Sdim  if (V == 0 && M == 0)
122249259Sdim    OS << "Releasing pass '";
123249259Sdim  else
124249259Sdim    OS << "Running pass '";
125249259Sdim
126249259Sdim  OS << P->getPassName() << "'";
127249259Sdim
128249259Sdim  if (M) {
129249259Sdim    OS << " on module '" << M->getModuleIdentifier() << "'.\n";
130249259Sdim    return;
131249259Sdim  }
132249259Sdim  if (V == 0) {
133249259Sdim    OS << '\n';
134249259Sdim    return;
135249259Sdim  }
136249259Sdim
137249259Sdim  OS << " on ";
138249259Sdim  if (isa<Function>(V))
139249259Sdim    OS << "function";
140249259Sdim  else if (isa<BasicBlock>(V))
141249259Sdim    OS << "basic block";
142249259Sdim  else
143249259Sdim    OS << "value";
144249259Sdim
145249259Sdim  OS << " '";
146249259Sdim  WriteAsOperand(OS, V, /*PrintTy=*/false, M);
147249259Sdim  OS << "'\n";
148249259Sdim}
149249259Sdim
150249259Sdim
151249259Sdimnamespace {
152249259Sdim
153249259Sdim//===----------------------------------------------------------------------===//
154249259Sdim// BBPassManager
155249259Sdim//
156249259Sdim/// BBPassManager manages BasicBlockPass. It batches all the
157249259Sdim/// pass together and sequence them to process one basic block before
158249259Sdim/// processing next basic block.
159249259Sdimclass BBPassManager : public PMDataManager, public FunctionPass {
160249259Sdim
161249259Sdimpublic:
162249259Sdim  static char ID;
163249259Sdim  explicit BBPassManager()
164249259Sdim    : PMDataManager(), FunctionPass(ID) {}
165249259Sdim
166249259Sdim  /// Execute all of the passes scheduled for execution.  Keep track of
167249259Sdim  /// whether any of the passes modifies the function, and if so, return true.
168249259Sdim  bool runOnFunction(Function &F);
169249259Sdim
170249259Sdim  /// Pass Manager itself does not invalidate any analysis info.
171249259Sdim  void getAnalysisUsage(AnalysisUsage &Info) const {
172249259Sdim    Info.setPreservesAll();
173249259Sdim  }
174249259Sdim
175249259Sdim  bool doInitialization(Module &M);
176249259Sdim  bool doInitialization(Function &F);
177249259Sdim  bool doFinalization(Module &M);
178249259Sdim  bool doFinalization(Function &F);
179249259Sdim
180249259Sdim  virtual PMDataManager *getAsPMDataManager() { return this; }
181249259Sdim  virtual Pass *getAsPass() { return this; }
182249259Sdim
183249259Sdim  virtual const char *getPassName() const {
184249259Sdim    return "BasicBlock Pass Manager";
185249259Sdim  }
186249259Sdim
187249259Sdim  // Print passes managed by this manager
188249259Sdim  void dumpPassStructure(unsigned Offset) {
189249259Sdim    llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
190249259Sdim    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
191249259Sdim      BasicBlockPass *BP = getContainedPass(Index);
192249259Sdim      BP->dumpPassStructure(Offset + 1);
193249259Sdim      dumpLastUses(BP, Offset+1);
194249259Sdim    }
195249259Sdim  }
196249259Sdim
197249259Sdim  BasicBlockPass *getContainedPass(unsigned N) {
198249259Sdim    assert(N < PassVector.size() && "Pass number out of range!");
199249259Sdim    BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
200249259Sdim    return BP;
201249259Sdim  }
202249259Sdim
203249259Sdim  virtual PassManagerType getPassManagerType() const {
204249259Sdim    return PMT_BasicBlockPassManager;
205249259Sdim  }
206249259Sdim};
207249259Sdim
208249259Sdimchar BBPassManager::ID = 0;
209249259Sdim}
210249259Sdim
211249259Sdimnamespace llvm {
212249259Sdim
213249259Sdim//===----------------------------------------------------------------------===//
214249259Sdim// FunctionPassManagerImpl
215249259Sdim//
216249259Sdim/// FunctionPassManagerImpl manages FPPassManagers
217249259Sdimclass FunctionPassManagerImpl : public Pass,
218249259Sdim                                public PMDataManager,
219249259Sdim                                public PMTopLevelManager {
220249259Sdim  virtual void anchor();
221249259Sdimprivate:
222249259Sdim  bool wasRun;
223249259Sdimpublic:
224249259Sdim  static char ID;
225249259Sdim  explicit FunctionPassManagerImpl() :
226249259Sdim    Pass(PT_PassManager, ID), PMDataManager(),
227249259Sdim    PMTopLevelManager(new FPPassManager()), wasRun(false) {}
228249259Sdim
229249259Sdim  /// add - Add a pass to the queue of passes to run.  This passes ownership of
230249259Sdim  /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
231249259Sdim  /// will be destroyed as well, so there is no need to delete the pass.  This
232249259Sdim  /// implies that all passes MUST be allocated with 'new'.
233249259Sdim  void add(Pass *P) {
234249259Sdim    schedulePass(P);
235249259Sdim  }
236249259Sdim
237249259Sdim  /// createPrinterPass - Get a function printer pass.
238249259Sdim  Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
239249259Sdim    return createPrintFunctionPass(Banner, &O);
240249259Sdim  }
241249259Sdim
242249259Sdim  // Prepare for running an on the fly pass, freeing memory if needed
243249259Sdim  // from a previous run.
244249259Sdim  void releaseMemoryOnTheFly();
245249259Sdim
246249259Sdim  /// run - Execute all of the passes scheduled for execution.  Keep track of
247249259Sdim  /// whether any of the passes modifies the module, and if so, return true.
248249259Sdim  bool run(Function &F);
249249259Sdim
250249259Sdim  /// doInitialization - Run all of the initializers for the function passes.
251249259Sdim  ///
252249259Sdim  bool doInitialization(Module &M);
253249259Sdim
254249259Sdim  /// doFinalization - Run all of the finalizers for the function passes.
255249259Sdim  ///
256249259Sdim  bool doFinalization(Module &M);
257249259Sdim
258249259Sdim
259249259Sdim  virtual PMDataManager *getAsPMDataManager() { return this; }
260249259Sdim  virtual Pass *getAsPass() { return this; }
261249259Sdim  virtual PassManagerType getTopLevelPassManagerType() {
262249259Sdim    return PMT_FunctionPassManager;
263249259Sdim  }
264249259Sdim
265249259Sdim  /// Pass Manager itself does not invalidate any analysis info.
266249259Sdim  void getAnalysisUsage(AnalysisUsage &Info) const {
267249259Sdim    Info.setPreservesAll();
268249259Sdim  }
269249259Sdim
270249259Sdim  FPPassManager *getContainedManager(unsigned N) {
271249259Sdim    assert(N < PassManagers.size() && "Pass number out of range!");
272249259Sdim    FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
273249259Sdim    return FP;
274249259Sdim  }
275249259Sdim};
276249259Sdim
277249259Sdimvoid FunctionPassManagerImpl::anchor() {}
278249259Sdim
279249259Sdimchar FunctionPassManagerImpl::ID = 0;
280249259Sdim
281249259Sdim//===----------------------------------------------------------------------===//
282249259Sdim// MPPassManager
283249259Sdim//
284249259Sdim/// MPPassManager manages ModulePasses and function pass managers.
285249259Sdim/// It batches all Module passes and function pass managers together and
286249259Sdim/// sequences them to process one module.
287249259Sdimclass MPPassManager : public Pass, public PMDataManager {
288249259Sdimpublic:
289249259Sdim  static char ID;
290249259Sdim  explicit MPPassManager() :
291249259Sdim    Pass(PT_PassManager, ID), PMDataManager() { }
292249259Sdim
293249259Sdim  // Delete on the fly managers.
294249259Sdim  virtual ~MPPassManager() {
295249259Sdim    for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
296249259Sdim           I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
297249259Sdim         I != E; ++I) {
298249259Sdim      FunctionPassManagerImpl *FPP = I->second;
299249259Sdim      delete FPP;
300249259Sdim    }
301249259Sdim  }
302249259Sdim
303249259Sdim  /// createPrinterPass - Get a module printer pass.
304249259Sdim  Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
305249259Sdim    return createPrintModulePass(&O, false, Banner);
306249259Sdim  }
307249259Sdim
308249259Sdim  /// run - Execute all of the passes scheduled for execution.  Keep track of
309249259Sdim  /// whether any of the passes modifies the module, and if so, return true.
310249259Sdim  bool runOnModule(Module &M);
311249259Sdim
312249259Sdim  using llvm::Pass::doInitialization;
313249259Sdim  using llvm::Pass::doFinalization;
314249259Sdim
315249259Sdim  /// doInitialization - Run all of the initializers for the module passes.
316249259Sdim  ///
317249259Sdim  bool doInitialization();
318249259Sdim
319249259Sdim  /// doFinalization - Run all of the finalizers for the module passes.
320249259Sdim  ///
321249259Sdim  bool doFinalization();
322249259Sdim
323249259Sdim  /// Pass Manager itself does not invalidate any analysis info.
324249259Sdim  void getAnalysisUsage(AnalysisUsage &Info) const {
325249259Sdim    Info.setPreservesAll();
326249259Sdim  }
327249259Sdim
328249259Sdim  /// Add RequiredPass into list of lower level passes required by pass P.
329249259Sdim  /// RequiredPass is run on the fly by Pass Manager when P requests it
330249259Sdim  /// through getAnalysis interface.
331249259Sdim  virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
332249259Sdim
333249259Sdim  /// Return function pass corresponding to PassInfo PI, that is
334249259Sdim  /// required by module pass MP. Instantiate analysis pass, by using
335249259Sdim  /// its runOnFunction() for function F.
336249259Sdim  virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
337249259Sdim
338249259Sdim  virtual const char *getPassName() const {
339249259Sdim    return "Module Pass Manager";
340249259Sdim  }
341249259Sdim
342249259Sdim  virtual PMDataManager *getAsPMDataManager() { return this; }
343249259Sdim  virtual Pass *getAsPass() { return this; }
344249259Sdim
345249259Sdim  // Print passes managed by this manager
346249259Sdim  void dumpPassStructure(unsigned Offset) {
347249259Sdim    llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
348249259Sdim    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
349249259Sdim      ModulePass *MP = getContainedPass(Index);
350249259Sdim      MP->dumpPassStructure(Offset + 1);
351249259Sdim      std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
352249259Sdim        OnTheFlyManagers.find(MP);
353249259Sdim      if (I != OnTheFlyManagers.end())
354249259Sdim        I->second->dumpPassStructure(Offset + 2);
355249259Sdim      dumpLastUses(MP, Offset+1);
356249259Sdim    }
357249259Sdim  }
358249259Sdim
359249259Sdim  ModulePass *getContainedPass(unsigned N) {
360249259Sdim    assert(N < PassVector.size() && "Pass number out of range!");
361249259Sdim    return static_cast<ModulePass *>(PassVector[N]);
362249259Sdim  }
363249259Sdim
364249259Sdim  virtual PassManagerType getPassManagerType() const {
365249259Sdim    return PMT_ModulePassManager;
366249259Sdim  }
367249259Sdim
368249259Sdim private:
369249259Sdim  /// Collection of on the fly FPPassManagers. These managers manage
370249259Sdim  /// function passes that are required by module passes.
371249259Sdim  std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
372249259Sdim};
373249259Sdim
374249259Sdimchar MPPassManager::ID = 0;
375249259Sdim//===----------------------------------------------------------------------===//
376249259Sdim// PassManagerImpl
377249259Sdim//
378249259Sdim
379249259Sdim/// PassManagerImpl manages MPPassManagers
380249259Sdimclass PassManagerImpl : public Pass,
381249259Sdim                        public PMDataManager,
382249259Sdim                        public PMTopLevelManager {
383249259Sdim  virtual void anchor();
384249259Sdim
385249259Sdimpublic:
386249259Sdim  static char ID;
387249259Sdim  explicit PassManagerImpl() :
388249259Sdim    Pass(PT_PassManager, ID), PMDataManager(),
389249259Sdim                              PMTopLevelManager(new MPPassManager()) {}
390249259Sdim
391249259Sdim  /// add - Add a pass to the queue of passes to run.  This passes ownership of
392249259Sdim  /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
393249259Sdim  /// will be destroyed as well, so there is no need to delete the pass.  This
394249259Sdim  /// implies that all passes MUST be allocated with 'new'.
395249259Sdim  void add(Pass *P) {
396249259Sdim    schedulePass(P);
397249259Sdim  }
398249259Sdim
399249259Sdim  /// createPrinterPass - Get a module printer pass.
400249259Sdim  Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
401249259Sdim    return createPrintModulePass(&O, false, Banner);
402249259Sdim  }
403249259Sdim
404249259Sdim  /// run - Execute all of the passes scheduled for execution.  Keep track of
405249259Sdim  /// whether any of the passes modifies the module, and if so, return true.
406249259Sdim  bool run(Module &M);
407249259Sdim
408249259Sdim  using llvm::Pass::doInitialization;
409249259Sdim  using llvm::Pass::doFinalization;
410249259Sdim
411249259Sdim  /// doInitialization - Run all of the initializers for the module passes.
412249259Sdim  ///
413249259Sdim  bool doInitialization();
414249259Sdim
415249259Sdim  /// doFinalization - Run all of the finalizers for the module passes.
416249259Sdim  ///
417249259Sdim  bool doFinalization();
418249259Sdim
419249259Sdim  /// Pass Manager itself does not invalidate any analysis info.
420249259Sdim  void getAnalysisUsage(AnalysisUsage &Info) const {
421249259Sdim    Info.setPreservesAll();
422249259Sdim  }
423249259Sdim
424249259Sdim  virtual PMDataManager *getAsPMDataManager() { return this; }
425249259Sdim  virtual Pass *getAsPass() { return this; }
426249259Sdim  virtual PassManagerType getTopLevelPassManagerType() {
427249259Sdim    return PMT_ModulePassManager;
428249259Sdim  }
429249259Sdim
430249259Sdim  MPPassManager *getContainedManager(unsigned N) {
431249259Sdim    assert(N < PassManagers.size() && "Pass number out of range!");
432249259Sdim    MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
433249259Sdim    return MP;
434249259Sdim  }
435249259Sdim};
436249259Sdim
437249259Sdimvoid PassManagerImpl::anchor() {}
438249259Sdim
439249259Sdimchar PassManagerImpl::ID = 0;
440249259Sdim} // End of llvm namespace
441249259Sdim
442249259Sdimnamespace {
443249259Sdim
444249259Sdim//===----------------------------------------------------------------------===//
445249259Sdim/// TimingInfo Class - This class is used to calculate information about the
446249259Sdim/// amount of time each pass takes to execute.  This only happens when
447249259Sdim/// -time-passes is enabled on the command line.
448249259Sdim///
449249259Sdim
450249259Sdimstatic ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
451249259Sdim
452249259Sdimclass TimingInfo {
453249259Sdim  DenseMap<Pass*, Timer*> TimingData;
454249259Sdim  TimerGroup TG;
455249259Sdimpublic:
456249259Sdim  // Use 'create' member to get this.
457249259Sdim  TimingInfo() : TG("... Pass execution timing report ...") {}
458249259Sdim
459249259Sdim  // TimingDtor - Print out information about timing information
460249259Sdim  ~TimingInfo() {
461249259Sdim    // Delete all of the timers, which accumulate their info into the
462249259Sdim    // TimerGroup.
463249259Sdim    for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
464249259Sdim         E = TimingData.end(); I != E; ++I)
465249259Sdim      delete I->second;
466249259Sdim    // TimerGroup is deleted next, printing the report.
467249259Sdim  }
468249259Sdim
469249259Sdim  // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
470249259Sdim  // to a non null value (if the -time-passes option is enabled) or it leaves it
471249259Sdim  // null.  It may be called multiple times.
472249259Sdim  static void createTheTimeInfo();
473249259Sdim
474249259Sdim  /// getPassTimer - Return the timer for the specified pass if it exists.
475249259Sdim  Timer *getPassTimer(Pass *P) {
476249259Sdim    if (P->getAsPMDataManager())
477249259Sdim      return 0;
478249259Sdim
479249259Sdim    sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
480249259Sdim    Timer *&T = TimingData[P];
481249259Sdim    if (T == 0)
482249259Sdim      T = new Timer(P->getPassName(), TG);
483249259Sdim    return T;
484249259Sdim  }
485249259Sdim};
486249259Sdim
487249259Sdim} // End of anon namespace
488249259Sdim
489249259Sdimstatic TimingInfo *TheTimeInfo;
490249259Sdim
491249259Sdim//===----------------------------------------------------------------------===//
492249259Sdim// PMTopLevelManager implementation
493249259Sdim
494249259Sdim/// Initialize top level manager. Create first pass manager.
495249259SdimPMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
496249259Sdim  PMDM->setTopLevelManager(this);
497249259Sdim  addPassManager(PMDM);
498249259Sdim  activeStack.push(PMDM);
499249259Sdim}
500249259Sdim
501249259Sdim/// Set pass P as the last user of the given analysis passes.
502249259Sdimvoid
503249259SdimPMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
504249259Sdim  unsigned PDepth = 0;
505249259Sdim  if (P->getResolver())
506249259Sdim    PDepth = P->getResolver()->getPMDataManager().getDepth();
507249259Sdim
508249259Sdim  for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
509249259Sdim         E = AnalysisPasses.end(); I != E; ++I) {
510249259Sdim    Pass *AP = *I;
511249259Sdim    LastUser[AP] = P;
512249259Sdim
513249259Sdim    if (P == AP)
514249259Sdim      continue;
515249259Sdim
516249259Sdim    // Update the last users of passes that are required transitive by AP.
517249259Sdim    AnalysisUsage *AnUsage = findAnalysisUsage(AP);
518249259Sdim    const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
519249259Sdim    SmallVector<Pass *, 12> LastUses;
520249259Sdim    SmallVector<Pass *, 12> LastPMUses;
521249259Sdim    for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
522249259Sdim         E = IDs.end(); I != E; ++I) {
523249259Sdim      Pass *AnalysisPass = findAnalysisPass(*I);
524249259Sdim      assert(AnalysisPass && "Expected analysis pass to exist.");
525249259Sdim      AnalysisResolver *AR = AnalysisPass->getResolver();
526249259Sdim      assert(AR && "Expected analysis resolver to exist.");
527249259Sdim      unsigned APDepth = AR->getPMDataManager().getDepth();
528249259Sdim
529249259Sdim      if (PDepth == APDepth)
530249259Sdim        LastUses.push_back(AnalysisPass);
531249259Sdim      else if (PDepth > APDepth)
532249259Sdim        LastPMUses.push_back(AnalysisPass);
533249259Sdim    }
534249259Sdim
535249259Sdim    setLastUser(LastUses, P);
536249259Sdim
537249259Sdim    // If this pass has a corresponding pass manager, push higher level
538249259Sdim    // analysis to this pass manager.
539249259Sdim    if (P->getResolver())
540249259Sdim      setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
541249259Sdim
542249259Sdim
543249259Sdim    // If AP is the last user of other passes then make P last user of
544249259Sdim    // such passes.
545249259Sdim    for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
546249259Sdim           LUE = LastUser.end(); LUI != LUE; ++LUI) {
547249259Sdim      if (LUI->second == AP)
548249259Sdim        // DenseMap iterator is not invalidated here because
549249259Sdim        // this is just updating existing entries.
550249259Sdim        LastUser[LUI->first] = P;
551249259Sdim    }
552249259Sdim  }
553249259Sdim}
554249259Sdim
555249259Sdim/// Collect passes whose last user is P
556249259Sdimvoid PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
557249259Sdim                                        Pass *P) {
558249259Sdim  DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
559249259Sdim    InversedLastUser.find(P);
560249259Sdim  if (DMI == InversedLastUser.end())
561249259Sdim    return;
562249259Sdim
563249259Sdim  SmallPtrSet<Pass *, 8> &LU = DMI->second;
564249259Sdim  for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
565249259Sdim         E = LU.end(); I != E; ++I) {
566249259Sdim    LastUses.push_back(*I);
567249259Sdim  }
568249259Sdim
569249259Sdim}
570249259Sdim
571249259SdimAnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
572249259Sdim  AnalysisUsage *AnUsage = NULL;
573249259Sdim  DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
574249259Sdim  if (DMI != AnUsageMap.end())
575249259Sdim    AnUsage = DMI->second;
576249259Sdim  else {
577249259Sdim    AnUsage = new AnalysisUsage();
578249259Sdim    P->getAnalysisUsage(*AnUsage);
579249259Sdim    AnUsageMap[P] = AnUsage;
580249259Sdim  }
581249259Sdim  return AnUsage;
582249259Sdim}
583249259Sdim
584249259Sdim/// Schedule pass P for execution. Make sure that passes required by
585249259Sdim/// P are run before P is run. Update analysis info maintained by
586249259Sdim/// the manager. Remove dead passes. This is a recursive function.
587249259Sdimvoid PMTopLevelManager::schedulePass(Pass *P) {
588249259Sdim
589249259Sdim  // TODO : Allocate function manager for this pass, other wise required set
590249259Sdim  // may be inserted into previous function manager
591249259Sdim
592249259Sdim  // Give pass a chance to prepare the stage.
593249259Sdim  P->preparePassManager(activeStack);
594249259Sdim
595249259Sdim  // If P is an analysis pass and it is available then do not
596249259Sdim  // generate the analysis again. Stale analysis info should not be
597249259Sdim  // available at this point.
598249259Sdim  const PassInfo *PI =
599249259Sdim    PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
600249259Sdim  if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
601249259Sdim    delete P;
602249259Sdim    return;
603249259Sdim  }
604249259Sdim
605249259Sdim  AnalysisUsage *AnUsage = findAnalysisUsage(P);
606249259Sdim
607249259Sdim  bool checkAnalysis = true;
608249259Sdim  while (checkAnalysis) {
609249259Sdim    checkAnalysis = false;
610249259Sdim
611249259Sdim    const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
612249259Sdim    for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
613249259Sdim           E = RequiredSet.end(); I != E; ++I) {
614249259Sdim
615249259Sdim      Pass *AnalysisPass = findAnalysisPass(*I);
616249259Sdim      if (!AnalysisPass) {
617249259Sdim        const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
618249259Sdim
619249259Sdim        if (PI == NULL) {
620249259Sdim          // Pass P is not in the global PassRegistry
621249259Sdim          dbgs() << "Pass '"  << P->getPassName() << "' is not initialized." << "\n";
622249259Sdim          dbgs() << "Verify if there is a pass dependency cycle." << "\n";
623249259Sdim          dbgs() << "Required Passes:" << "\n";
624249259Sdim          for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
625249259Sdim                 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
626249259Sdim            Pass *AnalysisPass2 = findAnalysisPass(*I2);
627249259Sdim            if (AnalysisPass2) {
628249259Sdim              dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
629249259Sdim            } else {
630249259Sdim              dbgs() << "\t"   << "Error: Required pass not found! Possible causes:"  << "\n";
631249259Sdim              dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)"    << "\n";
632249259Sdim              dbgs() << "\t\t" << "- Corruption of the global PassRegistry"           << "\n";
633249259Sdim            }
634249259Sdim          }
635249259Sdim        }
636249259Sdim
637249259Sdim        assert(PI && "Expected required passes to be initialized");
638249259Sdim        AnalysisPass = PI->createPass();
639249259Sdim        if (P->getPotentialPassManagerType () ==
640249259Sdim            AnalysisPass->getPotentialPassManagerType())
641249259Sdim          // Schedule analysis pass that is managed by the same pass manager.
642249259Sdim          schedulePass(AnalysisPass);
643249259Sdim        else if (P->getPotentialPassManagerType () >
644249259Sdim                 AnalysisPass->getPotentialPassManagerType()) {
645249259Sdim          // Schedule analysis pass that is managed by a new manager.
646249259Sdim          schedulePass(AnalysisPass);
647249259Sdim          // Recheck analysis passes to ensure that required analyses that
648249259Sdim          // are already checked are still available.
649249259Sdim          checkAnalysis = true;
650249259Sdim        } else
651249259Sdim          // Do not schedule this analysis. Lower level analsyis
652249259Sdim          // passes are run on the fly.
653249259Sdim          delete AnalysisPass;
654249259Sdim      }
655249259Sdim    }
656249259Sdim  }
657249259Sdim
658249259Sdim  // Now all required passes are available.
659249259Sdim  if (ImmutablePass *IP = P->getAsImmutablePass()) {
660249259Sdim    // P is a immutable pass and it will be managed by this
661249259Sdim    // top level manager. Set up analysis resolver to connect them.
662249259Sdim    PMDataManager *DM = getAsPMDataManager();
663249259Sdim    AnalysisResolver *AR = new AnalysisResolver(*DM);
664249259Sdim    P->setResolver(AR);
665249259Sdim    DM->initializeAnalysisImpl(P);
666249259Sdim    addImmutablePass(IP);
667249259Sdim    DM->recordAvailableAnalysis(IP);
668249259Sdim    return;
669249259Sdim  }
670249259Sdim
671249259Sdim  if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
672249259Sdim    Pass *PP = P->createPrinterPass(
673249259Sdim      dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
674249259Sdim    PP->assignPassManager(activeStack, getTopLevelPassManagerType());
675249259Sdim  }
676249259Sdim
677249259Sdim  // Add the requested pass to the best available pass manager.
678249259Sdim  P->assignPassManager(activeStack, getTopLevelPassManagerType());
679249259Sdim
680249259Sdim  if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
681249259Sdim    Pass *PP = P->createPrinterPass(
682249259Sdim      dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
683249259Sdim    PP->assignPassManager(activeStack, getTopLevelPassManagerType());
684249259Sdim  }
685249259Sdim}
686249259Sdim
687249259Sdim/// Find the pass that implements Analysis AID. Search immutable
688249259Sdim/// passes and all pass managers. If desired pass is not found
689249259Sdim/// then return NULL.
690249259SdimPass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
691249259Sdim
692249259Sdim  // Check pass managers
693249259Sdim  for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
694249259Sdim         E = PassManagers.end(); I != E; ++I)
695249259Sdim    if (Pass *P = (*I)->findAnalysisPass(AID, false))
696249259Sdim      return P;
697249259Sdim
698249259Sdim  // Check other pass managers
699249259Sdim  for (SmallVectorImpl<PMDataManager *>::iterator
700249259Sdim         I = IndirectPassManagers.begin(),
701249259Sdim         E = IndirectPassManagers.end(); I != E; ++I)
702249259Sdim    if (Pass *P = (*I)->findAnalysisPass(AID, false))
703249259Sdim      return P;
704249259Sdim
705249259Sdim  // Check the immutable passes. Iterate in reverse order so that we find
706249259Sdim  // the most recently registered passes first.
707249259Sdim  for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
708249259Sdim       ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
709249259Sdim    AnalysisID PI = (*I)->getPassID();
710249259Sdim    if (PI == AID)
711249259Sdim      return *I;
712249259Sdim
713249259Sdim    // If Pass not found then check the interfaces implemented by Immutable Pass
714249259Sdim    const PassInfo *PassInf =
715249259Sdim      PassRegistry::getPassRegistry()->getPassInfo(PI);
716249259Sdim    assert(PassInf && "Expected all immutable passes to be initialized");
717249259Sdim    const std::vector<const PassInfo*> &ImmPI =
718249259Sdim      PassInf->getInterfacesImplemented();
719249259Sdim    for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
720249259Sdim         EE = ImmPI.end(); II != EE; ++II) {
721249259Sdim      if ((*II)->getTypeInfo() == AID)
722249259Sdim        return *I;
723249259Sdim    }
724249259Sdim  }
725249259Sdim
726249259Sdim  return 0;
727249259Sdim}
728249259Sdim
729249259Sdim// Print passes managed by this top level manager.
730249259Sdimvoid PMTopLevelManager::dumpPasses() const {
731249259Sdim
732249259Sdim  if (PassDebugging < Structure)
733249259Sdim    return;
734249259Sdim
735249259Sdim  // Print out the immutable passes
736249259Sdim  for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
737249259Sdim    ImmutablePasses[i]->dumpPassStructure(0);
738249259Sdim  }
739249259Sdim
740249259Sdim  // Every class that derives from PMDataManager also derives from Pass
741249259Sdim  // (sometimes indirectly), but there's no inheritance relationship
742249259Sdim  // between PMDataManager and Pass, so we have to getAsPass to get
743249259Sdim  // from a PMDataManager* to a Pass*.
744249259Sdim  for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
745249259Sdim         E = PassManagers.end(); I != E; ++I)
746249259Sdim    (*I)->getAsPass()->dumpPassStructure(1);
747249259Sdim}
748249259Sdim
749249259Sdimvoid PMTopLevelManager::dumpArguments() const {
750249259Sdim
751249259Sdim  if (PassDebugging < Arguments)
752249259Sdim    return;
753249259Sdim
754249259Sdim  dbgs() << "Pass Arguments: ";
755249259Sdim  for (SmallVector<ImmutablePass *, 8>::const_iterator I =
756249259Sdim       ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
757249259Sdim    if (const PassInfo *PI =
758249259Sdim        PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
759249259Sdim      assert(PI && "Expected all immutable passes to be initialized");
760249259Sdim      if (!PI->isAnalysisGroup())
761249259Sdim        dbgs() << " -" << PI->getPassArgument();
762249259Sdim    }
763249259Sdim  for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
764249259Sdim         E = PassManagers.end(); I != E; ++I)
765249259Sdim    (*I)->dumpPassArguments();
766249259Sdim  dbgs() << "\n";
767249259Sdim}
768249259Sdim
769249259Sdimvoid PMTopLevelManager::initializeAllAnalysisInfo() {
770249259Sdim  for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
771249259Sdim         E = PassManagers.end(); I != E; ++I)
772249259Sdim    (*I)->initializeAnalysisInfo();
773249259Sdim
774249259Sdim  // Initailize other pass managers
775249259Sdim  for (SmallVectorImpl<PMDataManager *>::iterator
776249259Sdim       I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
777249259Sdim       I != E; ++I)
778249259Sdim    (*I)->initializeAnalysisInfo();
779249259Sdim
780249259Sdim  for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
781249259Sdim        DME = LastUser.end(); DMI != DME; ++DMI) {
782249259Sdim    DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
783249259Sdim      InversedLastUser.find(DMI->second);
784249259Sdim    if (InvDMI != InversedLastUser.end()) {
785249259Sdim      SmallPtrSet<Pass *, 8> &L = InvDMI->second;
786249259Sdim      L.insert(DMI->first);
787249259Sdim    } else {
788249259Sdim      SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
789249259Sdim      InversedLastUser[DMI->second] = L;
790249259Sdim    }
791249259Sdim  }
792249259Sdim}
793249259Sdim
794249259Sdim/// Destructor
795249259SdimPMTopLevelManager::~PMTopLevelManager() {
796249259Sdim  for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
797249259Sdim         E = PassManagers.end(); I != E; ++I)
798249259Sdim    delete *I;
799249259Sdim
800249259Sdim  for (SmallVectorImpl<ImmutablePass *>::iterator
801249259Sdim         I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
802249259Sdim    delete *I;
803249259Sdim
804249259Sdim  for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
805249259Sdim         DME = AnUsageMap.end(); DMI != DME; ++DMI)
806249259Sdim    delete DMI->second;
807249259Sdim}
808249259Sdim
809249259Sdim//===----------------------------------------------------------------------===//
810249259Sdim// PMDataManager implementation
811249259Sdim
812249259Sdim/// Augement AvailableAnalysis by adding analysis made available by pass P.
813249259Sdimvoid PMDataManager::recordAvailableAnalysis(Pass *P) {
814249259Sdim  AnalysisID PI = P->getPassID();
815249259Sdim
816249259Sdim  AvailableAnalysis[PI] = P;
817249259Sdim
818249259Sdim  assert(!AvailableAnalysis.empty());
819249259Sdim
820249259Sdim  // This pass is the current implementation of all of the interfaces it
821249259Sdim  // implements as well.
822249259Sdim  const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
823249259Sdim  if (PInf == 0) return;
824249259Sdim  const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
825249259Sdim  for (unsigned i = 0, e = II.size(); i != e; ++i)
826249259Sdim    AvailableAnalysis[II[i]->getTypeInfo()] = P;
827249259Sdim}
828249259Sdim
829249259Sdim// Return true if P preserves high level analysis used by other
830249259Sdim// passes managed by this manager
831249259Sdimbool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
832249259Sdim  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
833249259Sdim  if (AnUsage->getPreservesAll())
834249259Sdim    return true;
835249259Sdim
836249259Sdim  const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
837249259Sdim  for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
838249259Sdim         E = HigherLevelAnalysis.end(); I  != E; ++I) {
839249259Sdim    Pass *P1 = *I;
840249259Sdim    if (P1->getAsImmutablePass() == 0 &&
841249259Sdim        std::find(PreservedSet.begin(), PreservedSet.end(),
842249259Sdim                  P1->getPassID()) ==
843249259Sdim           PreservedSet.end())
844249259Sdim      return false;
845249259Sdim  }
846249259Sdim
847249259Sdim  return true;
848249259Sdim}
849249259Sdim
850249259Sdim/// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
851249259Sdimvoid PMDataManager::verifyPreservedAnalysis(Pass *P) {
852249259Sdim  // Don't do this unless assertions are enabled.
853249259Sdim#ifdef NDEBUG
854249259Sdim  return;
855249259Sdim#endif
856249259Sdim  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
857249259Sdim  const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
858249259Sdim
859249259Sdim  // Verify preserved analysis
860249259Sdim  for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
861249259Sdim         E = PreservedSet.end(); I != E; ++I) {
862249259Sdim    AnalysisID AID = *I;
863249259Sdim    if (Pass *AP = findAnalysisPass(AID, true)) {
864249259Sdim      TimeRegion PassTimer(getPassTimer(AP));
865249259Sdim      AP->verifyAnalysis();
866249259Sdim    }
867249259Sdim  }
868249259Sdim}
869249259Sdim
870249259Sdim/// Remove Analysis not preserved by Pass P
871249259Sdimvoid PMDataManager::removeNotPreservedAnalysis(Pass *P) {
872249259Sdim  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
873249259Sdim  if (AnUsage->getPreservesAll())
874249259Sdim    return;
875249259Sdim
876249259Sdim  const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
877249259Sdim  for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
878249259Sdim         E = AvailableAnalysis.end(); I != E; ) {
879249259Sdim    DenseMap<AnalysisID, Pass*>::iterator Info = I++;
880249259Sdim    if (Info->second->getAsImmutablePass() == 0 &&
881249259Sdim        std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
882249259Sdim        PreservedSet.end()) {
883249259Sdim      // Remove this analysis
884249259Sdim      if (PassDebugging >= Details) {
885249259Sdim        Pass *S = Info->second;
886249259Sdim        dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
887249259Sdim        dbgs() << S->getPassName() << "'\n";
888249259Sdim      }
889249259Sdim      AvailableAnalysis.erase(Info);
890249259Sdim    }
891249259Sdim  }
892249259Sdim
893249259Sdim  // Check inherited analysis also. If P is not preserving analysis
894249259Sdim  // provided by parent manager then remove it here.
895249259Sdim  for (unsigned Index = 0; Index < PMT_Last; ++Index) {
896249259Sdim
897249259Sdim    if (!InheritedAnalysis[Index])
898249259Sdim      continue;
899249259Sdim
900249259Sdim    for (DenseMap<AnalysisID, Pass*>::iterator
901249259Sdim           I = InheritedAnalysis[Index]->begin(),
902249259Sdim           E = InheritedAnalysis[Index]->end(); I != E; ) {
903249259Sdim      DenseMap<AnalysisID, Pass *>::iterator Info = I++;
904249259Sdim      if (Info->second->getAsImmutablePass() == 0 &&
905249259Sdim          std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
906249259Sdim             PreservedSet.end()) {
907249259Sdim        // Remove this analysis
908249259Sdim        if (PassDebugging >= Details) {
909249259Sdim          Pass *S = Info->second;
910249259Sdim          dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
911249259Sdim          dbgs() << S->getPassName() << "'\n";
912249259Sdim        }
913249259Sdim        InheritedAnalysis[Index]->erase(Info);
914249259Sdim      }
915249259Sdim    }
916249259Sdim  }
917249259Sdim}
918249259Sdim
919249259Sdim/// Remove analysis passes that are not used any longer
920249259Sdimvoid PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
921249259Sdim                                     enum PassDebuggingString DBG_STR) {
922249259Sdim
923249259Sdim  SmallVector<Pass *, 12> DeadPasses;
924249259Sdim
925249259Sdim  // If this is a on the fly manager then it does not have TPM.
926249259Sdim  if (!TPM)
927249259Sdim    return;
928249259Sdim
929249259Sdim  TPM->collectLastUses(DeadPasses, P);
930249259Sdim
931249259Sdim  if (PassDebugging >= Details && !DeadPasses.empty()) {
932249259Sdim    dbgs() << " -*- '" <<  P->getPassName();
933249259Sdim    dbgs() << "' is the last user of following pass instances.";
934249259Sdim    dbgs() << " Free these instances\n";
935249259Sdim  }
936249259Sdim
937249259Sdim  for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
938249259Sdim         E = DeadPasses.end(); I != E; ++I)
939249259Sdim    freePass(*I, Msg, DBG_STR);
940249259Sdim}
941249259Sdim
942249259Sdimvoid PMDataManager::freePass(Pass *P, StringRef Msg,
943249259Sdim                             enum PassDebuggingString DBG_STR) {
944249259Sdim  dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
945249259Sdim
946249259Sdim  {
947249259Sdim    // If the pass crashes releasing memory, remember this.
948249259Sdim    PassManagerPrettyStackEntry X(P);
949249259Sdim    TimeRegion PassTimer(getPassTimer(P));
950249259Sdim
951249259Sdim    P->releaseMemory();
952249259Sdim  }
953249259Sdim
954249259Sdim  AnalysisID PI = P->getPassID();
955249259Sdim  if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
956249259Sdim    // Remove the pass itself (if it is not already removed).
957249259Sdim    AvailableAnalysis.erase(PI);
958249259Sdim
959249259Sdim    // Remove all interfaces this pass implements, for which it is also
960249259Sdim    // listed as the available implementation.
961249259Sdim    const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
962249259Sdim    for (unsigned i = 0, e = II.size(); i != e; ++i) {
963249259Sdim      DenseMap<AnalysisID, Pass*>::iterator Pos =
964249259Sdim        AvailableAnalysis.find(II[i]->getTypeInfo());
965249259Sdim      if (Pos != AvailableAnalysis.end() && Pos->second == P)
966249259Sdim        AvailableAnalysis.erase(Pos);
967249259Sdim    }
968249259Sdim  }
969249259Sdim}
970249259Sdim
971249259Sdim/// Add pass P into the PassVector. Update
972249259Sdim/// AvailableAnalysis appropriately if ProcessAnalysis is true.
973249259Sdimvoid PMDataManager::add(Pass *P, bool ProcessAnalysis) {
974249259Sdim  // This manager is going to manage pass P. Set up analysis resolver
975249259Sdim  // to connect them.
976249259Sdim  AnalysisResolver *AR = new AnalysisResolver(*this);
977249259Sdim  P->setResolver(AR);
978249259Sdim
979249259Sdim  // If a FunctionPass F is the last user of ModulePass info M
980249259Sdim  // then the F's manager, not F, records itself as a last user of M.
981249259Sdim  SmallVector<Pass *, 12> TransferLastUses;
982249259Sdim
983249259Sdim  if (!ProcessAnalysis) {
984249259Sdim    // Add pass
985249259Sdim    PassVector.push_back(P);
986249259Sdim    return;
987249259Sdim  }
988249259Sdim
989249259Sdim  // At the moment, this pass is the last user of all required passes.
990249259Sdim  SmallVector<Pass *, 12> LastUses;
991249259Sdim  SmallVector<Pass *, 8> RequiredPasses;
992249259Sdim  SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
993249259Sdim
994249259Sdim  unsigned PDepth = this->getDepth();
995249259Sdim
996249259Sdim  collectRequiredAnalysis(RequiredPasses,
997249259Sdim                          ReqAnalysisNotAvailable, P);
998249259Sdim  for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
999249259Sdim         E = RequiredPasses.end(); I != E; ++I) {
1000249259Sdim    Pass *PRequired = *I;
1001249259Sdim    unsigned RDepth = 0;
1002249259Sdim
1003249259Sdim    assert(PRequired->getResolver() && "Analysis Resolver is not set");
1004249259Sdim    PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1005249259Sdim    RDepth = DM.getDepth();
1006249259Sdim
1007249259Sdim    if (PDepth == RDepth)
1008249259Sdim      LastUses.push_back(PRequired);
1009249259Sdim    else if (PDepth > RDepth) {
1010249259Sdim      // Let the parent claim responsibility of last use
1011249259Sdim      TransferLastUses.push_back(PRequired);
1012249259Sdim      // Keep track of higher level analysis used by this manager.
1013249259Sdim      HigherLevelAnalysis.push_back(PRequired);
1014249259Sdim    } else
1015249259Sdim      llvm_unreachable("Unable to accommodate Required Pass");
1016249259Sdim  }
1017249259Sdim
1018249259Sdim  // Set P as P's last user until someone starts using P.
1019249259Sdim  // However, if P is a Pass Manager then it does not need
1020249259Sdim  // to record its last user.
1021249259Sdim  if (P->getAsPMDataManager() == 0)
1022249259Sdim    LastUses.push_back(P);
1023249259Sdim  TPM->setLastUser(LastUses, P);
1024249259Sdim
1025249259Sdim  if (!TransferLastUses.empty()) {
1026249259Sdim    Pass *My_PM = getAsPass();
1027249259Sdim    TPM->setLastUser(TransferLastUses, My_PM);
1028249259Sdim    TransferLastUses.clear();
1029249259Sdim  }
1030249259Sdim
1031249259Sdim  // Now, take care of required analyses that are not available.
1032249259Sdim  for (SmallVectorImpl<AnalysisID>::iterator
1033249259Sdim         I = ReqAnalysisNotAvailable.begin(),
1034249259Sdim         E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1035249259Sdim    const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1036249259Sdim    Pass *AnalysisPass = PI->createPass();
1037249259Sdim    this->addLowerLevelRequiredPass(P, AnalysisPass);
1038249259Sdim  }
1039249259Sdim
1040249259Sdim  // Take a note of analysis required and made available by this pass.
1041249259Sdim  // Remove the analysis not preserved by this pass
1042249259Sdim  removeNotPreservedAnalysis(P);
1043249259Sdim  recordAvailableAnalysis(P);
1044249259Sdim
1045249259Sdim  // Add pass
1046249259Sdim  PassVector.push_back(P);
1047249259Sdim}
1048249259Sdim
1049249259Sdim
1050249259Sdim/// Populate RP with analysis pass that are required by
1051249259Sdim/// pass P and are available. Populate RP_NotAvail with analysis
1052249259Sdim/// pass that are required by pass P but are not available.
1053249259Sdimvoid PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1054249259Sdim                                       SmallVectorImpl<AnalysisID> &RP_NotAvail,
1055249259Sdim                                            Pass *P) {
1056249259Sdim  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1057249259Sdim  const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1058249259Sdim  for (AnalysisUsage::VectorType::const_iterator
1059249259Sdim         I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1060249259Sdim    if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1061249259Sdim      RP.push_back(AnalysisPass);
1062249259Sdim    else
1063249259Sdim      RP_NotAvail.push_back(*I);
1064249259Sdim  }
1065249259Sdim
1066249259Sdim  const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1067249259Sdim  for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1068249259Sdim         E = IDs.end(); I != E; ++I) {
1069249259Sdim    if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1070249259Sdim      RP.push_back(AnalysisPass);
1071249259Sdim    else
1072249259Sdim      RP_NotAvail.push_back(*I);
1073249259Sdim  }
1074249259Sdim}
1075249259Sdim
1076249259Sdim// All Required analyses should be available to the pass as it runs!  Here
1077249259Sdim// we fill in the AnalysisImpls member of the pass so that it can
1078249259Sdim// successfully use the getAnalysis() method to retrieve the
1079249259Sdim// implementations it needs.
1080249259Sdim//
1081249259Sdimvoid PMDataManager::initializeAnalysisImpl(Pass *P) {
1082249259Sdim  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1083249259Sdim
1084249259Sdim  for (AnalysisUsage::VectorType::const_iterator
1085249259Sdim         I = AnUsage->getRequiredSet().begin(),
1086249259Sdim         E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1087249259Sdim    Pass *Impl = findAnalysisPass(*I, true);
1088249259Sdim    if (Impl == 0)
1089249259Sdim      // This may be analysis pass that is initialized on the fly.
1090249259Sdim      // If that is not the case then it will raise an assert when it is used.
1091249259Sdim      continue;
1092249259Sdim    AnalysisResolver *AR = P->getResolver();
1093249259Sdim    assert(AR && "Analysis Resolver is not set");
1094249259Sdim    AR->addAnalysisImplsPair(*I, Impl);
1095249259Sdim  }
1096249259Sdim}
1097249259Sdim
1098249259Sdim/// Find the pass that implements Analysis AID. If desired pass is not found
1099249259Sdim/// then return NULL.
1100249259SdimPass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1101249259Sdim
1102249259Sdim  // Check if AvailableAnalysis map has one entry.
1103249259Sdim  DenseMap<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
1104249259Sdim
1105249259Sdim  if (I != AvailableAnalysis.end())
1106249259Sdim    return I->second;
1107249259Sdim
1108249259Sdim  // Search Parents through TopLevelManager
1109249259Sdim  if (SearchParent)
1110249259Sdim    return TPM->findAnalysisPass(AID);
1111249259Sdim
1112249259Sdim  return NULL;
1113249259Sdim}
1114249259Sdim
1115249259Sdim// Print list of passes that are last used by P.
1116249259Sdimvoid PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1117249259Sdim
1118249259Sdim  SmallVector<Pass *, 12> LUses;
1119249259Sdim
1120249259Sdim  // If this is a on the fly manager then it does not have TPM.
1121249259Sdim  if (!TPM)
1122249259Sdim    return;
1123249259Sdim
1124249259Sdim  TPM->collectLastUses(LUses, P);
1125249259Sdim
1126249259Sdim  for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1127249259Sdim         E = LUses.end(); I != E; ++I) {
1128249259Sdim    llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1129249259Sdim    (*I)->dumpPassStructure(0);
1130249259Sdim  }
1131249259Sdim}
1132249259Sdim
1133249259Sdimvoid PMDataManager::dumpPassArguments() const {
1134249259Sdim  for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1135249259Sdim        E = PassVector.end(); I != E; ++I) {
1136249259Sdim    if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1137249259Sdim      PMD->dumpPassArguments();
1138249259Sdim    else
1139249259Sdim      if (const PassInfo *PI =
1140249259Sdim            PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1141249259Sdim        if (!PI->isAnalysisGroup())
1142249259Sdim          dbgs() << " -" << PI->getPassArgument();
1143249259Sdim  }
1144249259Sdim}
1145249259Sdim
1146249259Sdimvoid PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1147249259Sdim                                 enum PassDebuggingString S2,
1148249259Sdim                                 StringRef Msg) {
1149249259Sdim  if (PassDebugging < Executions)
1150249259Sdim    return;
1151249259Sdim  dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1152249259Sdim  switch (S1) {
1153249259Sdim  case EXECUTION_MSG:
1154249259Sdim    dbgs() << "Executing Pass '" << P->getPassName();
1155249259Sdim    break;
1156249259Sdim  case MODIFICATION_MSG:
1157249259Sdim    dbgs() << "Made Modification '" << P->getPassName();
1158249259Sdim    break;
1159249259Sdim  case FREEING_MSG:
1160249259Sdim    dbgs() << " Freeing Pass '" << P->getPassName();
1161249259Sdim    break;
1162249259Sdim  default:
1163249259Sdim    break;
1164249259Sdim  }
1165249259Sdim  switch (S2) {
1166249259Sdim  case ON_BASICBLOCK_MSG:
1167249259Sdim    dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1168249259Sdim    break;
1169249259Sdim  case ON_FUNCTION_MSG:
1170249259Sdim    dbgs() << "' on Function '" << Msg << "'...\n";
1171249259Sdim    break;
1172249259Sdim  case ON_MODULE_MSG:
1173249259Sdim    dbgs() << "' on Module '"  << Msg << "'...\n";
1174249259Sdim    break;
1175249259Sdim  case ON_REGION_MSG:
1176249259Sdim    dbgs() << "' on Region '"  << Msg << "'...\n";
1177249259Sdim    break;
1178249259Sdim  case ON_LOOP_MSG:
1179249259Sdim    dbgs() << "' on Loop '" << Msg << "'...\n";
1180249259Sdim    break;
1181249259Sdim  case ON_CG_MSG:
1182249259Sdim    dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1183249259Sdim    break;
1184249259Sdim  default:
1185249259Sdim    break;
1186249259Sdim  }
1187249259Sdim}
1188249259Sdim
1189249259Sdimvoid PMDataManager::dumpRequiredSet(const Pass *P) const {
1190249259Sdim  if (PassDebugging < Details)
1191249259Sdim    return;
1192249259Sdim
1193249259Sdim  AnalysisUsage analysisUsage;
1194249259Sdim  P->getAnalysisUsage(analysisUsage);
1195249259Sdim  dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1196249259Sdim}
1197249259Sdim
1198249259Sdimvoid PMDataManager::dumpPreservedSet(const Pass *P) const {
1199249259Sdim  if (PassDebugging < Details)
1200249259Sdim    return;
1201249259Sdim
1202249259Sdim  AnalysisUsage analysisUsage;
1203249259Sdim  P->getAnalysisUsage(analysisUsage);
1204249259Sdim  dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1205249259Sdim}
1206249259Sdim
1207249259Sdimvoid PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1208249259Sdim                                   const AnalysisUsage::VectorType &Set) const {
1209249259Sdim  assert(PassDebugging >= Details);
1210249259Sdim  if (Set.empty())
1211249259Sdim    return;
1212249259Sdim  dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1213249259Sdim  for (unsigned i = 0; i != Set.size(); ++i) {
1214249259Sdim    if (i) dbgs() << ',';
1215249259Sdim    const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1216249259Sdim    if (!PInf) {
1217249259Sdim      // Some preserved passes, such as AliasAnalysis, may not be initialized by
1218249259Sdim      // all drivers.
1219249259Sdim      dbgs() << " Uninitialized Pass";
1220249259Sdim      continue;
1221249259Sdim    }
1222249259Sdim    dbgs() << ' ' << PInf->getPassName();
1223249259Sdim  }
1224249259Sdim  dbgs() << '\n';
1225249259Sdim}
1226249259Sdim
1227249259Sdim/// Add RequiredPass into list of lower level passes required by pass P.
1228249259Sdim/// RequiredPass is run on the fly by Pass Manager when P requests it
1229249259Sdim/// through getAnalysis interface.
1230249259Sdim/// This should be handled by specific pass manager.
1231249259Sdimvoid PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1232249259Sdim  if (TPM) {
1233249259Sdim    TPM->dumpArguments();
1234249259Sdim    TPM->dumpPasses();
1235249259Sdim  }
1236249259Sdim
1237249259Sdim  // Module Level pass may required Function Level analysis info
1238249259Sdim  // (e.g. dominator info). Pass manager uses on the fly function pass manager
1239249259Sdim  // to provide this on demand. In that case, in Pass manager terminology,
1240249259Sdim  // module level pass is requiring lower level analysis info managed by
1241249259Sdim  // lower level pass manager.
1242249259Sdim
1243249259Sdim  // When Pass manager is not able to order required analysis info, Pass manager
1244249259Sdim  // checks whether any lower level manager will be able to provide this
1245249259Sdim  // analysis info on demand or not.
1246249259Sdim#ifndef NDEBUG
1247249259Sdim  dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1248249259Sdim  dbgs() << "' required by '" << P->getPassName() << "'\n";
1249249259Sdim#endif
1250249259Sdim  llvm_unreachable("Unable to schedule pass");
1251249259Sdim}
1252249259Sdim
1253249259SdimPass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1254249259Sdim  llvm_unreachable("Unable to find on the fly pass");
1255249259Sdim}
1256249259Sdim
1257249259Sdim// Destructor
1258249259SdimPMDataManager::~PMDataManager() {
1259249259Sdim  for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1260249259Sdim         E = PassVector.end(); I != E; ++I)
1261249259Sdim    delete *I;
1262249259Sdim}
1263249259Sdim
1264249259Sdim//===----------------------------------------------------------------------===//
1265249259Sdim// NOTE: Is this the right place to define this method ?
1266249259Sdim// getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1267249259SdimPass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1268249259Sdim  return PM.findAnalysisPass(ID, dir);
1269249259Sdim}
1270249259Sdim
1271249259SdimPass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1272249259Sdim                                     Function &F) {
1273249259Sdim  return PM.getOnTheFlyPass(P, AnalysisPI, F);
1274249259Sdim}
1275249259Sdim
1276249259Sdim//===----------------------------------------------------------------------===//
1277249259Sdim// BBPassManager implementation
1278249259Sdim
1279249259Sdim/// Execute all of the passes scheduled for execution by invoking
1280249259Sdim/// runOnBasicBlock method.  Keep track of whether any of the passes modifies
1281249259Sdim/// the function, and if so, return true.
1282249259Sdimbool BBPassManager::runOnFunction(Function &F) {
1283249259Sdim  if (F.isDeclaration())
1284249259Sdim    return false;
1285249259Sdim
1286249259Sdim  bool Changed = doInitialization(F);
1287249259Sdim
1288249259Sdim  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1289249259Sdim    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1290249259Sdim      BasicBlockPass *BP = getContainedPass(Index);
1291249259Sdim      bool LocalChanged = false;
1292249259Sdim
1293249259Sdim      dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1294249259Sdim      dumpRequiredSet(BP);
1295249259Sdim
1296249259Sdim      initializeAnalysisImpl(BP);
1297249259Sdim
1298249259Sdim      {
1299249259Sdim        // If the pass crashes, remember this.
1300249259Sdim        PassManagerPrettyStackEntry X(BP, *I);
1301249259Sdim        TimeRegion PassTimer(getPassTimer(BP));
1302249259Sdim
1303249259Sdim        LocalChanged |= BP->runOnBasicBlock(*I);
1304249259Sdim      }
1305249259Sdim
1306249259Sdim      Changed |= LocalChanged;
1307249259Sdim      if (LocalChanged)
1308249259Sdim        dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1309249259Sdim                     I->getName());
1310249259Sdim      dumpPreservedSet(BP);
1311249259Sdim
1312249259Sdim      verifyPreservedAnalysis(BP);
1313249259Sdim      removeNotPreservedAnalysis(BP);
1314249259Sdim      recordAvailableAnalysis(BP);
1315249259Sdim      removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1316249259Sdim    }
1317249259Sdim
1318249259Sdim  return doFinalization(F) || Changed;
1319249259Sdim}
1320249259Sdim
1321249259Sdim// Implement doInitialization and doFinalization
1322249259Sdimbool BBPassManager::doInitialization(Module &M) {
1323249259Sdim  bool Changed = false;
1324249259Sdim
1325249259Sdim  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1326249259Sdim    Changed |= getContainedPass(Index)->doInitialization(M);
1327249259Sdim
1328249259Sdim  return Changed;
1329249259Sdim}
1330249259Sdim
1331249259Sdimbool BBPassManager::doFinalization(Module &M) {
1332249259Sdim  bool Changed = false;
1333249259Sdim
1334249259Sdim  for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1335249259Sdim    Changed |= getContainedPass(Index)->doFinalization(M);
1336249259Sdim
1337249259Sdim  return Changed;
1338249259Sdim}
1339249259Sdim
1340249259Sdimbool BBPassManager::doInitialization(Function &F) {
1341249259Sdim  bool Changed = false;
1342249259Sdim
1343249259Sdim  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1344249259Sdim    BasicBlockPass *BP = getContainedPass(Index);
1345249259Sdim    Changed |= BP->doInitialization(F);
1346249259Sdim  }
1347249259Sdim
1348249259Sdim  return Changed;
1349249259Sdim}
1350249259Sdim
1351249259Sdimbool BBPassManager::doFinalization(Function &F) {
1352249259Sdim  bool Changed = false;
1353249259Sdim
1354249259Sdim  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1355249259Sdim    BasicBlockPass *BP = getContainedPass(Index);
1356249259Sdim    Changed |= BP->doFinalization(F);
1357249259Sdim  }
1358249259Sdim
1359249259Sdim  return Changed;
1360249259Sdim}
1361249259Sdim
1362249259Sdim
1363249259Sdim//===----------------------------------------------------------------------===//
1364249259Sdim// FunctionPassManager implementation
1365249259Sdim
1366249259Sdim/// Create new Function pass manager
1367249259SdimFunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1368249259Sdim  FPM = new FunctionPassManagerImpl();
1369249259Sdim  // FPM is the top level manager.
1370249259Sdim  FPM->setTopLevelManager(FPM);
1371249259Sdim
1372249259Sdim  AnalysisResolver *AR = new AnalysisResolver(*FPM);
1373249259Sdim  FPM->setResolver(AR);
1374249259Sdim}
1375249259Sdim
1376249259SdimFunctionPassManager::~FunctionPassManager() {
1377249259Sdim  delete FPM;
1378249259Sdim}
1379249259Sdim
1380249259Sdim/// add - Add a pass to the queue of passes to run.  This passes
1381249259Sdim/// ownership of the Pass to the PassManager.  When the
1382249259Sdim/// PassManager_X is destroyed, the pass will be destroyed as well, so
1383249259Sdim/// there is no need to delete the pass. (TODO delete passes.)
1384249259Sdim/// This implies that all passes MUST be allocated with 'new'.
1385249259Sdimvoid FunctionPassManager::add(Pass *P) {
1386249259Sdim  FPM->add(P);
1387249259Sdim}
1388249259Sdim
1389249259Sdim/// run - Execute all of the passes scheduled for execution.  Keep
1390249259Sdim/// track of whether any of the passes modifies the function, and if
1391249259Sdim/// so, return true.
1392249259Sdim///
1393249259Sdimbool FunctionPassManager::run(Function &F) {
1394249259Sdim  if (F.isMaterializable()) {
1395249259Sdim    std::string errstr;
1396249259Sdim    if (F.Materialize(&errstr))
1397249259Sdim      report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1398249259Sdim  }
1399249259Sdim  return FPM->run(F);
1400249259Sdim}
1401249259Sdim
1402249259Sdim
1403249259Sdim/// doInitialization - Run all of the initializers for the function passes.
1404249259Sdim///
1405249259Sdimbool FunctionPassManager::doInitialization() {
1406249259Sdim  return FPM->doInitialization(*M);
1407249259Sdim}
1408249259Sdim
1409249259Sdim/// doFinalization - Run all of the finalizers for the function passes.
1410249259Sdim///
1411249259Sdimbool FunctionPassManager::doFinalization() {
1412249259Sdim  return FPM->doFinalization(*M);
1413249259Sdim}
1414249259Sdim
1415249259Sdim//===----------------------------------------------------------------------===//
1416249259Sdim// FunctionPassManagerImpl implementation
1417249259Sdim//
1418249259Sdimbool FunctionPassManagerImpl::doInitialization(Module &M) {
1419249259Sdim  bool Changed = false;
1420249259Sdim
1421249259Sdim  dumpArguments();
1422249259Sdim  dumpPasses();
1423249259Sdim
1424249259Sdim  SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1425249259Sdim  for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1426249259Sdim       E = IPV.end(); I != E; ++I) {
1427249259Sdim    Changed |= (*I)->doInitialization(M);
1428249259Sdim  }
1429249259Sdim
1430249259Sdim  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1431249259Sdim    Changed |= getContainedManager(Index)->doInitialization(M);
1432249259Sdim
1433249259Sdim  return Changed;
1434249259Sdim}
1435249259Sdim
1436249259Sdimbool FunctionPassManagerImpl::doFinalization(Module &M) {
1437249259Sdim  bool Changed = false;
1438249259Sdim
1439249259Sdim  for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1440249259Sdim    Changed |= getContainedManager(Index)->doFinalization(M);
1441249259Sdim
1442249259Sdim  SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1443249259Sdim  for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1444249259Sdim       E = IPV.end(); I != E; ++I) {
1445249259Sdim    Changed |= (*I)->doFinalization(M);
1446249259Sdim  }
1447249259Sdim
1448249259Sdim  return Changed;
1449249259Sdim}
1450249259Sdim
1451249259Sdim/// cleanup - After running all passes, clean up pass manager cache.
1452249259Sdimvoid FPPassManager::cleanup() {
1453249259Sdim for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1454249259Sdim    FunctionPass *FP = getContainedPass(Index);
1455249259Sdim    AnalysisResolver *AR = FP->getResolver();
1456249259Sdim    assert(AR && "Analysis Resolver is not set");
1457249259Sdim    AR->clearAnalysisImpls();
1458249259Sdim }
1459249259Sdim}
1460249259Sdim
1461249259Sdimvoid FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1462249259Sdim  if (!wasRun)
1463249259Sdim    return;
1464249259Sdim  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1465249259Sdim    FPPassManager *FPPM = getContainedManager(Index);
1466249259Sdim    for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1467249259Sdim      FPPM->getContainedPass(Index)->releaseMemory();
1468249259Sdim    }
1469249259Sdim  }
1470249259Sdim  wasRun = false;
1471249259Sdim}
1472249259Sdim
1473249259Sdim// Execute all the passes managed by this top level manager.
1474249259Sdim// Return true if any function is modified by a pass.
1475249259Sdimbool FunctionPassManagerImpl::run(Function &F) {
1476249259Sdim  bool Changed = false;
1477249259Sdim  TimingInfo::createTheTimeInfo();
1478249259Sdim
1479249259Sdim  initializeAllAnalysisInfo();
1480249259Sdim  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1481249259Sdim    Changed |= getContainedManager(Index)->runOnFunction(F);
1482249259Sdim
1483249259Sdim  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1484249259Sdim    getContainedManager(Index)->cleanup();
1485249259Sdim
1486249259Sdim  wasRun = true;
1487249259Sdim  return Changed;
1488249259Sdim}
1489249259Sdim
1490249259Sdim//===----------------------------------------------------------------------===//
1491249259Sdim// FPPassManager implementation
1492249259Sdim
1493249259Sdimchar FPPassManager::ID = 0;
1494249259Sdim/// Print passes managed by this manager
1495249259Sdimvoid FPPassManager::dumpPassStructure(unsigned Offset) {
1496249259Sdim  dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1497249259Sdim  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1498249259Sdim    FunctionPass *FP = getContainedPass(Index);
1499249259Sdim    FP->dumpPassStructure(Offset + 1);
1500249259Sdim    dumpLastUses(FP, Offset+1);
1501249259Sdim  }
1502249259Sdim}
1503249259Sdim
1504249259Sdim
1505249259Sdim/// Execute all of the passes scheduled for execution by invoking
1506249259Sdim/// runOnFunction method.  Keep track of whether any of the passes modifies
1507249259Sdim/// the function, and if so, return true.
1508249259Sdimbool FPPassManager::runOnFunction(Function &F) {
1509249259Sdim  if (F.isDeclaration())
1510249259Sdim    return false;
1511249259Sdim
1512249259Sdim  bool Changed = false;
1513249259Sdim
1514249259Sdim  // Collect inherited analysis from Module level pass manager.
1515249259Sdim  populateInheritedAnalysis(TPM->activeStack);
1516249259Sdim
1517249259Sdim  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1518249259Sdim    FunctionPass *FP = getContainedPass(Index);
1519249259Sdim    bool LocalChanged = false;
1520249259Sdim
1521249259Sdim    dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1522249259Sdim    dumpRequiredSet(FP);
1523249259Sdim
1524249259Sdim    initializeAnalysisImpl(FP);
1525249259Sdim
1526249259Sdim    {
1527249259Sdim      PassManagerPrettyStackEntry X(FP, F);
1528249259Sdim      TimeRegion PassTimer(getPassTimer(FP));
1529249259Sdim
1530249259Sdim      LocalChanged |= FP->runOnFunction(F);
1531249259Sdim    }
1532249259Sdim
1533249259Sdim    Changed |= LocalChanged;
1534249259Sdim    if (LocalChanged)
1535249259Sdim      dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1536249259Sdim    dumpPreservedSet(FP);
1537249259Sdim
1538249259Sdim    verifyPreservedAnalysis(FP);
1539249259Sdim    removeNotPreservedAnalysis(FP);
1540249259Sdim    recordAvailableAnalysis(FP);
1541249259Sdim    removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1542249259Sdim  }
1543249259Sdim  return Changed;
1544249259Sdim}
1545249259Sdim
1546249259Sdimbool FPPassManager::runOnModule(Module &M) {
1547249259Sdim  bool Changed = false;
1548249259Sdim
1549249259Sdim  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1550249259Sdim    Changed |= runOnFunction(*I);
1551249259Sdim
1552249259Sdim  return Changed;
1553249259Sdim}
1554249259Sdim
1555249259Sdimbool FPPassManager::doInitialization(Module &M) {
1556249259Sdim  bool Changed = false;
1557249259Sdim
1558249259Sdim  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1559249259Sdim    Changed |= getContainedPass(Index)->doInitialization(M);
1560249259Sdim
1561249259Sdim  return Changed;
1562249259Sdim}
1563249259Sdim
1564249259Sdimbool FPPassManager::doFinalization(Module &M) {
1565249259Sdim  bool Changed = false;
1566249259Sdim
1567249259Sdim  for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1568249259Sdim    Changed |= getContainedPass(Index)->doFinalization(M);
1569249259Sdim
1570249259Sdim  return Changed;
1571249259Sdim}
1572249259Sdim
1573249259Sdim//===----------------------------------------------------------------------===//
1574249259Sdim// MPPassManager implementation
1575249259Sdim
1576249259Sdim/// Execute all of the passes scheduled for execution by invoking
1577249259Sdim/// runOnModule method.  Keep track of whether any of the passes modifies
1578249259Sdim/// the module, and if so, return true.
1579249259Sdimbool
1580249259SdimMPPassManager::runOnModule(Module &M) {
1581249259Sdim  bool Changed = false;
1582249259Sdim
1583249259Sdim  // Initialize on-the-fly passes
1584249259Sdim  for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1585249259Sdim       I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1586249259Sdim       I != E; ++I) {
1587249259Sdim    FunctionPassManagerImpl *FPP = I->second;
1588249259Sdim    Changed |= FPP->doInitialization(M);
1589249259Sdim  }
1590249259Sdim
1591249259Sdim  // Initialize module passes
1592249259Sdim  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1593249259Sdim    Changed |= getContainedPass(Index)->doInitialization(M);
1594249259Sdim
1595249259Sdim  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1596249259Sdim    ModulePass *MP = getContainedPass(Index);
1597249259Sdim    bool LocalChanged = false;
1598249259Sdim
1599249259Sdim    dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1600249259Sdim    dumpRequiredSet(MP);
1601249259Sdim
1602249259Sdim    initializeAnalysisImpl(MP);
1603249259Sdim
1604249259Sdim    {
1605249259Sdim      PassManagerPrettyStackEntry X(MP, M);
1606249259Sdim      TimeRegion PassTimer(getPassTimer(MP));
1607249259Sdim
1608249259Sdim      LocalChanged |= MP->runOnModule(M);
1609249259Sdim    }
1610249259Sdim
1611249259Sdim    Changed |= LocalChanged;
1612249259Sdim    if (LocalChanged)
1613249259Sdim      dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1614249259Sdim                   M.getModuleIdentifier());
1615249259Sdim    dumpPreservedSet(MP);
1616249259Sdim
1617249259Sdim    verifyPreservedAnalysis(MP);
1618249259Sdim    removeNotPreservedAnalysis(MP);
1619249259Sdim    recordAvailableAnalysis(MP);
1620249259Sdim    removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1621249259Sdim  }
1622249259Sdim
1623249259Sdim  // Finalize module passes
1624249259Sdim  for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1625249259Sdim    Changed |= getContainedPass(Index)->doFinalization(M);
1626249259Sdim
1627249259Sdim  // Finalize on-the-fly passes
1628249259Sdim  for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1629249259Sdim       I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1630249259Sdim       I != E; ++I) {
1631249259Sdim    FunctionPassManagerImpl *FPP = I->second;
1632249259Sdim    // We don't know when is the last time an on-the-fly pass is run,
1633249259Sdim    // so we need to releaseMemory / finalize here
1634249259Sdim    FPP->releaseMemoryOnTheFly();
1635249259Sdim    Changed |= FPP->doFinalization(M);
1636249259Sdim  }
1637249259Sdim
1638249259Sdim  return Changed;
1639249259Sdim}
1640249259Sdim
1641249259Sdim/// Add RequiredPass into list of lower level passes required by pass P.
1642249259Sdim/// RequiredPass is run on the fly by Pass Manager when P requests it
1643249259Sdim/// through getAnalysis interface.
1644249259Sdimvoid MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1645249259Sdim  assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1646249259Sdim         "Unable to handle Pass that requires lower level Analysis pass");
1647249259Sdim  assert((P->getPotentialPassManagerType() <
1648249259Sdim          RequiredPass->getPotentialPassManagerType()) &&
1649249259Sdim         "Unable to handle Pass that requires lower level Analysis pass");
1650249259Sdim
1651249259Sdim  FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1652249259Sdim  if (!FPP) {
1653249259Sdim    FPP = new FunctionPassManagerImpl();
1654249259Sdim    // FPP is the top level manager.
1655249259Sdim    FPP->setTopLevelManager(FPP);
1656249259Sdim
1657249259Sdim    OnTheFlyManagers[P] = FPP;
1658249259Sdim  }
1659249259Sdim  FPP->add(RequiredPass);
1660249259Sdim
1661249259Sdim  // Register P as the last user of RequiredPass.
1662249259Sdim  if (RequiredPass) {
1663249259Sdim    SmallVector<Pass *, 1> LU;
1664249259Sdim    LU.push_back(RequiredPass);
1665249259Sdim    FPP->setLastUser(LU,  P);
1666249259Sdim  }
1667249259Sdim}
1668249259Sdim
1669249259Sdim/// Return function pass corresponding to PassInfo PI, that is
1670249259Sdim/// required by module pass MP. Instantiate analysis pass, by using
1671249259Sdim/// its runOnFunction() for function F.
1672249259SdimPass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1673249259Sdim  FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1674249259Sdim  assert(FPP && "Unable to find on the fly pass");
1675249259Sdim
1676249259Sdim  FPP->releaseMemoryOnTheFly();
1677249259Sdim  FPP->run(F);
1678249259Sdim  return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1679249259Sdim}
1680249259Sdim
1681249259Sdim
1682249259Sdim//===----------------------------------------------------------------------===//
1683249259Sdim// PassManagerImpl implementation
1684249259Sdim
1685249259Sdim//
1686249259Sdim/// run - Execute all of the passes scheduled for execution.  Keep track of
1687249259Sdim/// whether any of the passes modifies the module, and if so, return true.
1688249259Sdimbool PassManagerImpl::run(Module &M) {
1689249259Sdim  bool Changed = false;
1690249259Sdim  TimingInfo::createTheTimeInfo();
1691249259Sdim
1692249259Sdim  dumpArguments();
1693249259Sdim  dumpPasses();
1694249259Sdim
1695249259Sdim  SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1696249259Sdim  for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1697249259Sdim       E = IPV.end(); I != E; ++I) {
1698249259Sdim    Changed |= (*I)->doInitialization(M);
1699249259Sdim  }
1700249259Sdim
1701249259Sdim  initializeAllAnalysisInfo();
1702249259Sdim  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1703249259Sdim    Changed |= getContainedManager(Index)->runOnModule(M);
1704249259Sdim
1705249259Sdim  for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1706249259Sdim       E = IPV.end(); I != E; ++I) {
1707249259Sdim    Changed |= (*I)->doFinalization(M);
1708249259Sdim  }
1709249259Sdim
1710249259Sdim  return Changed;
1711249259Sdim}
1712249259Sdim
1713249259Sdim//===----------------------------------------------------------------------===//
1714249259Sdim// PassManager implementation
1715249259Sdim
1716249259Sdim/// Create new pass manager
1717249259SdimPassManager::PassManager() {
1718249259Sdim  PM = new PassManagerImpl();
1719249259Sdim  // PM is the top level manager
1720249259Sdim  PM->setTopLevelManager(PM);
1721249259Sdim}
1722249259Sdim
1723249259SdimPassManager::~PassManager() {
1724249259Sdim  delete PM;
1725249259Sdim}
1726249259Sdim
1727249259Sdim/// add - Add a pass to the queue of passes to run.  This passes ownership of
1728249259Sdim/// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1729249259Sdim/// will be destroyed as well, so there is no need to delete the pass.  This
1730249259Sdim/// implies that all passes MUST be allocated with 'new'.
1731249259Sdimvoid PassManager::add(Pass *P) {
1732249259Sdim  PM->add(P);
1733249259Sdim}
1734249259Sdim
1735249259Sdim/// run - Execute all of the passes scheduled for execution.  Keep track of
1736249259Sdim/// whether any of the passes modifies the module, and if so, return true.
1737249259Sdimbool PassManager::run(Module &M) {
1738249259Sdim  return PM->run(M);
1739249259Sdim}
1740249259Sdim
1741249259Sdim//===----------------------------------------------------------------------===//
1742249259Sdim// TimingInfo implementation
1743249259Sdim
1744249259Sdimbool llvm::TimePassesIsEnabled = false;
1745249259Sdimstatic cl::opt<bool,true>
1746249259SdimEnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1747249259Sdim            cl::desc("Time each pass, printing elapsed time for each on exit"));
1748249259Sdim
1749249259Sdim// createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1750249259Sdim// a non null value (if the -time-passes option is enabled) or it leaves it
1751249259Sdim// null.  It may be called multiple times.
1752249259Sdimvoid TimingInfo::createTheTimeInfo() {
1753249259Sdim  if (!TimePassesIsEnabled || TheTimeInfo) return;
1754249259Sdim
1755249259Sdim  // Constructed the first time this is called, iff -time-passes is enabled.
1756249259Sdim  // This guarantees that the object will be constructed before static globals,
1757249259Sdim  // thus it will be destroyed before them.
1758249259Sdim  static ManagedStatic<TimingInfo> TTI;
1759249259Sdim  TheTimeInfo = &*TTI;
1760249259Sdim}
1761249259Sdim
1762249259Sdim/// If TimingInfo is enabled then start pass timer.
1763249259SdimTimer *llvm::getPassTimer(Pass *P) {
1764249259Sdim  if (TheTimeInfo)
1765249259Sdim    return TheTimeInfo->getPassTimer(P);
1766249259Sdim  return 0;
1767249259Sdim}
1768249259Sdim
1769249259Sdim//===----------------------------------------------------------------------===//
1770249259Sdim// PMStack implementation
1771249259Sdim//
1772249259Sdim
1773249259Sdim// Pop Pass Manager from the stack and clear its analysis info.
1774249259Sdimvoid PMStack::pop() {
1775249259Sdim
1776249259Sdim  PMDataManager *Top = this->top();
1777249259Sdim  Top->initializeAnalysisInfo();
1778249259Sdim
1779249259Sdim  S.pop_back();
1780249259Sdim}
1781249259Sdim
1782249259Sdim// Push PM on the stack and set its top level manager.
1783249259Sdimvoid PMStack::push(PMDataManager *PM) {
1784249259Sdim  assert(PM && "Unable to push. Pass Manager expected");
1785249259Sdim  assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1786249259Sdim
1787249259Sdim  if (!this->empty()) {
1788249259Sdim    assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1789249259Sdim           && "pushing bad pass manager to PMStack");
1790249259Sdim    PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1791249259Sdim
1792249259Sdim    assert(TPM && "Unable to find top level manager");
1793249259Sdim    TPM->addIndirectPassManager(PM);
1794249259Sdim    PM->setTopLevelManager(TPM);
1795249259Sdim    PM->setDepth(this->top()->getDepth()+1);
1796249259Sdim  } else {
1797249259Sdim    assert((PM->getPassManagerType() == PMT_ModulePassManager
1798249259Sdim           || PM->getPassManagerType() == PMT_FunctionPassManager)
1799249259Sdim           && "pushing bad pass manager to PMStack");
1800249259Sdim    PM->setDepth(1);
1801249259Sdim  }
1802249259Sdim
1803249259Sdim  S.push_back(PM);
1804249259Sdim}
1805249259Sdim
1806249259Sdim// Dump content of the pass manager stack.
1807249259Sdimvoid PMStack::dump() const {
1808249259Sdim  for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1809249259Sdim         E = S.end(); I != E; ++I)
1810249259Sdim    dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1811249259Sdim
1812249259Sdim  if (!S.empty())
1813249259Sdim    dbgs() << '\n';
1814249259Sdim}
1815249259Sdim
1816249259Sdim/// Find appropriate Module Pass Manager in the PM Stack and
1817249259Sdim/// add self into that manager.
1818249259Sdimvoid ModulePass::assignPassManager(PMStack &PMS,
1819249259Sdim                                   PassManagerType PreferredType) {
1820249259Sdim  // Find Module Pass Manager
1821249259Sdim  while (!PMS.empty()) {
1822249259Sdim    PassManagerType TopPMType = PMS.top()->getPassManagerType();
1823249259Sdim    if (TopPMType == PreferredType)
1824249259Sdim      break; // We found desired pass manager
1825249259Sdim    else if (TopPMType > PMT_ModulePassManager)
1826249259Sdim      PMS.pop();    // Pop children pass managers
1827249259Sdim    else
1828249259Sdim      break;
1829249259Sdim  }
1830249259Sdim  assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1831249259Sdim  PMS.top()->add(this);
1832249259Sdim}
1833249259Sdim
1834249259Sdim/// Find appropriate Function Pass Manager or Call Graph Pass Manager
1835249259Sdim/// in the PM Stack and add self into that manager.
1836249259Sdimvoid FunctionPass::assignPassManager(PMStack &PMS,
1837249259Sdim                                     PassManagerType PreferredType) {
1838249259Sdim
1839249259Sdim  // Find Function Pass Manager
1840249259Sdim  while (!PMS.empty()) {
1841249259Sdim    if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1842249259Sdim      PMS.pop();
1843249259Sdim    else
1844249259Sdim      break;
1845249259Sdim  }
1846249259Sdim
1847249259Sdim  // Create new Function Pass Manager if needed.
1848249259Sdim  FPPassManager *FPP;
1849249259Sdim  if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1850249259Sdim    FPP = (FPPassManager *)PMS.top();
1851249259Sdim  } else {
1852249259Sdim    assert(!PMS.empty() && "Unable to create Function Pass Manager");
1853249259Sdim    PMDataManager *PMD = PMS.top();
1854249259Sdim
1855249259Sdim    // [1] Create new Function Pass Manager
1856249259Sdim    FPP = new FPPassManager();
1857249259Sdim    FPP->populateInheritedAnalysis(PMS);
1858249259Sdim
1859249259Sdim    // [2] Set up new manager's top level manager
1860249259Sdim    PMTopLevelManager *TPM = PMD->getTopLevelManager();
1861249259Sdim    TPM->addIndirectPassManager(FPP);
1862249259Sdim
1863249259Sdim    // [3] Assign manager to manage this new manager. This may create
1864249259Sdim    // and push new managers into PMS
1865249259Sdim    FPP->assignPassManager(PMS, PMD->getPassManagerType());
1866249259Sdim
1867249259Sdim    // [4] Push new manager into PMS
1868249259Sdim    PMS.push(FPP);
1869249259Sdim  }
1870249259Sdim
1871249259Sdim  // Assign FPP as the manager of this pass.
1872249259Sdim  FPP->add(this);
1873249259Sdim}
1874249259Sdim
1875249259Sdim/// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1876249259Sdim/// in the PM Stack and add self into that manager.
1877249259Sdimvoid BasicBlockPass::assignPassManager(PMStack &PMS,
1878249259Sdim                                       PassManagerType PreferredType) {
1879249259Sdim  BBPassManager *BBP;
1880249259Sdim
1881249259Sdim  // Basic Pass Manager is a leaf pass manager. It does not handle
1882249259Sdim  // any other pass manager.
1883249259Sdim  if (!PMS.empty() &&
1884249259Sdim      PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1885249259Sdim    BBP = (BBPassManager *)PMS.top();
1886249259Sdim  } else {
1887249259Sdim    // If leaf manager is not Basic Block Pass manager then create new
1888249259Sdim    // basic Block Pass manager.
1889249259Sdim    assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1890249259Sdim    PMDataManager *PMD = PMS.top();
1891249259Sdim
1892249259Sdim    // [1] Create new Basic Block Manager
1893249259Sdim    BBP = new BBPassManager();
1894249259Sdim
1895249259Sdim    // [2] Set up new manager's top level manager
1896249259Sdim    // Basic Block Pass Manager does not live by itself
1897249259Sdim    PMTopLevelManager *TPM = PMD->getTopLevelManager();
1898249259Sdim    TPM->addIndirectPassManager(BBP);
1899249259Sdim
1900249259Sdim    // [3] Assign manager to manage this new manager. This may create
1901249259Sdim    // and push new managers into PMS
1902249259Sdim    BBP->assignPassManager(PMS, PreferredType);
1903249259Sdim
1904249259Sdim    // [4] Push new manager into PMS
1905249259Sdim    PMS.push(BBP);
1906249259Sdim  }
1907249259Sdim
1908249259Sdim  // Assign BBP as the manager of this pass.
1909249259Sdim  BBP->add(this);
1910249259Sdim}
1911249259Sdim
1912249259SdimPassManagerBase::~PassManagerBase() {}
1913