Home | History | Annotate | Download | only in IR
      1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the legacy LLVM Pass Manager infrastructure.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 
     15 #include "llvm/IR/LLVMContext.h"
     16 #include "llvm/IR/IRPrintingPasses.h"
     17 #include "llvm/IR/LegacyPassManager.h"
     18 #include "llvm/IR/LegacyPassManagers.h"
     19 #include "llvm/IR/LegacyPassNameParser.h"
     20 #include "llvm/IR/Module.h"
     21 #include "llvm/Support/CommandLine.h"
     22 #include "llvm/Support/Debug.h"
     23 #include "llvm/Support/ErrorHandling.h"
     24 #include "llvm/Support/ManagedStatic.h"
     25 #include "llvm/Support/Mutex.h"
     26 #include "llvm/Support/TimeValue.h"
     27 #include "llvm/Support/Timer.h"
     28 #include "llvm/Support/raw_ostream.h"
     29 #include <algorithm>
     30 #include <map>
     31 using namespace llvm;
     32 using namespace llvm::legacy;
     33 
     34 // See PassManagers.h for Pass Manager infrastructure overview.
     35 
     36 //===----------------------------------------------------------------------===//
     37 // Pass debugging information.  Often it is useful to find out what pass is
     38 // running when a crash occurs in a utility.  When this library is compiled with
     39 // debugging on, a command line option (--debug-pass) is enabled that causes the
     40 // pass name to be printed before it executes.
     41 //
     42 
     43 namespace {
     44 // Different debug levels that can be enabled...
     45 enum PassDebugLevel {
     46   Disabled, Arguments, Structure, Executions, Details
     47 };
     48 }
     49 
     50 static cl::opt<enum PassDebugLevel>
     51 PassDebugging("debug-pass", cl::Hidden,
     52                   cl::desc("Print PassManager debugging information"),
     53                   cl::values(
     54   clEnumVal(Disabled  , "disable debug output"),
     55   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
     56   clEnumVal(Structure , "print pass structure before run()"),
     57   clEnumVal(Executions, "print pass name before it is executed"),
     58   clEnumVal(Details   , "print pass details when it is executed"),
     59                              clEnumValEnd));
     60 
     61 namespace {
     62 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
     63 PassOptionList;
     64 }
     65 
     66 // Print IR out before/after specified passes.
     67 static PassOptionList
     68 PrintBefore("print-before",
     69             llvm::cl::desc("Print IR before specified passes"),
     70             cl::Hidden);
     71 
     72 static PassOptionList
     73 PrintAfter("print-after",
     74            llvm::cl::desc("Print IR after specified passes"),
     75            cl::Hidden);
     76 
     77 static cl::opt<bool>
     78 PrintBeforeAll("print-before-all",
     79                llvm::cl::desc("Print IR before each pass"),
     80                cl::init(false));
     81 static cl::opt<bool>
     82 PrintAfterAll("print-after-all",
     83               llvm::cl::desc("Print IR after each pass"),
     84               cl::init(false));
     85 
     86 /// This is a helper to determine whether to print IR before or
     87 /// after a pass.
     88 
     89 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
     90                                          PassOptionList &PassesToPrint) {
     91   for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
     92     const llvm::PassInfo *PassInf = PassesToPrint[i];
     93     if (PassInf)
     94       if (PassInf->getPassArgument() == PI->getPassArgument()) {
     95         return true;
     96       }
     97   }
     98   return false;
     99 }
    100 
    101 /// This is a utility to check whether a pass should have IR dumped
    102 /// before it.
    103 static bool ShouldPrintBeforePass(const PassInfo *PI) {
    104   return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
    105 }
    106 
    107 /// This is a utility to check whether a pass should have IR dumped
    108 /// after it.
    109 static bool ShouldPrintAfterPass(const PassInfo *PI) {
    110   return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
    111 }
    112 
    113 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
    114 /// or higher is specified.
    115 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
    116   return PassDebugging >= Executions;
    117 }
    118 
    119 
    120 
    121 
    122 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
    123   if (!V && !M)
    124     OS << "Releasing pass '";
    125   else
    126     OS << "Running pass '";
    127 
    128   OS << P->getPassName() << "'";
    129 
    130   if (M) {
    131     OS << " on module '" << M->getModuleIdentifier() << "'.\n";
    132     return;
    133   }
    134   if (!V) {
    135     OS << '\n';
    136     return;
    137   }
    138 
    139   OS << " on ";
    140   if (isa<Function>(V))
    141     OS << "function";
    142   else if (isa<BasicBlock>(V))
    143     OS << "basic block";
    144   else
    145     OS << "value";
    146 
    147   OS << " '";
    148   V->printAsOperand(OS, /*PrintTy=*/false, M);
    149   OS << "'\n";
    150 }
    151 
    152 
    153 namespace {
    154 //===----------------------------------------------------------------------===//
    155 // BBPassManager
    156 //
    157 /// BBPassManager manages BasicBlockPass. It batches all the
    158 /// pass together and sequence them to process one basic block before
    159 /// processing next basic block.
    160 class BBPassManager : public PMDataManager, public FunctionPass {
    161 
    162 public:
    163   static char ID;
    164   explicit BBPassManager()
    165     : PMDataManager(), FunctionPass(ID) {}
    166 
    167   /// Execute all of the passes scheduled for execution.  Keep track of
    168   /// whether any of the passes modifies the function, and if so, return true.
    169   bool runOnFunction(Function &F) override;
    170 
    171   /// Pass Manager itself does not invalidate any analysis info.
    172   void getAnalysisUsage(AnalysisUsage &Info) const override {
    173     Info.setPreservesAll();
    174   }
    175 
    176   bool doInitialization(Module &M) override;
    177   bool doInitialization(Function &F);
    178   bool doFinalization(Module &M) override;
    179   bool doFinalization(Function &F);
    180 
    181   PMDataManager *getAsPMDataManager() override { return this; }
    182   Pass *getAsPass() override { return this; }
    183 
    184   const char *getPassName() const override {
    185     return "BasicBlock Pass Manager";
    186   }
    187 
    188   // Print passes managed by this manager
    189   void dumpPassStructure(unsigned Offset) override {
    190     dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
    191     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
    192       BasicBlockPass *BP = getContainedPass(Index);
    193       BP->dumpPassStructure(Offset + 1);
    194       dumpLastUses(BP, Offset+1);
    195     }
    196   }
    197 
    198   BasicBlockPass *getContainedPass(unsigned N) {
    199     assert(N < PassVector.size() && "Pass number out of range!");
    200     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
    201     return BP;
    202   }
    203 
    204   PassManagerType getPassManagerType() const override {
    205     return PMT_BasicBlockPassManager;
    206   }
    207 };
    208 
    209 char BBPassManager::ID = 0;
    210 } // End anonymous namespace
    211 
    212 namespace llvm {
    213 namespace legacy {
    214 //===----------------------------------------------------------------------===//
    215 // FunctionPassManagerImpl
    216 //
    217 /// FunctionPassManagerImpl manages FPPassManagers
    218 class FunctionPassManagerImpl : public Pass,
    219                                 public PMDataManager,
    220                                 public PMTopLevelManager {
    221   virtual void anchor();
    222 private:
    223   bool wasRun;
    224 public:
    225   static char ID;
    226   explicit FunctionPassManagerImpl() :
    227     Pass(PT_PassManager, ID), PMDataManager(),
    228     PMTopLevelManager(new FPPassManager()), wasRun(false) {}
    229 
    230   /// \copydoc FunctionPassManager::add()
    231   void add(Pass *P) {
    232     schedulePass(P);
    233   }
    234 
    235   /// createPrinterPass - Get a function printer pass.
    236   Pass *createPrinterPass(raw_ostream &O,
    237                           const std::string &Banner) const override {
    238     return createPrintFunctionPass(O, Banner);
    239   }
    240 
    241   // Prepare for running an on the fly pass, freeing memory if needed
    242   // from a previous run.
    243   void releaseMemoryOnTheFly();
    244 
    245   /// run - Execute all of the passes scheduled for execution.  Keep track of
    246   /// whether any of the passes modifies the module, and if so, return true.
    247   bool run(Function &F);
    248 
    249   /// doInitialization - Run all of the initializers for the function passes.
    250   ///
    251   bool doInitialization(Module &M) override;
    252 
    253   /// doFinalization - Run all of the finalizers for the function passes.
    254   ///
    255   bool doFinalization(Module &M) override;
    256 
    257 
    258   PMDataManager *getAsPMDataManager() override { return this; }
    259   Pass *getAsPass() override { return this; }
    260   PassManagerType getTopLevelPassManagerType() override {
    261     return PMT_FunctionPassManager;
    262   }
    263 
    264   /// Pass Manager itself does not invalidate any analysis info.
    265   void getAnalysisUsage(AnalysisUsage &Info) const override {
    266     Info.setPreservesAll();
    267   }
    268 
    269   FPPassManager *getContainedManager(unsigned N) {
    270     assert(N < PassManagers.size() && "Pass number out of range!");
    271     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
    272     return FP;
    273   }
    274 };
    275 
    276 void FunctionPassManagerImpl::anchor() {}
    277 
    278 char FunctionPassManagerImpl::ID = 0;
    279 } // End of legacy namespace
    280 } // End of llvm namespace
    281 
    282 namespace {
    283 //===----------------------------------------------------------------------===//
    284 // MPPassManager
    285 //
    286 /// MPPassManager manages ModulePasses and function pass managers.
    287 /// It batches all Module passes and function pass managers together and
    288 /// sequences them to process one module.
    289 class MPPassManager : public Pass, public PMDataManager {
    290 public:
    291   static char ID;
    292   explicit MPPassManager() :
    293     Pass(PT_PassManager, ID), PMDataManager() { }
    294 
    295   // Delete on the fly managers.
    296   ~MPPassManager() override {
    297     for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
    298            I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
    299          I != E; ++I) {
    300       FunctionPassManagerImpl *FPP = I->second;
    301       delete FPP;
    302     }
    303   }
    304 
    305   /// createPrinterPass - Get a module printer pass.
    306   Pass *createPrinterPass(raw_ostream &O,
    307                           const std::string &Banner) const override {
    308     return createPrintModulePass(O, Banner);
    309   }
    310 
    311   /// run - Execute all of the passes scheduled for execution.  Keep track of
    312   /// whether any of the passes modifies the module, and if so, return true.
    313   bool runOnModule(Module &M);
    314 
    315   using llvm::Pass::doInitialization;
    316   using llvm::Pass::doFinalization;
    317 
    318   /// doInitialization - Run all of the initializers for the module passes.
    319   ///
    320   bool doInitialization();
    321 
    322   /// doFinalization - Run all of the finalizers for the module passes.
    323   ///
    324   bool doFinalization();
    325 
    326   /// Pass Manager itself does not invalidate any analysis info.
    327   void getAnalysisUsage(AnalysisUsage &Info) const override {
    328     Info.setPreservesAll();
    329   }
    330 
    331   /// Add RequiredPass into list of lower level passes required by pass P.
    332   /// RequiredPass is run on the fly by Pass Manager when P requests it
    333   /// through getAnalysis interface.
    334   void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
    335 
    336   /// Return function pass corresponding to PassInfo PI, that is
    337   /// required by module pass MP. Instantiate analysis pass, by using
    338   /// its runOnFunction() for function F.
    339   Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
    340 
    341   const char *getPassName() const override {
    342     return "Module Pass Manager";
    343   }
    344 
    345   PMDataManager *getAsPMDataManager() override { return this; }
    346   Pass *getAsPass() override { return this; }
    347 
    348   // Print passes managed by this manager
    349   void dumpPassStructure(unsigned Offset) override {
    350     dbgs().indent(Offset*2) << "ModulePass Manager\n";
    351     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
    352       ModulePass *MP = getContainedPass(Index);
    353       MP->dumpPassStructure(Offset + 1);
    354       std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
    355         OnTheFlyManagers.find(MP);
    356       if (I != OnTheFlyManagers.end())
    357         I->second->dumpPassStructure(Offset + 2);
    358       dumpLastUses(MP, Offset+1);
    359     }
    360   }
    361 
    362   ModulePass *getContainedPass(unsigned N) {
    363     assert(N < PassVector.size() && "Pass number out of range!");
    364     return static_cast<ModulePass *>(PassVector[N]);
    365   }
    366 
    367   PassManagerType getPassManagerType() const override {
    368     return PMT_ModulePassManager;
    369   }
    370 
    371  private:
    372   /// Collection of on the fly FPPassManagers. These managers manage
    373   /// function passes that are required by module passes.
    374   std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
    375 };
    376 
    377 char MPPassManager::ID = 0;
    378 } // End anonymous namespace
    379 
    380 namespace llvm {
    381 namespace legacy {
    382 //===----------------------------------------------------------------------===//
    383 // PassManagerImpl
    384 //
    385 
    386 /// PassManagerImpl manages MPPassManagers
    387 class PassManagerImpl : public Pass,
    388                         public PMDataManager,
    389                         public PMTopLevelManager {
    390   virtual void anchor();
    391 
    392 public:
    393   static char ID;
    394   explicit PassManagerImpl() :
    395     Pass(PT_PassManager, ID), PMDataManager(),
    396                               PMTopLevelManager(new MPPassManager()) {}
    397 
    398   /// \copydoc PassManager::add()
    399   void add(Pass *P) {
    400     schedulePass(P);
    401   }
    402 
    403   /// createPrinterPass - Get a module printer pass.
    404   Pass *createPrinterPass(raw_ostream &O,
    405                           const std::string &Banner) const override {
    406     return createPrintModulePass(O, Banner);
    407   }
    408 
    409   /// run - Execute all of the passes scheduled for execution.  Keep track of
    410   /// whether any of the passes modifies the module, and if so, return true.
    411   bool run(Module &M);
    412 
    413   using llvm::Pass::doInitialization;
    414   using llvm::Pass::doFinalization;
    415 
    416   /// doInitialization - Run all of the initializers for the module passes.
    417   ///
    418   bool doInitialization();
    419 
    420   /// doFinalization - Run all of the finalizers for the module passes.
    421   ///
    422   bool doFinalization();
    423 
    424   /// Pass Manager itself does not invalidate any analysis info.
    425   void getAnalysisUsage(AnalysisUsage &Info) const override {
    426     Info.setPreservesAll();
    427   }
    428 
    429   PMDataManager *getAsPMDataManager() override { return this; }
    430   Pass *getAsPass() override { return this; }
    431   PassManagerType getTopLevelPassManagerType() override {
    432     return PMT_ModulePassManager;
    433   }
    434 
    435   MPPassManager *getContainedManager(unsigned N) {
    436     assert(N < PassManagers.size() && "Pass number out of range!");
    437     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
    438     return MP;
    439   }
    440 };
    441 
    442 void PassManagerImpl::anchor() {}
    443 
    444 char PassManagerImpl::ID = 0;
    445 } // End of legacy namespace
    446 } // End of llvm namespace
    447 
    448 namespace {
    449 
    450 //===----------------------------------------------------------------------===//
    451 /// TimingInfo Class - This class is used to calculate information about the
    452 /// amount of time each pass takes to execute.  This only happens when
    453 /// -time-passes is enabled on the command line.
    454 ///
    455 
    456 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
    457 
    458 class TimingInfo {
    459   DenseMap<Pass*, Timer*> TimingData;
    460   TimerGroup TG;
    461 public:
    462   // Use 'create' member to get this.
    463   TimingInfo() : TG("... Pass execution timing report ...") {}
    464 
    465   // TimingDtor - Print out information about timing information
    466   ~TimingInfo() {
    467     // Delete all of the timers, which accumulate their info into the
    468     // TimerGroup.
    469     for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
    470          E = TimingData.end(); I != E; ++I)
    471       delete I->second;
    472     // TimerGroup is deleted next, printing the report.
    473   }
    474 
    475   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
    476   // to a non-null value (if the -time-passes option is enabled) or it leaves it
    477   // null.  It may be called multiple times.
    478   static void createTheTimeInfo();
    479 
    480   /// getPassTimer - Return the timer for the specified pass if it exists.
    481   Timer *getPassTimer(Pass *P) {
    482     if (P->getAsPMDataManager())
    483       return nullptr;
    484 
    485     sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
    486     Timer *&T = TimingData[P];
    487     if (!T)
    488       T = new Timer(P->getPassName(), TG);
    489     return T;
    490   }
    491 };
    492 
    493 } // End of anon namespace
    494 
    495 static TimingInfo *TheTimeInfo;
    496 
    497 //===----------------------------------------------------------------------===//
    498 // PMTopLevelManager implementation
    499 
    500 /// Initialize top level manager. Create first pass manager.
    501 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
    502   PMDM->setTopLevelManager(this);
    503   addPassManager(PMDM);
    504   activeStack.push(PMDM);
    505 }
    506 
    507 /// Set pass P as the last user of the given analysis passes.
    508 void
    509 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
    510   unsigned PDepth = 0;
    511   if (P->getResolver())
    512     PDepth = P->getResolver()->getPMDataManager().getDepth();
    513 
    514   for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
    515          E = AnalysisPasses.end(); I != E; ++I) {
    516     Pass *AP = *I;
    517     LastUser[AP] = P;
    518 
    519     if (P == AP)
    520       continue;
    521 
    522     // Update the last users of passes that are required transitive by AP.
    523     AnalysisUsage *AnUsage = findAnalysisUsage(AP);
    524     const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
    525     SmallVector<Pass *, 12> LastUses;
    526     SmallVector<Pass *, 12> LastPMUses;
    527     for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
    528          E = IDs.end(); I != E; ++I) {
    529       Pass *AnalysisPass = findAnalysisPass(*I);
    530       assert(AnalysisPass && "Expected analysis pass to exist.");
    531       AnalysisResolver *AR = AnalysisPass->getResolver();
    532       assert(AR && "Expected analysis resolver to exist.");
    533       unsigned APDepth = AR->getPMDataManager().getDepth();
    534 
    535       if (PDepth == APDepth)
    536         LastUses.push_back(AnalysisPass);
    537       else if (PDepth > APDepth)
    538         LastPMUses.push_back(AnalysisPass);
    539     }
    540 
    541     setLastUser(LastUses, P);
    542 
    543     // If this pass has a corresponding pass manager, push higher level
    544     // analysis to this pass manager.
    545     if (P->getResolver())
    546       setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
    547 
    548 
    549     // If AP is the last user of other passes then make P last user of
    550     // such passes.
    551     for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
    552            LUE = LastUser.end(); LUI != LUE; ++LUI) {
    553       if (LUI->second == AP)
    554         // DenseMap iterator is not invalidated here because
    555         // this is just updating existing entries.
    556         LastUser[LUI->first] = P;
    557     }
    558   }
    559 }
    560 
    561 /// Collect passes whose last user is P
    562 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
    563                                         Pass *P) {
    564   DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
    565     InversedLastUser.find(P);
    566   if (DMI == InversedLastUser.end())
    567     return;
    568 
    569   SmallPtrSet<Pass *, 8> &LU = DMI->second;
    570   for (Pass *LUP : LU) {
    571     LastUses.push_back(LUP);
    572   }
    573 
    574 }
    575 
    576 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
    577   AnalysisUsage *AnUsage = nullptr;
    578   DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
    579   if (DMI != AnUsageMap.end())
    580     AnUsage = DMI->second;
    581   else {
    582     AnUsage = new AnalysisUsage();
    583     P->getAnalysisUsage(*AnUsage);
    584     AnUsageMap[P] = AnUsage;
    585   }
    586   return AnUsage;
    587 }
    588 
    589 /// Schedule pass P for execution. Make sure that passes required by
    590 /// P are run before P is run. Update analysis info maintained by
    591 /// the manager. Remove dead passes. This is a recursive function.
    592 void PMTopLevelManager::schedulePass(Pass *P) {
    593 
    594   // TODO : Allocate function manager for this pass, other wise required set
    595   // may be inserted into previous function manager
    596 
    597   // Give pass a chance to prepare the stage.
    598   P->preparePassManager(activeStack);
    599 
    600   // If P is an analysis pass and it is available then do not
    601   // generate the analysis again. Stale analysis info should not be
    602   // available at this point.
    603   const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
    604   if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
    605     delete P;
    606     return;
    607   }
    608 
    609   AnalysisUsage *AnUsage = findAnalysisUsage(P);
    610 
    611   bool checkAnalysis = true;
    612   while (checkAnalysis) {
    613     checkAnalysis = false;
    614 
    615     const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
    616     for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
    617            E = RequiredSet.end(); I != E; ++I) {
    618 
    619       Pass *AnalysisPass = findAnalysisPass(*I);
    620       if (!AnalysisPass) {
    621         const PassInfo *PI = findAnalysisPassInfo(*I);
    622 
    623         if (!PI) {
    624           // Pass P is not in the global PassRegistry
    625           dbgs() << "Pass '"  << P->getPassName() << "' is not initialized." << "\n";
    626           dbgs() << "Verify if there is a pass dependency cycle." << "\n";
    627           dbgs() << "Required Passes:" << "\n";
    628           for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
    629                  E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
    630             Pass *AnalysisPass2 = findAnalysisPass(*I2);
    631             if (AnalysisPass2) {
    632               dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
    633             } else {
    634               dbgs() << "\t"   << "Error: Required pass not found! Possible causes:"  << "\n";
    635               dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)"    << "\n";
    636               dbgs() << "\t\t" << "- Corruption of the global PassRegistry"           << "\n";
    637             }
    638           }
    639         }
    640 
    641         assert(PI && "Expected required passes to be initialized");
    642         AnalysisPass = PI->createPass();
    643         if (P->getPotentialPassManagerType () ==
    644             AnalysisPass->getPotentialPassManagerType())
    645           // Schedule analysis pass that is managed by the same pass manager.
    646           schedulePass(AnalysisPass);
    647         else if (P->getPotentialPassManagerType () >
    648                  AnalysisPass->getPotentialPassManagerType()) {
    649           // Schedule analysis pass that is managed by a new manager.
    650           schedulePass(AnalysisPass);
    651           // Recheck analysis passes to ensure that required analyses that
    652           // are already checked are still available.
    653           checkAnalysis = true;
    654         } else
    655           // Do not schedule this analysis. Lower level analysis
    656           // passes are run on the fly.
    657           delete AnalysisPass;
    658       }
    659     }
    660   }
    661 
    662   // Now all required passes are available.
    663   if (ImmutablePass *IP = P->getAsImmutablePass()) {
    664     // P is a immutable pass and it will be managed by this
    665     // top level manager. Set up analysis resolver to connect them.
    666     PMDataManager *DM = getAsPMDataManager();
    667     AnalysisResolver *AR = new AnalysisResolver(*DM);
    668     P->setResolver(AR);
    669     DM->initializeAnalysisImpl(P);
    670     addImmutablePass(IP);
    671     DM->recordAvailableAnalysis(IP);
    672     return;
    673   }
    674 
    675   if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
    676     Pass *PP = P->createPrinterPass(
    677       dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
    678     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
    679   }
    680 
    681   // Add the requested pass to the best available pass manager.
    682   P->assignPassManager(activeStack, getTopLevelPassManagerType());
    683 
    684   if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
    685     Pass *PP = P->createPrinterPass(
    686       dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
    687     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
    688   }
    689 }
    690 
    691 /// Find the pass that implements Analysis AID. Search immutable
    692 /// passes and all pass managers. If desired pass is not found
    693 /// then return NULL.
    694 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
    695 
    696   // Check pass managers
    697   for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
    698          E = PassManagers.end(); I != E; ++I)
    699     if (Pass *P = (*I)->findAnalysisPass(AID, false))
    700       return P;
    701 
    702   // Check other pass managers
    703   for (SmallVectorImpl<PMDataManager *>::iterator
    704          I = IndirectPassManagers.begin(),
    705          E = IndirectPassManagers.end(); I != E; ++I)
    706     if (Pass *P = (*I)->findAnalysisPass(AID, false))
    707       return P;
    708 
    709   // Check the immutable passes. Iterate in reverse order so that we find
    710   // the most recently registered passes first.
    711   for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
    712        ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
    713     AnalysisID PI = (*I)->getPassID();
    714     if (PI == AID)
    715       return *I;
    716 
    717     // If Pass not found then check the interfaces implemented by Immutable Pass
    718     const PassInfo *PassInf = findAnalysisPassInfo(PI);
    719     assert(PassInf && "Expected all immutable passes to be initialized");
    720     const std::vector<const PassInfo*> &ImmPI =
    721       PassInf->getInterfacesImplemented();
    722     for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
    723          EE = ImmPI.end(); II != EE; ++II) {
    724       if ((*II)->getTypeInfo() == AID)
    725         return *I;
    726     }
    727   }
    728 
    729   return nullptr;
    730 }
    731 
    732 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
    733   const PassInfo *&PI = AnalysisPassInfos[AID];
    734   if (!PI)
    735     PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
    736   else
    737     assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
    738            "The pass info pointer changed for an analysis ID!");
    739 
    740   return PI;
    741 }
    742 
    743 // Print passes managed by this top level manager.
    744 void PMTopLevelManager::dumpPasses() const {
    745 
    746   if (PassDebugging < Structure)
    747     return;
    748 
    749   // Print out the immutable passes
    750   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
    751     ImmutablePasses[i]->dumpPassStructure(0);
    752   }
    753 
    754   // Every class that derives from PMDataManager also derives from Pass
    755   // (sometimes indirectly), but there's no inheritance relationship
    756   // between PMDataManager and Pass, so we have to getAsPass to get
    757   // from a PMDataManager* to a Pass*.
    758   for (SmallVectorImpl<PMDataManager *>::const_iterator I =
    759        PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
    760     (*I)->getAsPass()->dumpPassStructure(1);
    761 }
    762 
    763 void PMTopLevelManager::dumpArguments() const {
    764 
    765   if (PassDebugging < Arguments)
    766     return;
    767 
    768   dbgs() << "Pass Arguments: ";
    769   for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
    770        ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
    771     if (const PassInfo *PI = findAnalysisPassInfo((*I)->getPassID())) {
    772       assert(PI && "Expected all immutable passes to be initialized");
    773       if (!PI->isAnalysisGroup())
    774         dbgs() << " -" << PI->getPassArgument();
    775     }
    776   for (SmallVectorImpl<PMDataManager *>::const_iterator I =
    777        PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
    778     (*I)->dumpPassArguments();
    779   dbgs() << "\n";
    780 }
    781 
    782 void PMTopLevelManager::initializeAllAnalysisInfo() {
    783   for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
    784          E = PassManagers.end(); I != E; ++I)
    785     (*I)->initializeAnalysisInfo();
    786 
    787   // Initailize other pass managers
    788   for (SmallVectorImpl<PMDataManager *>::iterator
    789        I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
    790        I != E; ++I)
    791     (*I)->initializeAnalysisInfo();
    792 
    793   for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
    794         DME = LastUser.end(); DMI != DME; ++DMI) {
    795     DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
    796       InversedLastUser.find(DMI->second);
    797     if (InvDMI != InversedLastUser.end()) {
    798       SmallPtrSet<Pass *, 8> &L = InvDMI->second;
    799       L.insert(DMI->first);
    800     } else {
    801       SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
    802       InversedLastUser[DMI->second] = L;
    803     }
    804   }
    805 }
    806 
    807 /// Destructor
    808 PMTopLevelManager::~PMTopLevelManager() {
    809   for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
    810          E = PassManagers.end(); I != E; ++I)
    811     delete *I;
    812 
    813   for (SmallVectorImpl<ImmutablePass *>::iterator
    814          I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
    815     delete *I;
    816 
    817   for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
    818          DME = AnUsageMap.end(); DMI != DME; ++DMI)
    819     delete DMI->second;
    820 }
    821 
    822 //===----------------------------------------------------------------------===//
    823 // PMDataManager implementation
    824 
    825 /// Augement AvailableAnalysis by adding analysis made available by pass P.
    826 void PMDataManager::recordAvailableAnalysis(Pass *P) {
    827   AnalysisID PI = P->getPassID();
    828 
    829   AvailableAnalysis[PI] = P;
    830 
    831   assert(!AvailableAnalysis.empty());
    832 
    833   // This pass is the current implementation of all of the interfaces it
    834   // implements as well.
    835   const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
    836   if (!PInf) return;
    837   const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
    838   for (unsigned i = 0, e = II.size(); i != e; ++i)
    839     AvailableAnalysis[II[i]->getTypeInfo()] = P;
    840 }
    841 
    842 // Return true if P preserves high level analysis used by other
    843 // passes managed by this manager
    844 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
    845   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
    846   if (AnUsage->getPreservesAll())
    847     return true;
    848 
    849   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
    850   for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
    851          E = HigherLevelAnalysis.end(); I  != E; ++I) {
    852     Pass *P1 = *I;
    853     if (P1->getAsImmutablePass() == nullptr &&
    854         std::find(PreservedSet.begin(), PreservedSet.end(),
    855                   P1->getPassID()) ==
    856            PreservedSet.end())
    857       return false;
    858   }
    859 
    860   return true;
    861 }
    862 
    863 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
    864 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
    865   // Don't do this unless assertions are enabled.
    866 #ifdef NDEBUG
    867   return;
    868 #endif
    869   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
    870   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
    871 
    872   // Verify preserved analysis
    873   for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
    874          E = PreservedSet.end(); I != E; ++I) {
    875     AnalysisID AID = *I;
    876     if (Pass *AP = findAnalysisPass(AID, true)) {
    877       TimeRegion PassTimer(getPassTimer(AP));
    878       AP->verifyAnalysis();
    879     }
    880   }
    881 }
    882 
    883 /// Remove Analysis not preserved by Pass P
    884 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
    885   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
    886   if (AnUsage->getPreservesAll())
    887     return;
    888 
    889   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
    890   for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
    891          E = AvailableAnalysis.end(); I != E; ) {
    892     DenseMap<AnalysisID, Pass*>::iterator Info = I++;
    893     if (Info->second->getAsImmutablePass() == nullptr &&
    894         std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
    895         PreservedSet.end()) {
    896       // Remove this analysis
    897       if (PassDebugging >= Details) {
    898         Pass *S = Info->second;
    899         dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
    900         dbgs() << S->getPassName() << "'\n";
    901       }
    902       AvailableAnalysis.erase(Info);
    903     }
    904   }
    905 
    906   // Check inherited analysis also. If P is not preserving analysis
    907   // provided by parent manager then remove it here.
    908   for (unsigned Index = 0; Index < PMT_Last; ++Index) {
    909 
    910     if (!InheritedAnalysis[Index])
    911       continue;
    912 
    913     for (DenseMap<AnalysisID, Pass*>::iterator
    914            I = InheritedAnalysis[Index]->begin(),
    915            E = InheritedAnalysis[Index]->end(); I != E; ) {
    916       DenseMap<AnalysisID, Pass *>::iterator Info = I++;
    917       if (Info->second->getAsImmutablePass() == nullptr &&
    918           std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
    919              PreservedSet.end()) {
    920         // Remove this analysis
    921         if (PassDebugging >= Details) {
    922           Pass *S = Info->second;
    923           dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
    924           dbgs() << S->getPassName() << "'\n";
    925         }
    926         InheritedAnalysis[Index]->erase(Info);
    927       }
    928     }
    929   }
    930 }
    931 
    932 /// Remove analysis passes that are not used any longer
    933 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
    934                                      enum PassDebuggingString DBG_STR) {
    935 
    936   SmallVector<Pass *, 12> DeadPasses;
    937 
    938   // If this is a on the fly manager then it does not have TPM.
    939   if (!TPM)
    940     return;
    941 
    942   TPM->collectLastUses(DeadPasses, P);
    943 
    944   if (PassDebugging >= Details && !DeadPasses.empty()) {
    945     dbgs() << " -*- '" <<  P->getPassName();
    946     dbgs() << "' is the last user of following pass instances.";
    947     dbgs() << " Free these instances\n";
    948   }
    949 
    950   for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
    951          E = DeadPasses.end(); I != E; ++I)
    952     freePass(*I, Msg, DBG_STR);
    953 }
    954 
    955 void PMDataManager::freePass(Pass *P, StringRef Msg,
    956                              enum PassDebuggingString DBG_STR) {
    957   dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
    958 
    959   {
    960     // If the pass crashes releasing memory, remember this.
    961     PassManagerPrettyStackEntry X(P);
    962     TimeRegion PassTimer(getPassTimer(P));
    963 
    964     P->releaseMemory();
    965   }
    966 
    967   AnalysisID PI = P->getPassID();
    968   if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
    969     // Remove the pass itself (if it is not already removed).
    970     AvailableAnalysis.erase(PI);
    971 
    972     // Remove all interfaces this pass implements, for which it is also
    973     // listed as the available implementation.
    974     const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
    975     for (unsigned i = 0, e = II.size(); i != e; ++i) {
    976       DenseMap<AnalysisID, Pass*>::iterator Pos =
    977         AvailableAnalysis.find(II[i]->getTypeInfo());
    978       if (Pos != AvailableAnalysis.end() && Pos->second == P)
    979         AvailableAnalysis.erase(Pos);
    980     }
    981   }
    982 }
    983 
    984 /// Add pass P into the PassVector. Update
    985 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
    986 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
    987   // This manager is going to manage pass P. Set up analysis resolver
    988   // to connect them.
    989   AnalysisResolver *AR = new AnalysisResolver(*this);
    990   P->setResolver(AR);
    991 
    992   // If a FunctionPass F is the last user of ModulePass info M
    993   // then the F's manager, not F, records itself as a last user of M.
    994   SmallVector<Pass *, 12> TransferLastUses;
    995 
    996   if (!ProcessAnalysis) {
    997     // Add pass
    998     PassVector.push_back(P);
    999     return;
   1000   }
   1001 
   1002   // At the moment, this pass is the last user of all required passes.
   1003   SmallVector<Pass *, 12> LastUses;
   1004   SmallVector<Pass *, 8> RequiredPasses;
   1005   SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
   1006 
   1007   unsigned PDepth = this->getDepth();
   1008 
   1009   collectRequiredAnalysis(RequiredPasses,
   1010                           ReqAnalysisNotAvailable, P);
   1011   for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
   1012          E = RequiredPasses.end(); I != E; ++I) {
   1013     Pass *PRequired = *I;
   1014     unsigned RDepth = 0;
   1015 
   1016     assert(PRequired->getResolver() && "Analysis Resolver is not set");
   1017     PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
   1018     RDepth = DM.getDepth();
   1019 
   1020     if (PDepth == RDepth)
   1021       LastUses.push_back(PRequired);
   1022     else if (PDepth > RDepth) {
   1023       // Let the parent claim responsibility of last use
   1024       TransferLastUses.push_back(PRequired);
   1025       // Keep track of higher level analysis used by this manager.
   1026       HigherLevelAnalysis.push_back(PRequired);
   1027     } else
   1028       llvm_unreachable("Unable to accommodate Required Pass");
   1029   }
   1030 
   1031   // Set P as P's last user until someone starts using P.
   1032   // However, if P is a Pass Manager then it does not need
   1033   // to record its last user.
   1034   if (!P->getAsPMDataManager())
   1035     LastUses.push_back(P);
   1036   TPM->setLastUser(LastUses, P);
   1037 
   1038   if (!TransferLastUses.empty()) {
   1039     Pass *My_PM = getAsPass();
   1040     TPM->setLastUser(TransferLastUses, My_PM);
   1041     TransferLastUses.clear();
   1042   }
   1043 
   1044   // Now, take care of required analyses that are not available.
   1045   for (SmallVectorImpl<AnalysisID>::iterator
   1046          I = ReqAnalysisNotAvailable.begin(),
   1047          E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
   1048     const PassInfo *PI = TPM->findAnalysisPassInfo(*I);
   1049     Pass *AnalysisPass = PI->createPass();
   1050     this->addLowerLevelRequiredPass(P, AnalysisPass);
   1051   }
   1052 
   1053   // Take a note of analysis required and made available by this pass.
   1054   // Remove the analysis not preserved by this pass
   1055   removeNotPreservedAnalysis(P);
   1056   recordAvailableAnalysis(P);
   1057 
   1058   // Add pass
   1059   PassVector.push_back(P);
   1060 }
   1061 
   1062 
   1063 /// Populate RP with analysis pass that are required by
   1064 /// pass P and are available. Populate RP_NotAvail with analysis
   1065 /// pass that are required by pass P but are not available.
   1066 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
   1067                                        SmallVectorImpl<AnalysisID> &RP_NotAvail,
   1068                                             Pass *P) {
   1069   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
   1070   const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
   1071   for (AnalysisUsage::VectorType::const_iterator
   1072          I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
   1073     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
   1074       RP.push_back(AnalysisPass);
   1075     else
   1076       RP_NotAvail.push_back(*I);
   1077   }
   1078 
   1079   const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
   1080   for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
   1081          E = IDs.end(); I != E; ++I) {
   1082     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
   1083       RP.push_back(AnalysisPass);
   1084     else
   1085       RP_NotAvail.push_back(*I);
   1086   }
   1087 }
   1088 
   1089 // All Required analyses should be available to the pass as it runs!  Here
   1090 // we fill in the AnalysisImpls member of the pass so that it can
   1091 // successfully use the getAnalysis() method to retrieve the
   1092 // implementations it needs.
   1093 //
   1094 void PMDataManager::initializeAnalysisImpl(Pass *P) {
   1095   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
   1096 
   1097   for (AnalysisUsage::VectorType::const_iterator
   1098          I = AnUsage->getRequiredSet().begin(),
   1099          E = AnUsage->getRequiredSet().end(); I != E; ++I) {
   1100     Pass *Impl = findAnalysisPass(*I, true);
   1101     if (!Impl)
   1102       // This may be analysis pass that is initialized on the fly.
   1103       // If that is not the case then it will raise an assert when it is used.
   1104       continue;
   1105     AnalysisResolver *AR = P->getResolver();
   1106     assert(AR && "Analysis Resolver is not set");
   1107     AR->addAnalysisImplsPair(*I, Impl);
   1108   }
   1109 }
   1110 
   1111 /// Find the pass that implements Analysis AID. If desired pass is not found
   1112 /// then return NULL.
   1113 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
   1114 
   1115   // Check if AvailableAnalysis map has one entry.
   1116   DenseMap<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
   1117 
   1118   if (I != AvailableAnalysis.end())
   1119     return I->second;
   1120 
   1121   // Search Parents through TopLevelManager
   1122   if (SearchParent)
   1123     return TPM->findAnalysisPass(AID);
   1124 
   1125   return nullptr;
   1126 }
   1127 
   1128 // Print list of passes that are last used by P.
   1129 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
   1130 
   1131   SmallVector<Pass *, 12> LUses;
   1132 
   1133   // If this is a on the fly manager then it does not have TPM.
   1134   if (!TPM)
   1135     return;
   1136 
   1137   TPM->collectLastUses(LUses, P);
   1138 
   1139   for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
   1140          E = LUses.end(); I != E; ++I) {
   1141     dbgs() << "--" << std::string(Offset*2, ' ');
   1142     (*I)->dumpPassStructure(0);
   1143   }
   1144 }
   1145 
   1146 void PMDataManager::dumpPassArguments() const {
   1147   for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
   1148         E = PassVector.end(); I != E; ++I) {
   1149     if (PMDataManager *PMD = (*I)->getAsPMDataManager())
   1150       PMD->dumpPassArguments();
   1151     else
   1152       if (const PassInfo *PI =
   1153             TPM->findAnalysisPassInfo((*I)->getPassID()))
   1154         if (!PI->isAnalysisGroup())
   1155           dbgs() << " -" << PI->getPassArgument();
   1156   }
   1157 }
   1158 
   1159 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
   1160                                  enum PassDebuggingString S2,
   1161                                  StringRef Msg) {
   1162   if (PassDebugging < Executions)
   1163     return;
   1164   dbgs() << "[" << sys::TimeValue::now().str() << "] " << (void *)this
   1165          << std::string(getDepth() * 2 + 1, ' ');
   1166   switch (S1) {
   1167   case EXECUTION_MSG:
   1168     dbgs() << "Executing Pass '" << P->getPassName();
   1169     break;
   1170   case MODIFICATION_MSG:
   1171     dbgs() << "Made Modification '" << P->getPassName();
   1172     break;
   1173   case FREEING_MSG:
   1174     dbgs() << " Freeing Pass '" << P->getPassName();
   1175     break;
   1176   default:
   1177     break;
   1178   }
   1179   switch (S2) {
   1180   case ON_BASICBLOCK_MSG:
   1181     dbgs() << "' on BasicBlock '" << Msg << "'...\n";
   1182     break;
   1183   case ON_FUNCTION_MSG:
   1184     dbgs() << "' on Function '" << Msg << "'...\n";
   1185     break;
   1186   case ON_MODULE_MSG:
   1187     dbgs() << "' on Module '"  << Msg << "'...\n";
   1188     break;
   1189   case ON_REGION_MSG:
   1190     dbgs() << "' on Region '"  << Msg << "'...\n";
   1191     break;
   1192   case ON_LOOP_MSG:
   1193     dbgs() << "' on Loop '" << Msg << "'...\n";
   1194     break;
   1195   case ON_CG_MSG:
   1196     dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
   1197     break;
   1198   default:
   1199     break;
   1200   }
   1201 }
   1202 
   1203 void PMDataManager::dumpRequiredSet(const Pass *P) const {
   1204   if (PassDebugging < Details)
   1205     return;
   1206 
   1207   AnalysisUsage analysisUsage;
   1208   P->getAnalysisUsage(analysisUsage);
   1209   dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
   1210 }
   1211 
   1212 void PMDataManager::dumpPreservedSet(const Pass *P) const {
   1213   if (PassDebugging < Details)
   1214     return;
   1215 
   1216   AnalysisUsage analysisUsage;
   1217   P->getAnalysisUsage(analysisUsage);
   1218   dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
   1219 }
   1220 
   1221 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
   1222                                    const AnalysisUsage::VectorType &Set) const {
   1223   assert(PassDebugging >= Details);
   1224   if (Set.empty())
   1225     return;
   1226   dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
   1227   for (unsigned i = 0; i != Set.size(); ++i) {
   1228     if (i) dbgs() << ',';
   1229     const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
   1230     if (!PInf) {
   1231       // Some preserved passes, such as AliasAnalysis, may not be initialized by
   1232       // all drivers.
   1233       dbgs() << " Uninitialized Pass";
   1234       continue;
   1235     }
   1236     dbgs() << ' ' << PInf->getPassName();
   1237   }
   1238   dbgs() << '\n';
   1239 }
   1240 
   1241 /// Add RequiredPass into list of lower level passes required by pass P.
   1242 /// RequiredPass is run on the fly by Pass Manager when P requests it
   1243 /// through getAnalysis interface.
   1244 /// This should be handled by specific pass manager.
   1245 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
   1246   if (TPM) {
   1247     TPM->dumpArguments();
   1248     TPM->dumpPasses();
   1249   }
   1250 
   1251   // Module Level pass may required Function Level analysis info
   1252   // (e.g. dominator info). Pass manager uses on the fly function pass manager
   1253   // to provide this on demand. In that case, in Pass manager terminology,
   1254   // module level pass is requiring lower level analysis info managed by
   1255   // lower level pass manager.
   1256 
   1257   // When Pass manager is not able to order required analysis info, Pass manager
   1258   // checks whether any lower level manager will be able to provide this
   1259   // analysis info on demand or not.
   1260 #ifndef NDEBUG
   1261   dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
   1262   dbgs() << "' required by '" << P->getPassName() << "'\n";
   1263 #endif
   1264   llvm_unreachable("Unable to schedule pass");
   1265 }
   1266 
   1267 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
   1268   llvm_unreachable("Unable to find on the fly pass");
   1269 }
   1270 
   1271 // Destructor
   1272 PMDataManager::~PMDataManager() {
   1273   for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
   1274          E = PassVector.end(); I != E; ++I)
   1275     delete *I;
   1276 }
   1277 
   1278 //===----------------------------------------------------------------------===//
   1279 // NOTE: Is this the right place to define this method ?
   1280 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
   1281 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
   1282   return PM.findAnalysisPass(ID, dir);
   1283 }
   1284 
   1285 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
   1286                                      Function &F) {
   1287   return PM.getOnTheFlyPass(P, AnalysisPI, F);
   1288 }
   1289 
   1290 //===----------------------------------------------------------------------===//
   1291 // BBPassManager implementation
   1292 
   1293 /// Execute all of the passes scheduled for execution by invoking
   1294 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies
   1295 /// the function, and if so, return true.
   1296 bool BBPassManager::runOnFunction(Function &F) {
   1297   if (F.isDeclaration())
   1298     return false;
   1299 
   1300   bool Changed = doInitialization(F);
   1301 
   1302   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
   1303     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
   1304       BasicBlockPass *BP = getContainedPass(Index);
   1305       bool LocalChanged = false;
   1306 
   1307       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
   1308       dumpRequiredSet(BP);
   1309 
   1310       initializeAnalysisImpl(BP);
   1311 
   1312       {
   1313         // If the pass crashes, remember this.
   1314         PassManagerPrettyStackEntry X(BP, *I);
   1315         TimeRegion PassTimer(getPassTimer(BP));
   1316 
   1317         LocalChanged |= BP->runOnBasicBlock(*I);
   1318       }
   1319 
   1320       Changed |= LocalChanged;
   1321       if (LocalChanged)
   1322         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
   1323                      I->getName());
   1324       dumpPreservedSet(BP);
   1325 
   1326       verifyPreservedAnalysis(BP);
   1327       removeNotPreservedAnalysis(BP);
   1328       recordAvailableAnalysis(BP);
   1329       removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
   1330     }
   1331 
   1332   return doFinalization(F) || Changed;
   1333 }
   1334 
   1335 // Implement doInitialization and doFinalization
   1336 bool BBPassManager::doInitialization(Module &M) {
   1337   bool Changed = false;
   1338 
   1339   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
   1340     Changed |= getContainedPass(Index)->doInitialization(M);
   1341 
   1342   return Changed;
   1343 }
   1344 
   1345 bool BBPassManager::doFinalization(Module &M) {
   1346   bool Changed = false;
   1347 
   1348   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
   1349     Changed |= getContainedPass(Index)->doFinalization(M);
   1350 
   1351   return Changed;
   1352 }
   1353 
   1354 bool BBPassManager::doInitialization(Function &F) {
   1355   bool Changed = false;
   1356 
   1357   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
   1358     BasicBlockPass *BP = getContainedPass(Index);
   1359     Changed |= BP->doInitialization(F);
   1360   }
   1361 
   1362   return Changed;
   1363 }
   1364 
   1365 bool BBPassManager::doFinalization(Function &F) {
   1366   bool Changed = false;
   1367 
   1368   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
   1369     BasicBlockPass *BP = getContainedPass(Index);
   1370     Changed |= BP->doFinalization(F);
   1371   }
   1372 
   1373   return Changed;
   1374 }
   1375 
   1376 
   1377 //===----------------------------------------------------------------------===//
   1378 // FunctionPassManager implementation
   1379 
   1380 /// Create new Function pass manager
   1381 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
   1382   FPM = new FunctionPassManagerImpl();
   1383   // FPM is the top level manager.
   1384   FPM->setTopLevelManager(FPM);
   1385 
   1386   AnalysisResolver *AR = new AnalysisResolver(*FPM);
   1387   FPM->setResolver(AR);
   1388 }
   1389 
   1390 FunctionPassManager::~FunctionPassManager() {
   1391   delete FPM;
   1392 }
   1393 
   1394 void FunctionPassManager::add(Pass *P) {
   1395   FPM->add(P);
   1396 }
   1397 
   1398 /// run - Execute all of the passes scheduled for execution.  Keep
   1399 /// track of whether any of the passes modifies the function, and if
   1400 /// so, return true.
   1401 ///
   1402 bool FunctionPassManager::run(Function &F) {
   1403   if (std::error_code EC = F.materialize())
   1404     report_fatal_error("Error reading bitcode file: " + EC.message());
   1405   return FPM->run(F);
   1406 }
   1407 
   1408 
   1409 /// doInitialization - Run all of the initializers for the function passes.
   1410 ///
   1411 bool FunctionPassManager::doInitialization() {
   1412   return FPM->doInitialization(*M);
   1413 }
   1414 
   1415 /// doFinalization - Run all of the finalizers for the function passes.
   1416 ///
   1417 bool FunctionPassManager::doFinalization() {
   1418   return FPM->doFinalization(*M);
   1419 }
   1420 
   1421 //===----------------------------------------------------------------------===//
   1422 // FunctionPassManagerImpl implementation
   1423 //
   1424 bool FunctionPassManagerImpl::doInitialization(Module &M) {
   1425   bool Changed = false;
   1426 
   1427   dumpArguments();
   1428   dumpPasses();
   1429 
   1430   SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
   1431   for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
   1432        E = IPV.end(); I != E; ++I) {
   1433     Changed |= (*I)->doInitialization(M);
   1434   }
   1435 
   1436   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
   1437     Changed |= getContainedManager(Index)->doInitialization(M);
   1438 
   1439   return Changed;
   1440 }
   1441 
   1442 bool FunctionPassManagerImpl::doFinalization(Module &M) {
   1443   bool Changed = false;
   1444 
   1445   for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
   1446     Changed |= getContainedManager(Index)->doFinalization(M);
   1447 
   1448   SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
   1449   for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
   1450        E = IPV.end(); I != E; ++I) {
   1451     Changed |= (*I)->doFinalization(M);
   1452   }
   1453 
   1454   return Changed;
   1455 }
   1456 
   1457 /// cleanup - After running all passes, clean up pass manager cache.
   1458 void FPPassManager::cleanup() {
   1459  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
   1460     FunctionPass *FP = getContainedPass(Index);
   1461     AnalysisResolver *AR = FP->getResolver();
   1462     assert(AR && "Analysis Resolver is not set");
   1463     AR->clearAnalysisImpls();
   1464  }
   1465 }
   1466 
   1467 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
   1468   if (!wasRun)
   1469     return;
   1470   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
   1471     FPPassManager *FPPM = getContainedManager(Index);
   1472     for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
   1473       FPPM->getContainedPass(Index)->releaseMemory();
   1474     }
   1475   }
   1476   wasRun = false;
   1477 }
   1478 
   1479 // Execute all the passes managed by this top level manager.
   1480 // Return true if any function is modified by a pass.
   1481 bool FunctionPassManagerImpl::run(Function &F) {
   1482   bool Changed = false;
   1483   TimingInfo::createTheTimeInfo();
   1484 
   1485   initializeAllAnalysisInfo();
   1486   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
   1487     Changed |= getContainedManager(Index)->runOnFunction(F);
   1488     F.getContext().yield();
   1489   }
   1490 
   1491   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
   1492     getContainedManager(Index)->cleanup();
   1493 
   1494   wasRun = true;
   1495   return Changed;
   1496 }
   1497 
   1498 //===----------------------------------------------------------------------===//
   1499 // FPPassManager implementation
   1500 
   1501 char FPPassManager::ID = 0;
   1502 /// Print passes managed by this manager
   1503 void FPPassManager::dumpPassStructure(unsigned Offset) {
   1504   dbgs().indent(Offset*2) << "FunctionPass Manager\n";
   1505   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
   1506     FunctionPass *FP = getContainedPass(Index);
   1507     FP->dumpPassStructure(Offset + 1);
   1508     dumpLastUses(FP, Offset+1);
   1509   }
   1510 }
   1511 
   1512 
   1513 /// Execute all of the passes scheduled for execution by invoking
   1514 /// runOnFunction method.  Keep track of whether any of the passes modifies
   1515 /// the function, and if so, return true.
   1516 bool FPPassManager::runOnFunction(Function &F) {
   1517   if (F.isDeclaration())
   1518     return false;
   1519 
   1520   bool Changed = false;
   1521 
   1522   // Collect inherited analysis from Module level pass manager.
   1523   populateInheritedAnalysis(TPM->activeStack);
   1524 
   1525   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
   1526     FunctionPass *FP = getContainedPass(Index);
   1527     bool LocalChanged = false;
   1528 
   1529     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
   1530     dumpRequiredSet(FP);
   1531 
   1532     initializeAnalysisImpl(FP);
   1533 
   1534     {
   1535       PassManagerPrettyStackEntry X(FP, F);
   1536       TimeRegion PassTimer(getPassTimer(FP));
   1537 
   1538       LocalChanged |= FP->runOnFunction(F);
   1539     }
   1540 
   1541     Changed |= LocalChanged;
   1542     if (LocalChanged)
   1543       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
   1544     dumpPreservedSet(FP);
   1545 
   1546     verifyPreservedAnalysis(FP);
   1547     removeNotPreservedAnalysis(FP);
   1548     recordAvailableAnalysis(FP);
   1549     removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
   1550   }
   1551   return Changed;
   1552 }
   1553 
   1554 bool FPPassManager::runOnModule(Module &M) {
   1555   bool Changed = false;
   1556 
   1557   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
   1558     Changed |= runOnFunction(*I);
   1559 
   1560   return Changed;
   1561 }
   1562 
   1563 bool FPPassManager::doInitialization(Module &M) {
   1564   bool Changed = false;
   1565 
   1566   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
   1567     Changed |= getContainedPass(Index)->doInitialization(M);
   1568 
   1569   return Changed;
   1570 }
   1571 
   1572 bool FPPassManager::doFinalization(Module &M) {
   1573   bool Changed = false;
   1574 
   1575   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
   1576     Changed |= getContainedPass(Index)->doFinalization(M);
   1577 
   1578   return Changed;
   1579 }
   1580 
   1581 //===----------------------------------------------------------------------===//
   1582 // MPPassManager implementation
   1583 
   1584 /// Execute all of the passes scheduled for execution by invoking
   1585 /// runOnModule method.  Keep track of whether any of the passes modifies
   1586 /// the module, and if so, return true.
   1587 bool
   1588 MPPassManager::runOnModule(Module &M) {
   1589   bool Changed = false;
   1590 
   1591   // Initialize on-the-fly passes
   1592   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
   1593        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
   1594        I != E; ++I) {
   1595     FunctionPassManagerImpl *FPP = I->second;
   1596     Changed |= FPP->doInitialization(M);
   1597   }
   1598 
   1599   // Initialize module passes
   1600   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
   1601     Changed |= getContainedPass(Index)->doInitialization(M);
   1602 
   1603   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
   1604     ModulePass *MP = getContainedPass(Index);
   1605     bool LocalChanged = false;
   1606 
   1607     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
   1608     dumpRequiredSet(MP);
   1609 
   1610     initializeAnalysisImpl(MP);
   1611 
   1612     {
   1613       PassManagerPrettyStackEntry X(MP, M);
   1614       TimeRegion PassTimer(getPassTimer(MP));
   1615 
   1616       LocalChanged |= MP->runOnModule(M);
   1617     }
   1618 
   1619     Changed |= LocalChanged;
   1620     if (LocalChanged)
   1621       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
   1622                    M.getModuleIdentifier());
   1623     dumpPreservedSet(MP);
   1624 
   1625     verifyPreservedAnalysis(MP);
   1626     removeNotPreservedAnalysis(MP);
   1627     recordAvailableAnalysis(MP);
   1628     removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
   1629   }
   1630 
   1631   // Finalize module passes
   1632   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
   1633     Changed |= getContainedPass(Index)->doFinalization(M);
   1634 
   1635   // Finalize on-the-fly passes
   1636   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
   1637        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
   1638        I != E; ++I) {
   1639     FunctionPassManagerImpl *FPP = I->second;
   1640     // We don't know when is the last time an on-the-fly pass is run,
   1641     // so we need to releaseMemory / finalize here
   1642     FPP->releaseMemoryOnTheFly();
   1643     Changed |= FPP->doFinalization(M);
   1644   }
   1645 
   1646   return Changed;
   1647 }
   1648 
   1649 /// Add RequiredPass into list of lower level passes required by pass P.
   1650 /// RequiredPass is run on the fly by Pass Manager when P requests it
   1651 /// through getAnalysis interface.
   1652 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
   1653   assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
   1654          "Unable to handle Pass that requires lower level Analysis pass");
   1655   assert((P->getPotentialPassManagerType() <
   1656           RequiredPass->getPotentialPassManagerType()) &&
   1657          "Unable to handle Pass that requires lower level Analysis pass");
   1658   if (!RequiredPass)
   1659     return;
   1660 
   1661   FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
   1662   if (!FPP) {
   1663     FPP = new FunctionPassManagerImpl();
   1664     // FPP is the top level manager.
   1665     FPP->setTopLevelManager(FPP);
   1666 
   1667     OnTheFlyManagers[P] = FPP;
   1668   }
   1669   const PassInfo *RequiredPassPI =
   1670       TPM->findAnalysisPassInfo(RequiredPass->getPassID());
   1671 
   1672   Pass *FoundPass = nullptr;
   1673   if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
   1674     FoundPass =
   1675       ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
   1676   }
   1677   if (!FoundPass) {
   1678     FoundPass = RequiredPass;
   1679     // This should be guaranteed to add RequiredPass to the passmanager given
   1680     // that we checked for an available analysis above.
   1681     FPP->add(RequiredPass);
   1682   }
   1683   // Register P as the last user of FoundPass or RequiredPass.
   1684   SmallVector<Pass *, 1> LU;
   1685   LU.push_back(FoundPass);
   1686   FPP->setLastUser(LU,  P);
   1687 }
   1688 
   1689 /// Return function pass corresponding to PassInfo PI, that is
   1690 /// required by module pass MP. Instantiate analysis pass, by using
   1691 /// its runOnFunction() for function F.
   1692 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
   1693   FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
   1694   assert(FPP && "Unable to find on the fly pass");
   1695 
   1696   FPP->releaseMemoryOnTheFly();
   1697   FPP->run(F);
   1698   return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
   1699 }
   1700 
   1701 
   1702 //===----------------------------------------------------------------------===//
   1703 // PassManagerImpl implementation
   1704 
   1705 //
   1706 /// run - Execute all of the passes scheduled for execution.  Keep track of
   1707 /// whether any of the passes modifies the module, and if so, return true.
   1708 bool PassManagerImpl::run(Module &M) {
   1709   bool Changed = false;
   1710   TimingInfo::createTheTimeInfo();
   1711 
   1712   dumpArguments();
   1713   dumpPasses();
   1714 
   1715   SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
   1716   for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
   1717        E = IPV.end(); I != E; ++I) {
   1718     Changed |= (*I)->doInitialization(M);
   1719   }
   1720 
   1721   initializeAllAnalysisInfo();
   1722   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
   1723     Changed |= getContainedManager(Index)->runOnModule(M);
   1724     M.getContext().yield();
   1725   }
   1726 
   1727   for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
   1728        E = IPV.end(); I != E; ++I) {
   1729     Changed |= (*I)->doFinalization(M);
   1730   }
   1731 
   1732   return Changed;
   1733 }
   1734 
   1735 //===----------------------------------------------------------------------===//
   1736 // PassManager implementation
   1737 
   1738 /// Create new pass manager
   1739 PassManager::PassManager() {
   1740   PM = new PassManagerImpl();
   1741   // PM is the top level manager
   1742   PM->setTopLevelManager(PM);
   1743 }
   1744 
   1745 PassManager::~PassManager() {
   1746   delete PM;
   1747 }
   1748 
   1749 void PassManager::add(Pass *P) {
   1750   PM->add(P);
   1751 }
   1752 
   1753 /// run - Execute all of the passes scheduled for execution.  Keep track of
   1754 /// whether any of the passes modifies the module, and if so, return true.
   1755 bool PassManager::run(Module &M) {
   1756   return PM->run(M);
   1757 }
   1758 
   1759 //===----------------------------------------------------------------------===//
   1760 // TimingInfo implementation
   1761 
   1762 bool llvm::TimePassesIsEnabled = false;
   1763 static cl::opt<bool,true>
   1764 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
   1765             cl::desc("Time each pass, printing elapsed time for each on exit"));
   1766 
   1767 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
   1768 // a non-null value (if the -time-passes option is enabled) or it leaves it
   1769 // null.  It may be called multiple times.
   1770 void TimingInfo::createTheTimeInfo() {
   1771   if (!TimePassesIsEnabled || TheTimeInfo) return;
   1772 
   1773   // Constructed the first time this is called, iff -time-passes is enabled.
   1774   // This guarantees that the object will be constructed before static globals,
   1775   // thus it will be destroyed before them.
   1776   static ManagedStatic<TimingInfo> TTI;
   1777   TheTimeInfo = &*TTI;
   1778 }
   1779 
   1780 /// If TimingInfo is enabled then start pass timer.
   1781 Timer *llvm::getPassTimer(Pass *P) {
   1782   if (TheTimeInfo)
   1783     return TheTimeInfo->getPassTimer(P);
   1784   return nullptr;
   1785 }
   1786 
   1787 //===----------------------------------------------------------------------===//
   1788 // PMStack implementation
   1789 //
   1790 
   1791 // Pop Pass Manager from the stack and clear its analysis info.
   1792 void PMStack::pop() {
   1793 
   1794   PMDataManager *Top = this->top();
   1795   Top->initializeAnalysisInfo();
   1796 
   1797   S.pop_back();
   1798 }
   1799 
   1800 // Push PM on the stack and set its top level manager.
   1801 void PMStack::push(PMDataManager *PM) {
   1802   assert(PM && "Unable to push. Pass Manager expected");
   1803   assert(PM->getDepth()==0 && "Pass Manager depth set too early");
   1804 
   1805   if (!this->empty()) {
   1806     assert(PM->getPassManagerType() > this->top()->getPassManagerType()
   1807            && "pushing bad pass manager to PMStack");
   1808     PMTopLevelManager *TPM = this->top()->getTopLevelManager();
   1809 
   1810     assert(TPM && "Unable to find top level manager");
   1811     TPM->addIndirectPassManager(PM);
   1812     PM->setTopLevelManager(TPM);
   1813     PM->setDepth(this->top()->getDepth()+1);
   1814   } else {
   1815     assert((PM->getPassManagerType() == PMT_ModulePassManager
   1816            || PM->getPassManagerType() == PMT_FunctionPassManager)
   1817            && "pushing bad pass manager to PMStack");
   1818     PM->setDepth(1);
   1819   }
   1820 
   1821   S.push_back(PM);
   1822 }
   1823 
   1824 // Dump content of the pass manager stack.
   1825 void PMStack::dump() const {
   1826   for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
   1827          E = S.end(); I != E; ++I)
   1828     dbgs() << (*I)->getAsPass()->getPassName() << ' ';
   1829 
   1830   if (!S.empty())
   1831     dbgs() << '\n';
   1832 }
   1833 
   1834 /// Find appropriate Module Pass Manager in the PM Stack and
   1835 /// add self into that manager.
   1836 void ModulePass::assignPassManager(PMStack &PMS,
   1837                                    PassManagerType PreferredType) {
   1838   // Find Module Pass Manager
   1839   while (!PMS.empty()) {
   1840     PassManagerType TopPMType = PMS.top()->getPassManagerType();
   1841     if (TopPMType == PreferredType)
   1842       break; // We found desired pass manager
   1843     else if (TopPMType > PMT_ModulePassManager)
   1844       PMS.pop();    // Pop children pass managers
   1845     else
   1846       break;
   1847   }
   1848   assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
   1849   PMS.top()->add(this);
   1850 }
   1851 
   1852 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
   1853 /// in the PM Stack and add self into that manager.
   1854 void FunctionPass::assignPassManager(PMStack &PMS,
   1855                                      PassManagerType PreferredType) {
   1856 
   1857   // Find Function Pass Manager
   1858   while (!PMS.empty()) {
   1859     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
   1860       PMS.pop();
   1861     else
   1862       break;
   1863   }
   1864 
   1865   // Create new Function Pass Manager if needed.
   1866   FPPassManager *FPP;
   1867   if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
   1868     FPP = (FPPassManager *)PMS.top();
   1869   } else {
   1870     assert(!PMS.empty() && "Unable to create Function Pass Manager");
   1871     PMDataManager *PMD = PMS.top();
   1872 
   1873     // [1] Create new Function Pass Manager
   1874     FPP = new FPPassManager();
   1875     FPP->populateInheritedAnalysis(PMS);
   1876 
   1877     // [2] Set up new manager's top level manager
   1878     PMTopLevelManager *TPM = PMD->getTopLevelManager();
   1879     TPM->addIndirectPassManager(FPP);
   1880 
   1881     // [3] Assign manager to manage this new manager. This may create
   1882     // and push new managers into PMS
   1883     FPP->assignPassManager(PMS, PMD->getPassManagerType());
   1884 
   1885     // [4] Push new manager into PMS
   1886     PMS.push(FPP);
   1887   }
   1888 
   1889   // Assign FPP as the manager of this pass.
   1890   FPP->add(this);
   1891 }
   1892 
   1893 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
   1894 /// in the PM Stack and add self into that manager.
   1895 void BasicBlockPass::assignPassManager(PMStack &PMS,
   1896                                        PassManagerType PreferredType) {
   1897   BBPassManager *BBP;
   1898 
   1899   // Basic Pass Manager is a leaf pass manager. It does not handle
   1900   // any other pass manager.
   1901   if (!PMS.empty() &&
   1902       PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
   1903     BBP = (BBPassManager *)PMS.top();
   1904   } else {
   1905     // If leaf manager is not Basic Block Pass manager then create new
   1906     // basic Block Pass manager.
   1907     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
   1908     PMDataManager *PMD = PMS.top();
   1909 
   1910     // [1] Create new Basic Block Manager
   1911     BBP = new BBPassManager();
   1912 
   1913     // [2] Set up new manager's top level manager
   1914     // Basic Block Pass Manager does not live by itself
   1915     PMTopLevelManager *TPM = PMD->getTopLevelManager();
   1916     TPM->addIndirectPassManager(BBP);
   1917 
   1918     // [3] Assign manager to manage this new manager. This may create
   1919     // and push new managers into PMS
   1920     BBP->assignPassManager(PMS, PreferredType);
   1921 
   1922     // [4] Push new manager into PMS
   1923     PMS.push(BBP);
   1924   }
   1925 
   1926   // Assign BBP as the manager of this pass.
   1927   BBP->add(this);
   1928 }
   1929 
   1930 PassManagerBase::~PassManagerBase() {}
   1931