LLVM API Documentation

IR/PassManager.h
Go to the documentation of this file.
00001 //===- PassManager.h - Pass management 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 /// \file
00010 ///
00011 /// This header defines various interfaces for pass management in LLVM. There
00012 /// is no "pass" interface in LLVM per se. Instead, an instance of any class
00013 /// which supports a method to 'run' it over a unit of IR can be used as
00014 /// a pass. A pass manager is generally a tool to collect a sequence of passes
00015 /// which run over a particular IR construct, and run each of them in sequence
00016 /// over each such construct in the containing IR construct. As there is no
00017 /// containing IR construct for a Module, a manager for passes over modules
00018 /// forms the base case which runs its managed passes in sequence over the
00019 /// single module provided.
00020 ///
00021 /// The core IR library provides managers for running passes over
00022 /// modules and functions.
00023 ///
00024 /// * FunctionPassManager can run over a Module, runs each pass over
00025 ///   a Function.
00026 /// * ModulePassManager must be directly run, runs each pass over the Module.
00027 ///
00028 /// Note that the implementations of the pass managers use concept-based
00029 /// polymorphism as outlined in the "Value Semantics and Concept-based
00030 /// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base
00031 /// Class of Evil") by Sean Parent:
00032 /// * http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations
00033 /// * http://www.youtube.com/watch?v=_BpMYeUFXv8
00034 /// * http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil
00035 ///
00036 //===----------------------------------------------------------------------===//
00037 
00038 #ifndef LLVM_IR_PASSMANAGER_H
00039 #define LLVM_IR_PASSMANAGER_H
00040 
00041 #include "llvm/ADT/DenseMap.h"
00042 #include "llvm/ADT/STLExtras.h"
00043 #include "llvm/ADT/SmallPtrSet.h"
00044 #include "llvm/IR/Function.h"
00045 #include "llvm/IR/Module.h"
00046 #include "llvm/Support/type_traits.h"
00047 #include <list>
00048 #include <memory>
00049 #include <vector>
00050 
00051 namespace llvm {
00052 
00053 class Module;
00054 class Function;
00055 
00056 /// \brief An abstract set of preserved analyses following a transformation pass
00057 /// run.
00058 ///
00059 /// When a transformation pass is run, it can return a set of analyses whose
00060 /// results were preserved by that transformation. The default set is "none",
00061 /// and preserving analyses must be done explicitly.
00062 ///
00063 /// There is also an explicit all state which can be used (for example) when
00064 /// the IR is not mutated at all.
00065 class PreservedAnalyses {
00066 public:
00067   // We have to explicitly define all the special member functions because MSVC
00068   // refuses to generate them.
00069   PreservedAnalyses() {}
00070   PreservedAnalyses(const PreservedAnalyses &Arg)
00071       : PreservedPassIDs(Arg.PreservedPassIDs) {}
00072   PreservedAnalyses(PreservedAnalyses &&Arg)
00073       : PreservedPassIDs(std::move(Arg.PreservedPassIDs)) {}
00074   friend void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
00075     using std::swap;
00076     swap(LHS.PreservedPassIDs, RHS.PreservedPassIDs);
00077   }
00078   PreservedAnalyses &operator=(PreservedAnalyses RHS) {
00079     swap(*this, RHS);
00080     return *this;
00081   }
00082 
00083   /// \brief Convenience factory function for the empty preserved set.
00084   static PreservedAnalyses none() { return PreservedAnalyses(); }
00085 
00086   /// \brief Construct a special preserved set that preserves all passes.
00087   static PreservedAnalyses all() {
00088     PreservedAnalyses PA;
00089     PA.PreservedPassIDs.insert((void *)AllPassesID);
00090     return PA;
00091   }
00092 
00093   /// \brief Mark a particular pass as preserved, adding it to the set.
00094   template <typename PassT> void preserve() {
00095     if (!areAllPreserved())
00096       PreservedPassIDs.insert(PassT::ID());
00097   }
00098 
00099   /// \brief Intersect this set with another in place.
00100   ///
00101   /// This is a mutating operation on this preserved set, removing all
00102   /// preserved passes which are not also preserved in the argument.
00103   void intersect(const PreservedAnalyses &Arg) {
00104     if (Arg.areAllPreserved())
00105       return;
00106     if (areAllPreserved()) {
00107       PreservedPassIDs = Arg.PreservedPassIDs;
00108       return;
00109     }
00110     for (void *P : PreservedPassIDs)
00111       if (!Arg.PreservedPassIDs.count(P))
00112         PreservedPassIDs.erase(P);
00113   }
00114 
00115   /// \brief Intersect this set with a temporary other set in place.
00116   ///
00117   /// This is a mutating operation on this preserved set, removing all
00118   /// preserved passes which are not also preserved in the argument.
00119   void intersect(PreservedAnalyses &&Arg) {
00120     if (Arg.areAllPreserved())
00121       return;
00122     if (areAllPreserved()) {
00123       PreservedPassIDs = std::move(Arg.PreservedPassIDs);
00124       return;
00125     }
00126     for (void *P : PreservedPassIDs)
00127       if (!Arg.PreservedPassIDs.count(P))
00128         PreservedPassIDs.erase(P);
00129   }
00130 
00131   /// \brief Query whether a pass is marked as preserved by this set.
00132   template <typename PassT> bool preserved() const {
00133     return preserved(PassT::ID());
00134   }
00135 
00136   /// \brief Query whether an abstract pass ID is marked as preserved by this
00137   /// set.
00138   bool preserved(void *PassID) const {
00139     return PreservedPassIDs.count((void *)AllPassesID) ||
00140            PreservedPassIDs.count(PassID);
00141   }
00142 
00143 private:
00144   // Note that this must not be -1 or -2 as those are already used by the
00145   // SmallPtrSet.
00146   static const uintptr_t AllPassesID = (intptr_t)(-3);
00147 
00148   bool areAllPreserved() const {
00149     return PreservedPassIDs.count((void *)AllPassesID);
00150   }
00151 
00152   SmallPtrSet<void *, 2> PreservedPassIDs;
00153 };
00154 
00155 /// \brief Implementation details of the pass manager interfaces.
00156 namespace detail {
00157 
00158 /// \brief Template for the abstract base class used to dispatch
00159 /// polymorphically over pass objects.
00160 template <typename IRUnitT, typename AnalysisManagerT> struct PassConcept {
00161   // Boiler plate necessary for the container of derived classes.
00162   virtual ~PassConcept() {}
00163 
00164   /// \brief The polymorphic API which runs the pass over a given IR entity.
00165   ///
00166   /// Note that actual pass object can omit the analysis manager argument if
00167   /// desired. Also that the analysis manager may be null if there is no
00168   /// analysis manager in the pass pipeline.
00169   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) = 0;
00170 
00171   /// \brief Polymorphic method to access the name of a pass.
00172   virtual StringRef name() = 0;
00173 };
00174 
00175 /// \brief SFINAE metafunction for computing whether \c PassT has a run method
00176 /// accepting an \c AnalysisManagerT.
00177 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
00178           typename ResultT>
00179 class PassRunAcceptsAnalysisManager {
00180   typedef char SmallType;
00181   struct BigType {
00182     char a, b;
00183   };
00184 
00185   template <typename T, ResultT (T::*)(IRUnitT, AnalysisManagerT *)>
00186   struct Checker;
00187 
00188   template <typename T> static SmallType f(Checker<T, &T::run> *);
00189   template <typename T> static BigType f(...);
00190 
00191 public:
00192   enum { Value = sizeof(f<PassT>(nullptr)) == sizeof(SmallType) };
00193 };
00194 
00195 /// \brief A template wrapper used to implement the polymorphic API.
00196 ///
00197 /// Can be instantiated for any object which provides a \c run method accepting
00198 /// an \c IRUnitT. It requires the pass to be a copyable object. When the
00199 /// \c run method also accepts an \c AnalysisManagerT*, we pass it along.
00200 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
00201           bool AcceptsAnalysisManager = PassRunAcceptsAnalysisManager<
00202               IRUnitT, AnalysisManagerT, PassT, PreservedAnalyses>::Value>
00203 struct PassModel;
00204 
00205 /// \brief Specialization of \c PassModel for passes that accept an analyis
00206 /// manager.
00207 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
00208 struct PassModel<IRUnitT, AnalysisManagerT, PassT, true>
00209     : PassConcept<IRUnitT, AnalysisManagerT> {
00210   explicit PassModel(PassT Pass) : Pass(std::move(Pass)) {}
00211   // We have to explicitly define all the special member functions because MSVC
00212   // refuses to generate them.
00213   PassModel(const PassModel &Arg) : Pass(Arg.Pass) {}
00214   PassModel(PassModel &&Arg) : Pass(std::move(Arg.Pass)) {}
00215   friend void swap(PassModel &LHS, PassModel &RHS) {
00216     using std::swap;
00217     swap(LHS.Pass, RHS.Pass);
00218   }
00219   PassModel &operator=(PassModel RHS) {
00220     swap(*this, RHS);
00221     return *this;
00222   }
00223 
00224   PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) override {
00225     return Pass.run(IR, AM);
00226   }
00227   StringRef name() override { return PassT::name(); }
00228   PassT Pass;
00229 };
00230 
00231 /// \brief Specialization of \c PassModel for passes that accept an analyis
00232 /// manager.
00233 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
00234 struct PassModel<IRUnitT, AnalysisManagerT, PassT, false>
00235     : PassConcept<IRUnitT, AnalysisManagerT> {
00236   explicit PassModel(PassT Pass) : Pass(std::move(Pass)) {}
00237   // We have to explicitly define all the special member functions because MSVC
00238   // refuses to generate them.
00239   PassModel(const PassModel &Arg) : Pass(Arg.Pass) {}
00240   PassModel(PassModel &&Arg) : Pass(std::move(Arg.Pass)) {}
00241   friend void swap(PassModel &LHS, PassModel &RHS) {
00242     using std::swap;
00243     swap(LHS.Pass, RHS.Pass);
00244   }
00245   PassModel &operator=(PassModel RHS) {
00246     swap(*this, RHS);
00247     return *this;
00248   }
00249 
00250   PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) override {
00251     return Pass.run(IR);
00252   }
00253   StringRef name() override { return PassT::name(); }
00254   PassT Pass;
00255 };
00256 
00257 /// \brief Abstract concept of an analysis result.
00258 ///
00259 /// This concept is parameterized over the IR unit that this result pertains
00260 /// to.
00261 template <typename IRUnitT> struct AnalysisResultConcept {
00262   virtual ~AnalysisResultConcept() {}
00263 
00264   /// \brief Method to try and mark a result as invalid.
00265   ///
00266   /// When the outer analysis manager detects a change in some underlying
00267   /// unit of the IR, it will call this method on all of the results cached.
00268   ///
00269   /// This method also receives a set of preserved analyses which can be used
00270   /// to avoid invalidation because the pass which changed the underlying IR
00271   /// took care to update or preserve the analysis result in some way.
00272   ///
00273   /// \returns true if the result is indeed invalid (the default).
00274   virtual bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) = 0;
00275 };
00276 
00277 /// \brief SFINAE metafunction for computing whether \c ResultT provides an
00278 /// \c invalidate member function.
00279 template <typename IRUnitT, typename ResultT> class ResultHasInvalidateMethod {
00280   typedef char SmallType;
00281   struct BigType {
00282     char a, b;
00283   };
00284 
00285   template <typename T, bool (T::*)(IRUnitT, const PreservedAnalyses &)>
00286   struct Checker;
00287 
00288   template <typename T> static SmallType f(Checker<T, &T::invalidate> *);
00289   template <typename T> static BigType f(...);
00290 
00291 public:
00292   enum { Value = sizeof(f<ResultT>(nullptr)) == sizeof(SmallType) };
00293 };
00294 
00295 /// \brief Wrapper to model the analysis result concept.
00296 ///
00297 /// By default, this will implement the invalidate method with a trivial
00298 /// implementation so that the actual analysis result doesn't need to provide
00299 /// an invalidation handler. It is only selected when the invalidation handler
00300 /// is not part of the ResultT's interface.
00301 template <typename IRUnitT, typename PassT, typename ResultT,
00302           bool HasInvalidateHandler =
00303               ResultHasInvalidateMethod<IRUnitT, ResultT>::Value>
00304 struct AnalysisResultModel;
00305 
00306 /// \brief Specialization of \c AnalysisResultModel which provides the default
00307 /// invalidate functionality.
00308 template <typename IRUnitT, typename PassT, typename ResultT>
00309 struct AnalysisResultModel<IRUnitT, PassT, ResultT, false>
00310     : AnalysisResultConcept<IRUnitT> {
00311   explicit AnalysisResultModel(ResultT Result) : Result(std::move(Result)) {}
00312   // We have to explicitly define all the special member functions because MSVC
00313   // refuses to generate them.
00314   AnalysisResultModel(const AnalysisResultModel &Arg) : Result(Arg.Result) {}
00315   AnalysisResultModel(AnalysisResultModel &&Arg)
00316       : Result(std::move(Arg.Result)) {}
00317   friend void swap(AnalysisResultModel &LHS, AnalysisResultModel &RHS) {
00318     using std::swap;
00319     swap(LHS.Result, RHS.Result);
00320   }
00321   AnalysisResultModel &operator=(AnalysisResultModel RHS) {
00322     swap(*this, RHS);
00323     return *this;
00324   }
00325 
00326   /// \brief The model bases invalidation solely on being in the preserved set.
00327   //
00328   // FIXME: We should actually use two different concepts for analysis results
00329   // rather than two different models, and avoid the indirect function call for
00330   // ones that use the trivial behavior.
00331   bool invalidate(IRUnitT, const PreservedAnalyses &PA) override {
00332     return !PA.preserved(PassT::ID());
00333   }
00334 
00335   ResultT Result;
00336 };
00337 
00338 /// \brief Specialization of \c AnalysisResultModel which delegates invalidate
00339 /// handling to \c ResultT.
00340 template <typename IRUnitT, typename PassT, typename ResultT>
00341 struct AnalysisResultModel<IRUnitT, PassT, ResultT, true>
00342     : AnalysisResultConcept<IRUnitT> {
00343   explicit AnalysisResultModel(ResultT Result) : Result(std::move(Result)) {}
00344   // We have to explicitly define all the special member functions because MSVC
00345   // refuses to generate them.
00346   AnalysisResultModel(const AnalysisResultModel &Arg) : Result(Arg.Result) {}
00347   AnalysisResultModel(AnalysisResultModel &&Arg)
00348       : Result(std::move(Arg.Result)) {}
00349   friend void swap(AnalysisResultModel &LHS, AnalysisResultModel &RHS) {
00350     using std::swap;
00351     swap(LHS.Result, RHS.Result);
00352   }
00353   AnalysisResultModel &operator=(AnalysisResultModel RHS) {
00354     swap(*this, RHS);
00355     return *this;
00356   }
00357 
00358   /// \brief The model delegates to the \c ResultT method.
00359   bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) override {
00360     return Result.invalidate(IR, PA);
00361   }
00362 
00363   ResultT Result;
00364 };
00365 
00366 /// \brief Abstract concept of an analysis pass.
00367 ///
00368 /// This concept is parameterized over the IR unit that it can run over and
00369 /// produce an analysis result.
00370 template <typename IRUnitT, typename AnalysisManagerT>
00371 struct AnalysisPassConcept {
00372   virtual ~AnalysisPassConcept() {}
00373 
00374   /// \brief Method to run this analysis over a unit of IR.
00375   /// \returns A unique_ptr to the analysis result object to be queried by
00376   /// users.
00377   virtual std::unique_ptr<AnalysisResultConcept<IRUnitT>>
00378   run(IRUnitT IR, AnalysisManagerT *AM) = 0;
00379 };
00380 
00381 /// \brief Wrapper to model the analysis pass concept.
00382 ///
00383 /// Can wrap any type which implements a suitable \c run method. The method
00384 /// must accept the IRUnitT as an argument and produce an object which can be
00385 /// wrapped in a \c AnalysisResultModel.
00386 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
00387           bool AcceptsAnalysisManager = PassRunAcceptsAnalysisManager<
00388               IRUnitT, AnalysisManagerT, PassT, typename PassT::Result>::Value>
00389 struct AnalysisPassModel;
00390 
00391 /// \brief Specialization of \c AnalysisPassModel which passes an
00392 /// \c AnalysisManager to PassT's run method.
00393 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
00394 struct AnalysisPassModel<IRUnitT, AnalysisManagerT, PassT, true>
00395     : AnalysisPassConcept<IRUnitT, AnalysisManagerT> {
00396   explicit AnalysisPassModel(PassT Pass) : Pass(std::move(Pass)) {}
00397   // We have to explicitly define all the special member functions because MSVC
00398   // refuses to generate them.
00399   AnalysisPassModel(const AnalysisPassModel &Arg) : Pass(Arg.Pass) {}
00400   AnalysisPassModel(AnalysisPassModel &&Arg) : Pass(std::move(Arg.Pass)) {}
00401   friend void swap(AnalysisPassModel &LHS, AnalysisPassModel &RHS) {
00402     using std::swap;
00403     swap(LHS.Pass, RHS.Pass);
00404   }
00405   AnalysisPassModel &operator=(AnalysisPassModel RHS) {
00406     swap(*this, RHS);
00407     return *this;
00408   }
00409 
00410   // FIXME: Replace PassT::Result with type traits when we use C++11.
00411   typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
00412       ResultModelT;
00413 
00414   /// \brief The model delegates to the \c PassT::run method.
00415   ///
00416   /// The return is wrapped in an \c AnalysisResultModel.
00417   std::unique_ptr<AnalysisResultConcept<IRUnitT>>
00418   run(IRUnitT IR, AnalysisManagerT *AM) override {
00419     return make_unique<ResultModelT>(Pass.run(IR, AM));
00420   }
00421 
00422   PassT Pass;
00423 };
00424 
00425 /// \brief Specialization of \c AnalysisPassModel which does not pass an
00426 /// \c AnalysisManager to PassT's run method.
00427 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
00428 struct AnalysisPassModel<IRUnitT, AnalysisManagerT, PassT, false>
00429     : AnalysisPassConcept<IRUnitT, AnalysisManagerT> {
00430   explicit AnalysisPassModel(PassT Pass) : Pass(std::move(Pass)) {}
00431   // We have to explicitly define all the special member functions because MSVC
00432   // refuses to generate them.
00433   AnalysisPassModel(const AnalysisPassModel &Arg) : Pass(Arg.Pass) {}
00434   AnalysisPassModel(AnalysisPassModel &&Arg) : Pass(std::move(Arg.Pass)) {}
00435   friend void swap(AnalysisPassModel &LHS, AnalysisPassModel &RHS) {
00436     using std::swap;
00437     swap(LHS.Pass, RHS.Pass);
00438   }
00439   AnalysisPassModel &operator=(AnalysisPassModel RHS) {
00440     swap(*this, RHS);
00441     return *this;
00442   }
00443 
00444   // FIXME: Replace PassT::Result with type traits when we use C++11.
00445   typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
00446       ResultModelT;
00447 
00448   /// \brief The model delegates to the \c PassT::run method.
00449   ///
00450   /// The return is wrapped in an \c AnalysisResultModel.
00451   std::unique_ptr<AnalysisResultConcept<IRUnitT>>
00452   run(IRUnitT IR, AnalysisManagerT *) override {
00453     return make_unique<ResultModelT>(Pass.run(IR));
00454   }
00455 
00456   PassT Pass;
00457 };
00458 
00459 } // End namespace detail
00460 
00461 class ModuleAnalysisManager;
00462 
00463 class ModulePassManager {
00464 public:
00465   // We have to explicitly define all the special member functions because MSVC
00466   // refuses to generate them.
00467   ModulePassManager() {}
00468   ModulePassManager(ModulePassManager &&Arg) : Passes(std::move(Arg.Passes)) {}
00469   ModulePassManager &operator=(ModulePassManager &&RHS) {
00470     Passes = std::move(RHS.Passes);
00471     return *this;
00472   }
00473 
00474   /// \brief Run all of the module passes in this module pass manager over
00475   /// a module.
00476   ///
00477   /// This method should only be called for a single module as there is the
00478   /// expectation that the lifetime of a pass is bounded to that of a module.
00479   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM = nullptr);
00480 
00481   template <typename ModulePassT> void addPass(ModulePassT Pass) {
00482     Passes.emplace_back(new ModulePassModel<ModulePassT>(std::move(Pass)));
00483   }
00484 
00485   static StringRef name() { return "ModulePassManager"; }
00486 
00487 private:
00488   // Pull in the concept type and model template specialized for modules.
00489   typedef detail::PassConcept<Module *, ModuleAnalysisManager>
00490   ModulePassConcept;
00491   template <typename PassT>
00492   struct ModulePassModel
00493       : detail::PassModel<Module *, ModuleAnalysisManager, PassT> {
00494     ModulePassModel(PassT Pass)
00495         : detail::PassModel<Module *, ModuleAnalysisManager, PassT>(
00496               std::move(Pass)) {}
00497   };
00498 
00499   ModulePassManager(const ModulePassManager &) LLVM_DELETED_FUNCTION;
00500   ModulePassManager &operator=(const ModulePassManager &) LLVM_DELETED_FUNCTION;
00501 
00502   std::vector<std::unique_ptr<ModulePassConcept>> Passes;
00503 };
00504 
00505 class FunctionAnalysisManager;
00506 
00507 class FunctionPassManager {
00508 public:
00509   // We have to explicitly define all the special member functions because MSVC
00510   // refuses to generate them.
00511   FunctionPassManager() {}
00512   FunctionPassManager(FunctionPassManager &&Arg)
00513       : Passes(std::move(Arg.Passes)) {}
00514   FunctionPassManager &operator=(FunctionPassManager &&RHS) {
00515     Passes = std::move(RHS.Passes);
00516     return *this;
00517   }
00518 
00519   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
00520     Passes.emplace_back(new FunctionPassModel<FunctionPassT>(std::move(Pass)));
00521   }
00522 
00523   PreservedAnalyses run(Function *F, FunctionAnalysisManager *AM = nullptr);
00524 
00525   static StringRef name() { return "FunctionPassManager"; }
00526 
00527 private:
00528   // Pull in the concept type and model template specialized for functions.
00529   typedef detail::PassConcept<Function *, FunctionAnalysisManager>
00530   FunctionPassConcept;
00531   template <typename PassT>
00532   struct FunctionPassModel
00533       : detail::PassModel<Function *, FunctionAnalysisManager, PassT> {
00534     FunctionPassModel(PassT Pass)
00535         : detail::PassModel<Function *, FunctionAnalysisManager, PassT>(
00536               std::move(Pass)) {}
00537   };
00538 
00539   FunctionPassManager(const FunctionPassManager &) LLVM_DELETED_FUNCTION;
00540   FunctionPassManager &
00541   operator=(const FunctionPassManager &) LLVM_DELETED_FUNCTION;
00542 
00543   std::vector<std::unique_ptr<FunctionPassConcept>> Passes;
00544 };
00545 
00546 namespace detail {
00547 
00548 /// \brief A CRTP base used to implement analysis managers.
00549 ///
00550 /// This class template serves as the boiler plate of an analysis manager. Any
00551 /// analysis manager can be implemented on top of this base class. Any
00552 /// implementation will be required to provide specific hooks:
00553 ///
00554 /// - getResultImpl
00555 /// - getCachedResultImpl
00556 /// - invalidateImpl
00557 ///
00558 /// The details of the call pattern are within.
00559 template <typename DerivedT, typename IRUnitT> class AnalysisManagerBase {
00560   DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
00561   const DerivedT *derived_this() const {
00562     return static_cast<const DerivedT *>(this);
00563   }
00564 
00565   AnalysisManagerBase(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
00566   AnalysisManagerBase &
00567   operator=(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
00568 
00569 protected:
00570   typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
00571   typedef detail::AnalysisPassConcept<IRUnitT, DerivedT> PassConceptT;
00572 
00573   // FIXME: Provide template aliases for the models when we're using C++11 in
00574   // a mode supporting them.
00575 
00576   // We have to explicitly define all the special member functions because MSVC
00577   // refuses to generate them.
00578   AnalysisManagerBase() {}
00579   AnalysisManagerBase(AnalysisManagerBase &&Arg)
00580       : AnalysisPasses(std::move(Arg.AnalysisPasses)) {}
00581   AnalysisManagerBase &operator=(AnalysisManagerBase &&RHS) {
00582     AnalysisPasses = std::move(RHS.AnalysisPasses);
00583     return *this;
00584   }
00585 
00586 public:
00587   /// \brief Get the result of an analysis pass for this module.
00588   ///
00589   /// If there is not a valid cached result in the manager already, this will
00590   /// re-run the analysis to produce a valid result.
00591   template <typename PassT> typename PassT::Result &getResult(IRUnitT IR) {
00592     assert(AnalysisPasses.count(PassT::ID()) &&
00593            "This analysis pass was not registered prior to being queried");
00594 
00595     ResultConceptT &ResultConcept =
00596         derived_this()->getResultImpl(PassT::ID(), IR);
00597     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
00598         ResultModelT;
00599     return static_cast<ResultModelT &>(ResultConcept).Result;
00600   }
00601 
00602   /// \brief Get the cached result of an analysis pass for this module.
00603   ///
00604   /// This method never runs the analysis.
00605   ///
00606   /// \returns null if there is no cached result.
00607   template <typename PassT>
00608   typename PassT::Result *getCachedResult(IRUnitT IR) const {
00609     assert(AnalysisPasses.count(PassT::ID()) &&
00610            "This analysis pass was not registered prior to being queried");
00611 
00612     ResultConceptT *ResultConcept =
00613         derived_this()->getCachedResultImpl(PassT::ID(), IR);
00614     if (!ResultConcept)
00615       return nullptr;
00616 
00617     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
00618         ResultModelT;
00619     return &static_cast<ResultModelT *>(ResultConcept)->Result;
00620   }
00621 
00622   /// \brief Register an analysis pass with the manager.
00623   ///
00624   /// This provides an initialized and set-up analysis pass to the analysis
00625   /// manager. Whomever is setting up analysis passes must use this to populate
00626   /// the manager with all of the analysis passes available.
00627   template <typename PassT> void registerPass(PassT Pass) {
00628     assert(!AnalysisPasses.count(PassT::ID()) &&
00629            "Registered the same analysis pass twice!");
00630     typedef detail::AnalysisPassModel<IRUnitT, DerivedT, PassT> PassModelT;
00631     AnalysisPasses[PassT::ID()].reset(new PassModelT(std::move(Pass)));
00632   }
00633 
00634   /// \brief Invalidate a specific analysis pass for an IR module.
00635   ///
00636   /// Note that the analysis result can disregard invalidation.
00637   template <typename PassT> void invalidate(Module *M) {
00638     assert(AnalysisPasses.count(PassT::ID()) &&
00639            "This analysis pass was not registered prior to being invalidated");
00640     derived_this()->invalidateImpl(PassT::ID(), M);
00641   }
00642 
00643   /// \brief Invalidate analyses cached for an IR unit.
00644   ///
00645   /// Walk through all of the analyses pertaining to this unit of IR and
00646   /// invalidate them unless they are preserved by the PreservedAnalyses set.
00647   void invalidate(IRUnitT IR, const PreservedAnalyses &PA) {
00648     derived_this()->invalidateImpl(IR, PA);
00649   }
00650 
00651 protected:
00652   /// \brief Lookup a registered analysis pass.
00653   PassConceptT &lookupPass(void *PassID) {
00654     typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
00655     assert(PI != AnalysisPasses.end() &&
00656            "Analysis passes must be registered prior to being queried!");
00657     return *PI->second;
00658   }
00659 
00660   /// \brief Lookup a registered analysis pass.
00661   const PassConceptT &lookupPass(void *PassID) const {
00662     typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
00663     assert(PI != AnalysisPasses.end() &&
00664            "Analysis passes must be registered prior to being queried!");
00665     return *PI->second;
00666   }
00667 
00668 private:
00669   /// \brief Map type from module analysis pass ID to pass concept pointer.
00670   typedef DenseMap<void *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
00671 
00672   /// \brief Collection of module analysis passes, indexed by ID.
00673   AnalysisPassMapT AnalysisPasses;
00674 };
00675 
00676 } // End namespace detail
00677 
00678 /// \brief A module analysis pass manager with lazy running and caching of
00679 /// results.
00680 class ModuleAnalysisManager
00681     : public detail::AnalysisManagerBase<ModuleAnalysisManager, Module *> {
00682   friend class detail::AnalysisManagerBase<ModuleAnalysisManager, Module *>;
00683   typedef detail::AnalysisManagerBase<ModuleAnalysisManager, Module *> BaseT;
00684   typedef BaseT::ResultConceptT ResultConceptT;
00685   typedef BaseT::PassConceptT PassConceptT;
00686 
00687 public:
00688   // We have to explicitly define all the special member functions because MSVC
00689   // refuses to generate them.
00690   ModuleAnalysisManager() {}
00691   ModuleAnalysisManager(ModuleAnalysisManager &&Arg)
00692       : BaseT(std::move(static_cast<BaseT &>(Arg))),
00693         ModuleAnalysisResults(std::move(Arg.ModuleAnalysisResults)) {}
00694   ModuleAnalysisManager &operator=(ModuleAnalysisManager &&RHS) {
00695     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
00696     ModuleAnalysisResults = std::move(RHS.ModuleAnalysisResults);
00697     return *this;
00698   }
00699 
00700 private:
00701   ModuleAnalysisManager(const ModuleAnalysisManager &) LLVM_DELETED_FUNCTION;
00702   ModuleAnalysisManager &
00703   operator=(const ModuleAnalysisManager &) LLVM_DELETED_FUNCTION;
00704 
00705   /// \brief Get a module pass result, running the pass if necessary.
00706   ResultConceptT &getResultImpl(void *PassID, Module *M);
00707 
00708   /// \brief Get a cached module pass result or return null.
00709   ResultConceptT *getCachedResultImpl(void *PassID, Module *M) const;
00710 
00711   /// \brief Invalidate a module pass result.
00712   void invalidateImpl(void *PassID, Module *M);
00713 
00714   /// \brief Invalidate results across a module.
00715   void invalidateImpl(Module *M, const PreservedAnalyses &PA);
00716 
00717   /// \brief Map type from module analysis pass ID to pass result concept
00718   /// pointer.
00719   typedef DenseMap<void *,
00720                    std::unique_ptr<detail::AnalysisResultConcept<Module *>>>
00721       ModuleAnalysisResultMapT;
00722 
00723   /// \brief Cache of computed module analysis results for this module.
00724   ModuleAnalysisResultMapT ModuleAnalysisResults;
00725 };
00726 
00727 /// \brief A function analysis manager to coordinate and cache analyses run over
00728 /// a module.
00729 class FunctionAnalysisManager
00730     : public detail::AnalysisManagerBase<FunctionAnalysisManager, Function *> {
00731   friend class detail::AnalysisManagerBase<FunctionAnalysisManager, Function *>;
00732   typedef detail::AnalysisManagerBase<FunctionAnalysisManager, Function *>
00733       BaseT;
00734   typedef BaseT::ResultConceptT ResultConceptT;
00735   typedef BaseT::PassConceptT PassConceptT;
00736 
00737 public:
00738   // Most public APIs are inherited from the CRTP base class.
00739 
00740   // We have to explicitly define all the special member functions because MSVC
00741   // refuses to generate them.
00742   FunctionAnalysisManager() {}
00743   FunctionAnalysisManager(FunctionAnalysisManager &&Arg)
00744       : BaseT(std::move(static_cast<BaseT &>(Arg))),
00745         FunctionAnalysisResults(std::move(Arg.FunctionAnalysisResults)) {}
00746   FunctionAnalysisManager &operator=(FunctionAnalysisManager &&RHS) {
00747     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
00748     FunctionAnalysisResults = std::move(RHS.FunctionAnalysisResults);
00749     return *this;
00750   }
00751 
00752   /// \brief Returns true if the analysis manager has an empty results cache.
00753   bool empty() const;
00754 
00755   /// \brief Clear the function analysis result cache.
00756   ///
00757   /// This routine allows cleaning up when the set of functions itself has
00758   /// potentially changed, and thus we can't even look up a a result and
00759   /// invalidate it directly. Notably, this does *not* call invalidate
00760   /// functions as there is nothing to be done for them.
00761   void clear();
00762 
00763 private:
00764   FunctionAnalysisManager(const FunctionAnalysisManager &)
00765       LLVM_DELETED_FUNCTION;
00766   FunctionAnalysisManager &
00767   operator=(const FunctionAnalysisManager &) LLVM_DELETED_FUNCTION;
00768 
00769   /// \brief Get a function pass result, running the pass if necessary.
00770   ResultConceptT &getResultImpl(void *PassID, Function *F);
00771 
00772   /// \brief Get a cached function pass result or return null.
00773   ResultConceptT *getCachedResultImpl(void *PassID, Function *F) const;
00774 
00775   /// \brief Invalidate a function pass result.
00776   void invalidateImpl(void *PassID, Function *F);
00777 
00778   /// \brief Invalidate the results for a function..
00779   void invalidateImpl(Function *F, const PreservedAnalyses &PA);
00780 
00781   /// \brief List of function analysis pass IDs and associated concept pointers.
00782   ///
00783   /// Requires iterators to be valid across appending new entries and arbitrary
00784   /// erases. Provides both the pass ID and concept pointer such that it is
00785   /// half of a bijection and provides storage for the actual result concept.
00786   typedef std::list<std::pair<
00787       void *, std::unique_ptr<detail::AnalysisResultConcept<Function *>>>>
00788           FunctionAnalysisResultListT;
00789 
00790   /// \brief Map type from function pointer to our custom list type.
00791   typedef DenseMap<Function *, FunctionAnalysisResultListT>
00792       FunctionAnalysisResultListMapT;
00793 
00794   /// \brief Map from function to a list of function analysis results.
00795   ///
00796   /// Provides linear time removal of all analysis results for a function and
00797   /// the ultimate storage for a particular cached analysis result.
00798   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
00799 
00800   /// \brief Map type from a pair of analysis ID and function pointer to an
00801   /// iterator into a particular result list.
00802   typedef DenseMap<std::pair<void *, Function *>,
00803                    FunctionAnalysisResultListT::iterator>
00804       FunctionAnalysisResultMapT;
00805 
00806   /// \brief Map from an analysis ID and function to a particular cached
00807   /// analysis result.
00808   FunctionAnalysisResultMapT FunctionAnalysisResults;
00809 };
00810 
00811 /// \brief A module analysis which acts as a proxy for a function analysis
00812 /// manager.
00813 ///
00814 /// This primarily proxies invalidation information from the module analysis
00815 /// manager and module pass manager to a function analysis manager. You should
00816 /// never use a function analysis manager from within (transitively) a module
00817 /// pass manager unless your parent module pass has received a proxy result
00818 /// object for it.
00819 class FunctionAnalysisManagerModuleProxy {
00820 public:
00821   class Result;
00822 
00823   static void *ID() { return (void *)&PassID; }
00824 
00825   explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM)
00826       : FAM(&FAM) {}
00827   // We have to explicitly define all the special member functions because MSVC
00828   // refuses to generate them.
00829   FunctionAnalysisManagerModuleProxy(
00830       const FunctionAnalysisManagerModuleProxy &Arg)
00831       : FAM(Arg.FAM) {}
00832   FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy &&Arg)
00833       : FAM(std::move(Arg.FAM)) {}
00834   FunctionAnalysisManagerModuleProxy &
00835   operator=(FunctionAnalysisManagerModuleProxy RHS) {
00836     std::swap(FAM, RHS.FAM);
00837     return *this;
00838   }
00839 
00840   /// \brief Run the analysis pass and create our proxy result object.
00841   ///
00842   /// This doesn't do any interesting work, it is primarily used to insert our
00843   /// proxy result object into the module analysis cache so that we can proxy
00844   /// invalidation to the function analysis manager.
00845   ///
00846   /// In debug builds, it will also assert that the analysis manager is empty
00847   /// as no queries should arrive at the function analysis manager prior to
00848   /// this analysis being requested.
00849   Result run(Module *M);
00850 
00851 private:
00852   static char PassID;
00853 
00854   FunctionAnalysisManager *FAM;
00855 };
00856 
00857 /// \brief The result proxy object for the
00858 /// \c FunctionAnalysisManagerModuleProxy.
00859 ///
00860 /// See its documentation for more information.
00861 class FunctionAnalysisManagerModuleProxy::Result {
00862 public:
00863   explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
00864   // We have to explicitly define all the special member functions because MSVC
00865   // refuses to generate them.
00866   Result(const Result &Arg) : FAM(Arg.FAM) {}
00867   Result(Result &&Arg) : FAM(std::move(Arg.FAM)) {}
00868   Result &operator=(Result RHS) {
00869     std::swap(FAM, RHS.FAM);
00870     return *this;
00871   }
00872   ~Result();
00873 
00874   /// \brief Accessor for the \c FunctionAnalysisManager.
00875   FunctionAnalysisManager &getManager() { return *FAM; }
00876 
00877   /// \brief Handler for invalidation of the module.
00878   ///
00879   /// If this analysis itself is preserved, then we assume that the set of \c
00880   /// Function objects in the \c Module hasn't changed and thus we don't need
00881   /// to invalidate *all* cached data associated with a \c Function* in the \c
00882   /// FunctionAnalysisManager.
00883   ///
00884   /// Regardless of whether this analysis is marked as preserved, all of the
00885   /// analyses in the \c FunctionAnalysisManager are potentially invalidated
00886   /// based on the set of preserved analyses.
00887   bool invalidate(Module *M, const PreservedAnalyses &PA);
00888 
00889 private:
00890   FunctionAnalysisManager *FAM;
00891 };
00892 
00893 /// \brief A function analysis which acts as a proxy for a module analysis
00894 /// manager.
00895 ///
00896 /// This primarily provides an accessor to a parent module analysis manager to
00897 /// function passes. Only the const interface of the module analysis manager is
00898 /// provided to indicate that once inside of a function analysis pass you
00899 /// cannot request a module analysis to actually run. Instead, the user must
00900 /// rely on the \c getCachedResult API.
00901 ///
00902 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
00903 /// the recursive return path of each layer of the pass manager and the
00904 /// returned PreservedAnalysis set.
00905 class ModuleAnalysisManagerFunctionProxy {
00906 public:
00907   /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
00908   class Result {
00909   public:
00910     explicit Result(const ModuleAnalysisManager &MAM) : MAM(&MAM) {}
00911     // We have to explicitly define all the special member functions because
00912     // MSVC refuses to generate them.
00913     Result(const Result &Arg) : MAM(Arg.MAM) {}
00914     Result(Result &&Arg) : MAM(std::move(Arg.MAM)) {}
00915     Result &operator=(Result RHS) {
00916       std::swap(MAM, RHS.MAM);
00917       return *this;
00918     }
00919 
00920     const ModuleAnalysisManager &getManager() const { return *MAM; }
00921 
00922     /// \brief Handle invalidation by ignoring it, this pass is immutable.
00923     bool invalidate(Function *) { return false; }
00924 
00925   private:
00926     const ModuleAnalysisManager *MAM;
00927   };
00928 
00929   static void *ID() { return (void *)&PassID; }
00930 
00931   ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
00932       : MAM(&MAM) {}
00933   // We have to explicitly define all the special member functions because MSVC
00934   // refuses to generate them.
00935   ModuleAnalysisManagerFunctionProxy(
00936       const ModuleAnalysisManagerFunctionProxy &Arg)
00937       : MAM(Arg.MAM) {}
00938   ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy &&Arg)
00939       : MAM(std::move(Arg.MAM)) {}
00940   ModuleAnalysisManagerFunctionProxy &
00941   operator=(ModuleAnalysisManagerFunctionProxy RHS) {
00942     std::swap(MAM, RHS.MAM);
00943     return *this;
00944   }
00945 
00946   /// \brief Run the analysis pass and create our proxy result object.
00947   /// Nothing to see here, it just forwards the \c MAM reference into the
00948   /// result.
00949   Result run(Function *) { return Result(*MAM); }
00950 
00951 private:
00952   static char PassID;
00953 
00954   const ModuleAnalysisManager *MAM;
00955 };
00956 
00957 /// \brief Trivial adaptor that maps from a module to its functions.
00958 ///
00959 /// Designed to allow composition of a FunctionPass(Manager) and
00960 /// a ModulePassManager. Note that if this pass is constructed with a pointer
00961 /// to a \c ModuleAnalysisManager it will run the
00962 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
00963 /// pass over the module to enable a \c FunctionAnalysisManager to be used
00964 /// within this run safely.
00965 template <typename FunctionPassT> class ModuleToFunctionPassAdaptor {
00966 public:
00967   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
00968       : Pass(std::move(Pass)) {}
00969   // We have to explicitly define all the special member functions because MSVC
00970   // refuses to generate them.
00971   ModuleToFunctionPassAdaptor(const ModuleToFunctionPassAdaptor &Arg)
00972       : Pass(Arg.Pass) {}
00973   ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor &&Arg)
00974       : Pass(std::move(Arg.Pass)) {}
00975   friend void swap(ModuleToFunctionPassAdaptor &LHS, ModuleToFunctionPassAdaptor &RHS) {
00976     using std::swap;
00977     swap(LHS.Pass, RHS.Pass);
00978   }
00979   ModuleToFunctionPassAdaptor &operator=(ModuleToFunctionPassAdaptor RHS) {
00980     swap(*this, RHS);
00981     return *this;
00982   }
00983 
00984   /// \brief Runs the function pass across every function in the module.
00985   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM) {
00986     FunctionAnalysisManager *FAM = nullptr;
00987     if (AM)
00988       // Setup the function analysis manager from its proxy.
00989       FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
00990 
00991     PreservedAnalyses PA = PreservedAnalyses::all();
00992     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
00993       PreservedAnalyses PassPA = Pass.run(I, FAM);
00994 
00995       // We know that the function pass couldn't have invalidated any other
00996       // function's analyses (that's the contract of a function pass), so
00997       // directly handle the function analysis manager's invalidation here.
00998       if (FAM)
00999         FAM->invalidate(I, PassPA);
01000 
01001       // Then intersect the preserved set so that invalidation of module
01002       // analyses will eventually occur when the module pass completes.
01003       PA.intersect(std::move(PassPA));
01004     }
01005 
01006     // By definition we preserve the proxy. This precludes *any* invalidation
01007     // of function analyses by the proxy, but that's OK because we've taken
01008     // care to invalidate analyses in the function analysis manager
01009     // incrementally above.
01010     PA.preserve<FunctionAnalysisManagerModuleProxy>();
01011     return PA;
01012   }
01013 
01014   static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
01015 
01016 private:
01017   FunctionPassT Pass;
01018 };
01019 
01020 /// \brief A function to deduce a function pass type and wrap it in the
01021 /// templated adaptor.
01022 template <typename FunctionPassT>
01023 ModuleToFunctionPassAdaptor<FunctionPassT>
01024 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
01025   return std::move(ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass)));
01026 }
01027 
01028 }
01029 
01030 #endif