[Orc] Rename IndirectStubsManagerBase method 'init' to 'createStubs'.
[oota-llvm.git] / include / llvm / ExecutionEngine / Orc / IndirectionUtils.h
index 13ba125e80b4b627b84350451e89b673238b148d..3ec6f2ab269a4787b1c7d6008cd1cf291f8d012e 100644 (file)
@@ -21,6 +21,7 @@
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/Mangler.h"
 #include "llvm/IR/Module.h"
+#include "llvm/Transforms/Utils/ValueMapper.h"
 #include <sstream>
 
 namespace llvm {
@@ -32,28 +33,22 @@ class JITCompileCallbackManagerBase {
 public:
 
   typedef std::function<TargetAddress()> CompileFtor;
-  typedef std::function<void(TargetAddress)> UpdateFtor;
 
   /// @brief Handle to a newly created compile callback. Can be used to get an
   ///        IR constant representing the address of the trampoline, and to set
-  ///        the compile and update actions for the callback.
+  ///        the compile action for the callback.
   class CompileCallbackInfo {
   public:
-    CompileCallbackInfo(TargetAddress Addr, CompileFtor &Compile,
-                        UpdateFtor &Update)
-      : Addr(Addr), Compile(Compile), Update(Update) {}
+    CompileCallbackInfo(TargetAddress Addr, CompileFtor &Compile)
+      : Addr(Addr), Compile(Compile) {}
 
     TargetAddress getAddress() const { return Addr; }
     void setCompileAction(CompileFtor Compile) {
       this->Compile = std::move(Compile);
     }
-    void setUpdateAction(UpdateFtor Update) {
-      this->Update = std::move(Update);
-    }
   private:
     TargetAddress Addr;
     CompileFtor &Compile;
-    UpdateFtor &Update;
   };
 
   /// @brief Construct a JITCompileCallbackManagerBase.
@@ -71,8 +66,8 @@ public:
 
   /// @brief Execute the callback for the given trampoline id. Called by the JIT
   ///        to compile functions on demand.
-  TargetAddress executeCompileCallback(TargetAddress TrampolineID) {
-    TrampolineMapT::iterator I = ActiveTrampolines.find(TrampolineID);
+  TargetAddress executeCompileCallback(TargetAddress TrampolineAddr) {
+    auto I = ActiveTrampolines.find(TrampolineAddr);
     // FIXME: Also raise an error in the Orc error-handler when we finally have
     //        one.
     if (I == ActiveTrampolines.end())
@@ -84,33 +79,48 @@ public:
     // Moving the trampoline ID back to the available list first means there's at
     // least one available trampoline if the compile action triggers a request for
     // a new one.
-    AvailableTrampolines.push_back(I->first);
-    auto CallbackHandler = std::move(I->second);
+    auto Compile = std::move(I->second);
     ActiveTrampolines.erase(I);
+    AvailableTrampolines.push_back(TrampolineAddr);
 
-    if (auto Addr = CallbackHandler.Compile()) {
-      CallbackHandler.Update(Addr);
+    if (auto Addr = Compile())
       return Addr;
-    }
+
     return ErrorHandlerAddress;
   }
 
-  /// @brief Get/create a compile callback with the given signature.
+  /// @brief Reserve a compile callback.
   virtual CompileCallbackInfo getCompileCallback(LLVMContext &Context) = 0;
 
-protected:
+  /// @brief Get a CompileCallbackInfo for an existing callback.
+  CompileCallbackInfo getCompileCallbackInfo(TargetAddress TrampolineAddr) {
+    auto I = ActiveTrampolines.find(TrampolineAddr);
+    assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
+    return CompileCallbackInfo(I->first, I->second);
+  }
 
-  struct CallbackHandler {
-    CompileFtor Compile;
-    UpdateFtor Update;
-  };
+  /// @brief Release a compile callback.
+  ///
+  ///   Note: Callbacks are auto-released after they execute. This method should
+  /// only be called to manually release a callback that is not going to
+  /// execute.
+  void releaseCompileCallback(TargetAddress TrampolineAddr) {
+    auto I = ActiveTrampolines.find(TrampolineAddr);
+    assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
+    ActiveTrampolines.erase(I);
+    AvailableTrampolines.push_back(TrampolineAddr);
+  }
 
+protected:
   TargetAddress ErrorHandlerAddress;
   unsigned NumTrampolinesPerBlock;
 
-  typedef std::map<TargetAddress, CallbackHandler> TrampolineMapT;
+  typedef std::map<TargetAddress, CompileFtor> TrampolineMapT;
   TrampolineMapT ActiveTrampolines;
   std::vector<TargetAddress> AvailableTrampolines;
+
+private:
+  virtual void anchor();
 };
 
 /// @brief Manage compile callbacks.
@@ -140,11 +150,8 @@ public:
   /// @brief Get/create a compile callback with the given signature.
   CompileCallbackInfo getCompileCallback(LLVMContext &Context) final {
     TargetAddress TrampolineAddr = getAvailableTrampolineAddr(Context);
-    auto &CallbackHandler =
-      this->ActiveTrampolines[TrampolineAddr];
-
-    return CompileCallbackInfo(TrampolineAddr, CallbackHandler.Compile,
-                               CallbackHandler.Update);
+    auto &Compile = this->ActiveTrampolines[TrampolineAddr];
+    return CompileCallbackInfo(TrampolineAddr, Compile);
   }
 
 private:
@@ -218,22 +225,93 @@ private:
   TargetAddress ResolverBlockAddr;
 };
 
-/// @brief Get an update functor that updates the value of a named function
-///        pointer.
-template <typename JITLayerT>
-JITCompileCallbackManagerBase::UpdateFtor
-getLocalFPUpdater(JITLayerT &JIT, typename JITLayerT::ModuleSetHandleT H,
-                  std::string Name) {
-    // FIXME: Move-capture Name once we can use C++14.
-    return [=,&JIT](TargetAddress Addr) {
-      auto FPSym = JIT.findSymbolIn(H, Name, true);
-      assert(FPSym && "Cannot find function pointer to update.");
-      void *FPAddr = reinterpret_cast<void*>(
-                       static_cast<uintptr_t>(FPSym.getAddress()));
-      memcpy(FPAddr, &Addr, sizeof(uintptr_t));
-    };
+/// @brief Base class for managing collections of named indirect stubs.
+class IndirectStubsManagerBase {
+public:
+
+  /// @brief Map type for initializing the manager. See init.
+  typedef StringMap<std::pair<TargetAddress, JITSymbolFlags>> StubInitsMap;
+
+  virtual ~IndirectStubsManagerBase() {}
+
+  /// @brief Create StubInits.size() stubs with the given names, target
+  ///        addresses, and flags.
+  virtual std::error_code createStubs(const StubInitsMap &StubInits) = 0;
+
+  /// @brief Find the stub with the given name. If ExportedStubsOnly is true,
+  ///        this will only return a result if the stub's flags indicate that it
+  ///        is exported.
+  virtual JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) = 0;
+
+  /// @brief Find the implementation-pointer for the stub.
+  virtual JITSymbol findPointer(StringRef Name) = 0;
+
+  /// @brief Change the value of the implementation pointer for the stub.
+  virtual std::error_code updatePointer(StringRef Name, TargetAddress NewAddr) = 0;
+private:
+  virtual void anchor();
+};
+
+/// @brief IndirectStubsManager implementation for a concrete target, e.g. OrcX86_64.
+///        (See OrcTargetSupport.h).
+template <typename TargetT>
+class IndirectStubsManager : public IndirectStubsManagerBase {
+public:
+
+  std::error_code
+  createStubs(const StubInitsMap &StubInits) override {
+    if (auto EC = TargetT::emitIndirectStubsBlock(IndirectStubsInfo,
+                                                  StubInits.size(),
+                                                  nullptr))
+      return EC;
+
+    unsigned I = 0;
+    for (auto &Entry : StubInits) {
+      *IndirectStubsInfo.getPtr(I) =
+        reinterpret_cast<void*>(static_cast<uintptr_t>(Entry.second.first));
+      StubIndexes[Entry.first()] = std::make_pair(I++, Entry.second.second);
+    }
+
+    return std::error_code();
+  }
+
+  JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
+    auto I = StubIndexes.find(Name);
+    if (I == StubIndexes.end())
+      return nullptr;
+    void *StubAddr = IndirectStubsInfo.getStub(I->second.first);
+    assert(StubAddr && "Missing stub address");
+    auto StubTargetAddr =
+      static_cast<TargetAddress>(reinterpret_cast<uintptr_t>(StubAddr));
+    auto StubSymbol = JITSymbol(StubTargetAddr, I->second.second);
+    if (ExportedStubsOnly && !StubSymbol.isExported())
+      return nullptr;
+    return StubSymbol;
+  }
+
+  JITSymbol findPointer(StringRef Name) override {
+    auto I = StubIndexes.find(Name);
+    if (I == StubIndexes.end())
+      return nullptr;
+    void *PtrAddr = IndirectStubsInfo.getPtr(StubIndexes[Name].first);
+    assert(PtrAddr && "Missing pointer address");
+    auto PtrTargetAddr =
+      static_cast<TargetAddress>(reinterpret_cast<uintptr_t>(PtrAddr));
+    return JITSymbol(PtrTargetAddr, JITSymbolFlags::None);
+  }
+
+  std::error_code updatePointer(StringRef Name, TargetAddress NewAddr) override {
+    assert(StubIndexes.count(Name) && "No stub pointer for symbol");
+    *IndirectStubsInfo.getPtr(StubIndexes[Name].first) =
+      reinterpret_cast<void*>(static_cast<uintptr_t>(NewAddr));
+    return std::error_code();
   }
 
+private:
+  typename TargetT::IndirectStubsInfo IndirectStubsInfo;
+  StringMap<std::pair<unsigned, JITSymbolFlags>> StubIndexes;
+};
+
 /// @brief Build a function pointer of FunctionType with the given constant
 ///        address.
 ///
@@ -248,29 +326,62 @@ GlobalVariable* createImplPointer(PointerType &PT, Module &M,
 
 /// @brief Turn a function declaration into a stub function that makes an
 ///        indirect call using the given function pointer.
-void makeStub(Function &F, GlobalVariable &ImplPointer);
+void makeStub(Function &F, Value &ImplPointer);
 
-typedef std::map<Module*, DenseSet<const GlobalValue*>> ModulePartitionMap;
-
-/// @brief Extract subsections of a Module into the given Module according to
-///        the given ModulePartitionMap.
-void partition(Module &M, const ModulePartitionMap &PMap);
-
-/// @brief Struct for trivial "complete" partitioning of a module.
-class FullyPartitionedModule {
-public:
-  std::unique_ptr<Module> GlobalVars;
-  std::unique_ptr<Module> Commons;
-  std::vector<std::unique_ptr<Module>> Functions;
-
-  FullyPartitionedModule() = default;
-  FullyPartitionedModule(FullyPartitionedModule &&S)
-      : GlobalVars(std::move(S.GlobalVars)), Commons(std::move(S.Commons)),
-        Functions(std::move(S.Functions)) {}
-};
+/// @brief Raise linkage types and rename as necessary to ensure that all
+///        symbols are accessible for other modules.
+///
+///   This should be called before partitioning a module to ensure that the
+/// partitions retain access to each other's symbols.
+void makeAllSymbolsExternallyAccessible(Module &M);
 
-/// @brief Extract every function in M into a separate module.
-FullyPartitionedModule fullyPartition(Module &M);
+/// @brief Clone a function declaration into a new module.
+///
+///   This function can be used as the first step towards creating a callback
+/// stub (see makeStub), or moving a function body (see moveFunctionBody).
+///
+///   If the VMap argument is non-null, a mapping will be added between F and
+/// the new declaration, and between each of F's arguments and the new
+/// declaration's arguments. This map can then be passed in to moveFunction to
+/// move the function body if required. Note: When moving functions between
+/// modules with these utilities, all decls should be cloned (and added to a
+/// single VMap) before any bodies are moved. This will ensure that references
+/// between functions all refer to the versions in the new module.
+Function* cloneFunctionDecl(Module &Dst, const Function &F,
+                            ValueToValueMapTy *VMap = nullptr);
+
+/// @brief Move the body of function 'F' to a cloned function declaration in a
+///        different module (See related cloneFunctionDecl).
+///
+///   If the target function declaration is not supplied via the NewF parameter
+/// then it will be looked up via the VMap.
+///
+///   This will delete the body of function 'F' from its original parent module,
+/// but leave its declaration.
+void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
+                      ValueMaterializer *Materializer = nullptr,
+                      Function *NewF = nullptr);
+
+/// @brief Clone a global variable declaration into a new module.
+GlobalVariable* cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
+                                        ValueToValueMapTy *VMap = nullptr);
+
+/// @brief Move global variable GV from its parent module to cloned global
+///        declaration in a different module.
+///
+///   If the target global declaration is not supplied via the NewGV parameter
+/// then it will be looked up via the VMap.
+///
+///   This will delete the initializer of GV from its original parent module,
+/// but leave its declaration.
+void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
+                                   ValueToValueMapTy &VMap,
+                                   ValueMaterializer *Materializer = nullptr,
+                                   GlobalVariable *NewGV = nullptr);
+
+/// @brief Clone 
+GlobalAlias* cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
+                                  ValueToValueMapTy &VMap);
 
 } // End namespace orc.
 } // End namespace llvm.