LLVM API Documentation

LegacyPassManagers.h
Go to the documentation of this file.
00001 //===- LegacyPassManagers.h - Legacy Pass Infrastructure --------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file declares the LLVM Pass Manager infrastructure.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_IR_LEGACYPASSMANAGERS_H
00015 #define LLVM_IR_LEGACYPASSMANAGERS_H
00016 
00017 #include "llvm/ADT/ArrayRef.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/SmallPtrSet.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/Pass.h"
00022 #include <map>
00023 #include <vector>
00024 
00025 //===----------------------------------------------------------------------===//
00026 // Overview:
00027 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
00028 //
00029 //   o Manage optimization pass execution order
00030 //   o Make required Analysis information available before pass P is run
00031 //   o Release memory occupied by dead passes
00032 //   o If Analysis information is dirtied by a pass then regenerate Analysis
00033 //     information before it is consumed by another pass.
00034 //
00035 // Pass Manager Infrastructure uses multiple pass managers.  They are
00036 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
00037 // This class hierarchy uses multiple inheritance but pass managers do not
00038 // derive from another pass manager.
00039 //
00040 // PassManager and FunctionPassManager are two top-level pass manager that
00041 // represents the external interface of this entire pass manager infrastucture.
00042 //
00043 // Important classes :
00044 //
00045 // [o] class PMTopLevelManager;
00046 //
00047 // Two top level managers, PassManager and FunctionPassManager, derive from
00048 // PMTopLevelManager. PMTopLevelManager manages information used by top level
00049 // managers such as last user info.
00050 //
00051 // [o] class PMDataManager;
00052 //
00053 // PMDataManager manages information, e.g. list of available analysis info,
00054 // used by a pass manager to manage execution order of passes. It also provides
00055 // a place to implement common pass manager APIs. All pass managers derive from
00056 // PMDataManager.
00057 //
00058 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
00059 //
00060 // BBPassManager manages BasicBlockPasses.
00061 //
00062 // [o] class FunctionPassManager;
00063 //
00064 // This is a external interface used to manage FunctionPasses. This
00065 // interface relies on FunctionPassManagerImpl to do all the tasks.
00066 //
00067 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
00068 //                                     public PMTopLevelManager;
00069 //
00070 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
00071 //
00072 // [o] class FPPassManager : public ModulePass, public PMDataManager;
00073 //
00074 // FPPassManager manages FunctionPasses and BBPassManagers
00075 //
00076 // [o] class MPPassManager : public Pass, public PMDataManager;
00077 //
00078 // MPPassManager manages ModulePasses and FPPassManagers
00079 //
00080 // [o] class PassManager;
00081 //
00082 // This is a external interface used by various tools to manages passes. It
00083 // relies on PassManagerImpl to do all the tasks.
00084 //
00085 // [o] class PassManagerImpl : public Pass, public PMDataManager,
00086 //                             public PMTopLevelManager
00087 //
00088 // PassManagerImpl is a top level pass manager responsible for managing
00089 // MPPassManagers.
00090 //===----------------------------------------------------------------------===//
00091 
00092 #include "llvm/Support/PrettyStackTrace.h"
00093 
00094 namespace llvm {
00095   class Module;
00096   class Pass;
00097   class StringRef;
00098   class Value;
00099   class Timer;
00100   class PMDataManager;
00101 
00102 // enums for debugging strings
00103 enum PassDebuggingString {
00104   EXECUTION_MSG, // "Executing Pass '" + PassName
00105   MODIFICATION_MSG, // "Made Modification '" + PassName
00106   FREEING_MSG, // " Freeing Pass '" + PassName
00107   ON_BASICBLOCK_MSG, // "' on BasicBlock '" + InstructionName + "'...\n"
00108   ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n"
00109   ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n"
00110   ON_REGION_MSG, // "' on Region '" + Msg + "'...\n'"
00111   ON_LOOP_MSG, // "' on Loop '" + Msg + "'...\n'"
00112   ON_CG_MSG // "' on Call Graph Nodes '" + Msg + "'...\n'"
00113 };
00114 
00115 /// PassManagerPrettyStackEntry - This is used to print informative information
00116 /// about what pass is running when/if a stack trace is generated.
00117 class PassManagerPrettyStackEntry : public PrettyStackTraceEntry {
00118   Pass *P;
00119   Value *V;
00120   Module *M;
00121 public:
00122   explicit PassManagerPrettyStackEntry(Pass *p)
00123     : P(p), V(nullptr), M(nullptr) {}  // When P is releaseMemory'd.
00124   PassManagerPrettyStackEntry(Pass *p, Value &v)
00125     : P(p), V(&v), M(nullptr) {} // When P is run on V
00126   PassManagerPrettyStackEntry(Pass *p, Module &m)
00127     : P(p), V(nullptr), M(&m) {} // When P is run on M
00128 
00129   /// print - Emit information about this stack frame to OS.
00130   void print(raw_ostream &OS) const override;
00131 };
00132 
00133 
00134 //===----------------------------------------------------------------------===//
00135 // PMStack
00136 //
00137 /// PMStack - This class implements a stack data structure of PMDataManager
00138 /// pointers.
00139 ///
00140 /// Top level pass managers (see PassManager.cpp) maintain active Pass Managers
00141 /// using PMStack. Each Pass implements assignPassManager() to connect itself
00142 /// with appropriate manager. assignPassManager() walks PMStack to find
00143 /// suitable manager.
00144 class PMStack {
00145 public:
00146   typedef std::vector<PMDataManager *>::const_reverse_iterator iterator;
00147   iterator begin() const { return S.rbegin(); }
00148   iterator end() const { return S.rend(); }
00149 
00150   void pop();
00151   PMDataManager *top() const { return S.back(); }
00152   void push(PMDataManager *PM);
00153   bool empty() const { return S.empty(); }
00154 
00155   void dump() const;
00156 
00157 private:
00158   std::vector<PMDataManager *> S;
00159 };
00160 
00161 
00162 //===----------------------------------------------------------------------===//
00163 // PMTopLevelManager
00164 //
00165 /// PMTopLevelManager manages LastUser info and collects common APIs used by
00166 /// top level pass managers.
00167 class PMTopLevelManager {
00168 protected:
00169   explicit PMTopLevelManager(PMDataManager *PMDM);
00170 
00171   unsigned getNumContainedManagers() const {
00172     return (unsigned)PassManagers.size();
00173   }
00174 
00175   void initializeAllAnalysisInfo();
00176 
00177 private:
00178   virtual PMDataManager *getAsPMDataManager() = 0;
00179   virtual PassManagerType getTopLevelPassManagerType() = 0;
00180 
00181 public:
00182   /// Schedule pass P for execution. Make sure that passes required by
00183   /// P are run before P is run. Update analysis info maintained by
00184   /// the manager. Remove dead passes. This is a recursive function.
00185   void schedulePass(Pass *P);
00186 
00187   /// Set pass P as the last user of the given analysis passes.
00188   void setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P);
00189 
00190   /// Collect passes whose last user is P
00191   void collectLastUses(SmallVectorImpl<Pass *> &LastUses, Pass *P);
00192 
00193   /// Find the pass that implements Analysis AID. Search immutable
00194   /// passes and all pass managers. If desired pass is not found
00195   /// then return NULL.
00196   Pass *findAnalysisPass(AnalysisID AID);
00197 
00198   /// Find analysis usage information for the pass P.
00199   AnalysisUsage *findAnalysisUsage(Pass *P);
00200 
00201   virtual ~PMTopLevelManager();
00202 
00203   /// Add immutable pass and initialize it.
00204   inline void addImmutablePass(ImmutablePass *P) {
00205     P->initializePass();
00206     ImmutablePasses.push_back(P);
00207   }
00208 
00209   inline SmallVectorImpl<ImmutablePass *>& getImmutablePasses() {
00210     return ImmutablePasses;
00211   }
00212 
00213   void addPassManager(PMDataManager *Manager) {
00214     PassManagers.push_back(Manager);
00215   }
00216 
00217   // Add Manager into the list of managers that are not directly
00218   // maintained by this top level pass manager
00219   inline void addIndirectPassManager(PMDataManager *Manager) {
00220     IndirectPassManagers.push_back(Manager);
00221   }
00222 
00223   // Print passes managed by this top level manager.
00224   void dumpPasses() const;
00225   void dumpArguments() const;
00226 
00227   // Active Pass Managers
00228   PMStack activeStack;
00229 
00230 protected:
00231 
00232   /// Collection of pass managers
00233   SmallVector<PMDataManager *, 8> PassManagers;
00234 
00235 private:
00236 
00237   /// Collection of pass managers that are not directly maintained
00238   /// by this pass manager
00239   SmallVector<PMDataManager *, 8> IndirectPassManagers;
00240 
00241   // Map to keep track of last user of the analysis pass.
00242   // LastUser->second is the last user of Lastuser->first.
00243   DenseMap<Pass *, Pass *> LastUser;
00244 
00245   // Map to keep track of passes that are last used by a pass.
00246   // This inverse map is initialized at PM->run() based on
00247   // LastUser map.
00248   DenseMap<Pass *, SmallPtrSet<Pass *, 8> > InversedLastUser;
00249 
00250   /// Immutable passes are managed by top level manager.
00251   SmallVector<ImmutablePass *, 16> ImmutablePasses;
00252 
00253   DenseMap<Pass *, AnalysisUsage *> AnUsageMap;
00254 };
00255 
00256 
00257 
00258 //===----------------------------------------------------------------------===//
00259 // PMDataManager
00260 
00261 /// PMDataManager provides the common place to manage the analysis data
00262 /// used by pass managers.
00263 class PMDataManager {
00264 public:
00265 
00266   explicit PMDataManager() : TPM(nullptr), Depth(0) {
00267     initializeAnalysisInfo();
00268   }
00269 
00270   virtual ~PMDataManager();
00271 
00272   virtual Pass *getAsPass() = 0;
00273 
00274   /// Augment AvailableAnalysis by adding analysis made available by pass P.
00275   void recordAvailableAnalysis(Pass *P);
00276 
00277   /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
00278   void verifyPreservedAnalysis(Pass *P);
00279 
00280   /// Remove Analysis that is not preserved by the pass
00281   void removeNotPreservedAnalysis(Pass *P);
00282 
00283   /// Remove dead passes used by P.
00284   void removeDeadPasses(Pass *P, StringRef Msg,
00285                         enum PassDebuggingString);
00286 
00287   /// Remove P.
00288   void freePass(Pass *P, StringRef Msg,
00289                 enum PassDebuggingString);
00290 
00291   /// Add pass P into the PassVector. Update
00292   /// AvailableAnalysis appropriately if ProcessAnalysis is true.
00293   void add(Pass *P, bool ProcessAnalysis = true);
00294 
00295   /// Add RequiredPass into list of lower level passes required by pass P.
00296   /// RequiredPass is run on the fly by Pass Manager when P requests it
00297   /// through getAnalysis interface.
00298   virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
00299 
00300   virtual Pass *getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F);
00301 
00302   /// Initialize available analysis information.
00303   void initializeAnalysisInfo() {
00304     AvailableAnalysis.clear();
00305     for (unsigned i = 0; i < PMT_Last; ++i)
00306       InheritedAnalysis[i] = nullptr;
00307   }
00308 
00309   // Return true if P preserves high level analysis used by other
00310   // passes that are managed by this manager.
00311   bool preserveHigherLevelAnalysis(Pass *P);
00312 
00313 
00314   /// Populate RequiredPasses with analysis pass that are required by
00315   /// pass P and are available. Populate ReqPassNotAvailable with analysis
00316   /// pass that are required by pass P but are not available.
00317   void collectRequiredAnalysis(SmallVectorImpl<Pass *> &RequiredPasses,
00318                                SmallVectorImpl<AnalysisID> &ReqPassNotAvailable,
00319                                Pass *P);
00320 
00321   /// All Required analyses should be available to the pass as it runs!  Here
00322   /// we fill in the AnalysisImpls member of the pass so that it can
00323   /// successfully use the getAnalysis() method to retrieve the
00324   /// implementations it needs.
00325   void initializeAnalysisImpl(Pass *P);
00326 
00327   /// Find the pass that implements Analysis AID. If desired pass is not found
00328   /// then return NULL.
00329   Pass *findAnalysisPass(AnalysisID AID, bool Direction);
00330 
00331   // Access toplevel manager
00332   PMTopLevelManager *getTopLevelManager() { return TPM; }
00333   void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
00334 
00335   unsigned getDepth() const { return Depth; }
00336   void setDepth(unsigned newDepth) { Depth = newDepth; }
00337 
00338   // Print routines used by debug-pass
00339   void dumpLastUses(Pass *P, unsigned Offset) const;
00340   void dumpPassArguments() const;
00341   void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
00342                     enum PassDebuggingString S2, StringRef Msg);
00343   void dumpRequiredSet(const Pass *P) const;
00344   void dumpPreservedSet(const Pass *P) const;
00345 
00346   unsigned getNumContainedPasses() const {
00347     return (unsigned)PassVector.size();
00348   }
00349 
00350   virtual PassManagerType getPassManagerType() const {
00351     assert ( 0 && "Invalid use of getPassManagerType");
00352     return PMT_Unknown;
00353   }
00354 
00355   DenseMap<AnalysisID, Pass*> *getAvailableAnalysis() {
00356     return &AvailableAnalysis;
00357   }
00358 
00359   // Collect AvailableAnalysis from all the active Pass Managers.
00360   void populateInheritedAnalysis(PMStack &PMS) {
00361     unsigned Index = 0;
00362     for (PMStack::iterator I = PMS.begin(), E = PMS.end();
00363          I != E; ++I)
00364       InheritedAnalysis[Index++] = (*I)->getAvailableAnalysis();
00365   }
00366 
00367 protected:
00368 
00369   // Top level manager.
00370   PMTopLevelManager *TPM;
00371 
00372   // Collection of pass that are managed by this manager
00373   SmallVector<Pass *, 16> PassVector;
00374 
00375   // Collection of Analysis provided by Parent pass manager and
00376   // used by current pass manager. At at time there can not be more
00377   // then PMT_Last active pass mangers.
00378   DenseMap<AnalysisID, Pass *> *InheritedAnalysis[PMT_Last];
00379 
00380   /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
00381   /// or higher is specified.
00382   bool isPassDebuggingExecutionsOrMore() const;
00383 
00384 private:
00385   void dumpAnalysisUsage(StringRef Msg, const Pass *P,
00386                          const AnalysisUsage::VectorType &Set) const;
00387 
00388   // Set of available Analysis. This information is used while scheduling
00389   // pass. If a pass requires an analysis which is not available then
00390   // the required analysis pass is scheduled to run before the pass itself is
00391   // scheduled to run.
00392   DenseMap<AnalysisID, Pass*> AvailableAnalysis;
00393 
00394   // Collection of higher level analysis used by the pass managed by
00395   // this manager.
00396   SmallVector<Pass *, 16> HigherLevelAnalysis;
00397 
00398   unsigned Depth;
00399 };
00400 
00401 //===----------------------------------------------------------------------===//
00402 // FPPassManager
00403 //
00404 /// FPPassManager manages BBPassManagers and FunctionPasses.
00405 /// It batches all function passes and basic block pass managers together and
00406 /// sequence them to process one function at a time before processing next
00407 /// function.
00408 class FPPassManager : public ModulePass, public PMDataManager {
00409 public:
00410   static char ID;
00411   explicit FPPassManager()
00412   : ModulePass(ID), PMDataManager() { }
00413 
00414   /// run - Execute all of the passes scheduled for execution.  Keep track of
00415   /// whether any of the passes modifies the module, and if so, return true.
00416   bool runOnFunction(Function &F);
00417   bool runOnModule(Module &M) override;
00418 
00419   /// cleanup - After running all passes, clean up pass manager cache.
00420   void cleanup();
00421 
00422   /// doInitialization - Overrides ModulePass doInitialization for global
00423   /// initialization tasks
00424   ///
00425   using ModulePass::doInitialization;
00426 
00427   /// doInitialization - Run all of the initializers for the function passes.
00428   ///
00429   bool doInitialization(Module &M) override;
00430 
00431   /// doFinalization - Overrides ModulePass doFinalization for global
00432   /// finalization tasks
00433   /// 
00434   using ModulePass::doFinalization;
00435   
00436   /// doFinalization - Run all of the finalizers for the function passes.
00437   ///
00438   bool doFinalization(Module &M) override;
00439 
00440   PMDataManager *getAsPMDataManager() override { return this; }
00441   Pass *getAsPass() override { return this; }
00442 
00443   /// Pass Manager itself does not invalidate any analysis info.
00444   void getAnalysisUsage(AnalysisUsage &Info) const override {
00445     Info.setPreservesAll();
00446   }
00447 
00448   // Print passes managed by this manager
00449   void dumpPassStructure(unsigned Offset) override;
00450 
00451   const char *getPassName() const override {
00452     return "Function Pass Manager";
00453   }
00454 
00455   FunctionPass *getContainedPass(unsigned N) {
00456     assert ( N < PassVector.size() && "Pass number out of range!");
00457     FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
00458     return FP;
00459   }
00460 
00461   PassManagerType getPassManagerType() const override {
00462     return PMT_FunctionPassManager;
00463   }
00464 };
00465 
00466 Timer *getPassTimer(Pass *);
00467 
00468 }
00469 
00470 #endif