[Orc] Rename IndirectStubsManagerBase method 'init' to 'createStubs'.
[oota-llvm.git] / include / llvm / ExecutionEngine / Orc / IndirectionUtils.h
1 //===-- IndirectionUtils.h - Utilities for adding indirections --*- C++ -*-===//
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 // Contains utilities for adding indirections and breaking up modules.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H
15 #define LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H
16
17 #include "JITSymbol.h"
18 #include "LambdaResolver.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ExecutionEngine/RuntimeDyld.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/Mangler.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Transforms/Utils/ValueMapper.h"
25 #include <sstream>
26
27 namespace llvm {
28 namespace orc {
29
30 /// @brief Base class for JITLayer independent aspects of
31 ///        JITCompileCallbackManager.
32 class JITCompileCallbackManagerBase {
33 public:
34
35   typedef std::function<TargetAddress()> CompileFtor;
36
37   /// @brief Handle to a newly created compile callback. Can be used to get an
38   ///        IR constant representing the address of the trampoline, and to set
39   ///        the compile action for the callback.
40   class CompileCallbackInfo {
41   public:
42     CompileCallbackInfo(TargetAddress Addr, CompileFtor &Compile)
43       : Addr(Addr), Compile(Compile) {}
44
45     TargetAddress getAddress() const { return Addr; }
46     void setCompileAction(CompileFtor Compile) {
47       this->Compile = std::move(Compile);
48     }
49   private:
50     TargetAddress Addr;
51     CompileFtor &Compile;
52   };
53
54   /// @brief Construct a JITCompileCallbackManagerBase.
55   /// @param ErrorHandlerAddress The address of an error handler in the target
56   ///                            process to be used if a compile callback fails.
57   /// @param NumTrampolinesPerBlock Number of trampolines to emit if there is no
58   ///                             available trampoline when getCompileCallback is
59   ///                             called.
60   JITCompileCallbackManagerBase(TargetAddress ErrorHandlerAddress,
61                                 unsigned NumTrampolinesPerBlock)
62     : ErrorHandlerAddress(ErrorHandlerAddress),
63       NumTrampolinesPerBlock(NumTrampolinesPerBlock) {}
64
65   virtual ~JITCompileCallbackManagerBase() {}
66
67   /// @brief Execute the callback for the given trampoline id. Called by the JIT
68   ///        to compile functions on demand.
69   TargetAddress executeCompileCallback(TargetAddress TrampolineAddr) {
70     auto I = ActiveTrampolines.find(TrampolineAddr);
71     // FIXME: Also raise an error in the Orc error-handler when we finally have
72     //        one.
73     if (I == ActiveTrampolines.end())
74       return ErrorHandlerAddress;
75
76     // Found a callback handler. Yank this trampoline out of the active list and
77     // put it back in the available trampolines list, then try to run the
78     // handler's compile and update actions.
79     // Moving the trampoline ID back to the available list first means there's at
80     // least one available trampoline if the compile action triggers a request for
81     // a new one.
82     auto Compile = std::move(I->second);
83     ActiveTrampolines.erase(I);
84     AvailableTrampolines.push_back(TrampolineAddr);
85
86     if (auto Addr = Compile())
87       return Addr;
88
89     return ErrorHandlerAddress;
90   }
91
92   /// @brief Reserve a compile callback.
93   virtual CompileCallbackInfo getCompileCallback(LLVMContext &Context) = 0;
94
95   /// @brief Get a CompileCallbackInfo for an existing callback.
96   CompileCallbackInfo getCompileCallbackInfo(TargetAddress TrampolineAddr) {
97     auto I = ActiveTrampolines.find(TrampolineAddr);
98     assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
99     return CompileCallbackInfo(I->first, I->second);
100   }
101
102   /// @brief Release a compile callback.
103   ///
104   ///   Note: Callbacks are auto-released after they execute. This method should
105   /// only be called to manually release a callback that is not going to
106   /// execute.
107   void releaseCompileCallback(TargetAddress TrampolineAddr) {
108     auto I = ActiveTrampolines.find(TrampolineAddr);
109     assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
110     ActiveTrampolines.erase(I);
111     AvailableTrampolines.push_back(TrampolineAddr);
112   }
113
114 protected:
115   TargetAddress ErrorHandlerAddress;
116   unsigned NumTrampolinesPerBlock;
117
118   typedef std::map<TargetAddress, CompileFtor> TrampolineMapT;
119   TrampolineMapT ActiveTrampolines;
120   std::vector<TargetAddress> AvailableTrampolines;
121
122 private:
123   virtual void anchor();
124 };
125
126 /// @brief Manage compile callbacks.
127 template <typename JITLayerT, typename TargetT>
128 class JITCompileCallbackManager : public JITCompileCallbackManagerBase {
129 public:
130
131   /// @brief Construct a JITCompileCallbackManager.
132   /// @param JIT JIT layer to emit callback trampolines, etc. into.
133   /// @param Context LLVMContext to use for trampoline & resolve block modules.
134   /// @param ErrorHandlerAddress The address of an error handler in the target
135   ///                            process to be used if a compile callback fails.
136   /// @param NumTrampolinesPerBlock Number of trampolines to allocate whenever
137   ///                               there is no existing callback trampoline.
138   ///                               (Trampolines are allocated in blocks for
139   ///                               efficiency.)
140   JITCompileCallbackManager(JITLayerT &JIT, RuntimeDyld::MemoryManager &MemMgr,
141                             LLVMContext &Context,
142                             TargetAddress ErrorHandlerAddress,
143                             unsigned NumTrampolinesPerBlock)
144     : JITCompileCallbackManagerBase(ErrorHandlerAddress,
145                                     NumTrampolinesPerBlock),
146       JIT(JIT), MemMgr(MemMgr) {
147     emitResolverBlock(Context);
148   }
149
150   /// @brief Get/create a compile callback with the given signature.
151   CompileCallbackInfo getCompileCallback(LLVMContext &Context) final {
152     TargetAddress TrampolineAddr = getAvailableTrampolineAddr(Context);
153     auto &Compile = this->ActiveTrampolines[TrampolineAddr];
154     return CompileCallbackInfo(TrampolineAddr, Compile);
155   }
156
157 private:
158
159   std::vector<std::unique_ptr<Module>>
160   SingletonSet(std::unique_ptr<Module> M) {
161     std::vector<std::unique_ptr<Module>> Ms;
162     Ms.push_back(std::move(M));
163     return Ms;
164   }
165
166   void emitResolverBlock(LLVMContext &Context) {
167     std::unique_ptr<Module> M(new Module("resolver_block_module",
168                                          Context));
169     TargetT::insertResolverBlock(*M, *this);
170     auto NonResolver =
171       createLambdaResolver(
172           [](const std::string &Name) -> RuntimeDyld::SymbolInfo {
173             llvm_unreachable("External symbols in resolver block?");
174           },
175           [](const std::string &Name) -> RuntimeDyld::SymbolInfo {
176             llvm_unreachable("Dylib symbols in resolver block?");
177           });
178     auto H = JIT.addModuleSet(SingletonSet(std::move(M)), &MemMgr,
179                               std::move(NonResolver));
180     JIT.emitAndFinalize(H);
181     auto ResolverBlockSymbol =
182       JIT.findSymbolIn(H, TargetT::ResolverBlockName, false);
183     assert(ResolverBlockSymbol && "Failed to insert resolver block");
184     ResolverBlockAddr = ResolverBlockSymbol.getAddress();
185   }
186
187   TargetAddress getAvailableTrampolineAddr(LLVMContext &Context) {
188     if (this->AvailableTrampolines.empty())
189       grow(Context);
190     assert(!this->AvailableTrampolines.empty() &&
191            "Failed to grow available trampolines.");
192     TargetAddress TrampolineAddr = this->AvailableTrampolines.back();
193     this->AvailableTrampolines.pop_back();
194     return TrampolineAddr;
195   }
196
197   void grow(LLVMContext &Context) {
198     assert(this->AvailableTrampolines.empty() && "Growing prematurely?");
199     std::unique_ptr<Module> M(new Module("trampoline_block", Context));
200     auto GetLabelName =
201       TargetT::insertCompileCallbackTrampolines(*M, ResolverBlockAddr,
202                                                 this->NumTrampolinesPerBlock,
203                                                 this->ActiveTrampolines.size());
204     auto NonResolver =
205       createLambdaResolver(
206           [](const std::string &Name) -> RuntimeDyld::SymbolInfo {
207             llvm_unreachable("External symbols in trampoline block?");
208           },
209           [](const std::string &Name) -> RuntimeDyld::SymbolInfo {
210             llvm_unreachable("Dylib symbols in trampoline block?");
211           });
212     auto H = JIT.addModuleSet(SingletonSet(std::move(M)), &MemMgr,
213                               std::move(NonResolver));
214     JIT.emitAndFinalize(H);
215     for (unsigned I = 0; I < this->NumTrampolinesPerBlock; ++I) {
216       std::string Name = GetLabelName(I);
217       auto TrampolineSymbol = JIT.findSymbolIn(H, Name, false);
218       assert(TrampolineSymbol && "Failed to emit trampoline.");
219       this->AvailableTrampolines.push_back(TrampolineSymbol.getAddress());
220     }
221   }
222
223   JITLayerT &JIT;
224   RuntimeDyld::MemoryManager &MemMgr;
225   TargetAddress ResolverBlockAddr;
226 };
227
228 /// @brief Base class for managing collections of named indirect stubs.
229 class IndirectStubsManagerBase {
230 public:
231
232   /// @brief Map type for initializing the manager. See init.
233   typedef StringMap<std::pair<TargetAddress, JITSymbolFlags>> StubInitsMap;
234
235   virtual ~IndirectStubsManagerBase() {}
236
237   /// @brief Create StubInits.size() stubs with the given names, target
238   ///        addresses, and flags.
239   virtual std::error_code createStubs(const StubInitsMap &StubInits) = 0;
240
241   /// @brief Find the stub with the given name. If ExportedStubsOnly is true,
242   ///        this will only return a result if the stub's flags indicate that it
243   ///        is exported.
244   virtual JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) = 0;
245
246   /// @brief Find the implementation-pointer for the stub.
247   virtual JITSymbol findPointer(StringRef Name) = 0;
248
249   /// @brief Change the value of the implementation pointer for the stub.
250   virtual std::error_code updatePointer(StringRef Name, TargetAddress NewAddr) = 0;
251 private:
252   virtual void anchor();
253 };
254
255 /// @brief IndirectStubsManager implementation for a concrete target, e.g. OrcX86_64.
256 ///        (See OrcTargetSupport.h).
257 template <typename TargetT>
258 class IndirectStubsManager : public IndirectStubsManagerBase {
259 public:
260
261   std::error_code
262   createStubs(const StubInitsMap &StubInits) override {
263     if (auto EC = TargetT::emitIndirectStubsBlock(IndirectStubsInfo,
264                                                   StubInits.size(),
265                                                   nullptr))
266       return EC;
267
268     unsigned I = 0;
269     for (auto &Entry : StubInits) {
270       *IndirectStubsInfo.getPtr(I) =
271         reinterpret_cast<void*>(static_cast<uintptr_t>(Entry.second.first));
272       StubIndexes[Entry.first()] = std::make_pair(I++, Entry.second.second);
273     }
274
275     return std::error_code();
276   }
277
278   JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
279     auto I = StubIndexes.find(Name);
280     if (I == StubIndexes.end())
281       return nullptr;
282     void *StubAddr = IndirectStubsInfo.getStub(I->second.first);
283     assert(StubAddr && "Missing stub address");
284     auto StubTargetAddr =
285       static_cast<TargetAddress>(reinterpret_cast<uintptr_t>(StubAddr));
286     auto StubSymbol = JITSymbol(StubTargetAddr, I->second.second);
287     if (ExportedStubsOnly && !StubSymbol.isExported())
288       return nullptr;
289     return StubSymbol;
290   }
291
292   JITSymbol findPointer(StringRef Name) override {
293     auto I = StubIndexes.find(Name);
294     if (I == StubIndexes.end())
295       return nullptr;
296     void *PtrAddr = IndirectStubsInfo.getPtr(StubIndexes[Name].first);
297     assert(PtrAddr && "Missing pointer address");
298     auto PtrTargetAddr =
299       static_cast<TargetAddress>(reinterpret_cast<uintptr_t>(PtrAddr));
300     return JITSymbol(PtrTargetAddr, JITSymbolFlags::None);
301   }
302
303   std::error_code updatePointer(StringRef Name, TargetAddress NewAddr) override {
304     assert(StubIndexes.count(Name) && "No stub pointer for symbol");
305     *IndirectStubsInfo.getPtr(StubIndexes[Name].first) =
306       reinterpret_cast<void*>(static_cast<uintptr_t>(NewAddr));
307     return std::error_code();
308   }
309
310 private:
311   typename TargetT::IndirectStubsInfo IndirectStubsInfo;
312   StringMap<std::pair<unsigned, JITSymbolFlags>> StubIndexes;
313 };
314
315 /// @brief Build a function pointer of FunctionType with the given constant
316 ///        address.
317 ///
318 ///   Usage example: Turn a trampoline address into a function pointer constant
319 /// for use in a stub.
320 Constant* createIRTypedAddress(FunctionType &FT, TargetAddress Addr);
321
322 /// @brief Create a function pointer with the given type, name, and initializer
323 ///        in the given Module.
324 GlobalVariable* createImplPointer(PointerType &PT, Module &M,
325                                   const Twine &Name, Constant *Initializer);
326
327 /// @brief Turn a function declaration into a stub function that makes an
328 ///        indirect call using the given function pointer.
329 void makeStub(Function &F, Value &ImplPointer);
330
331 /// @brief Raise linkage types and rename as necessary to ensure that all
332 ///        symbols are accessible for other modules.
333 ///
334 ///   This should be called before partitioning a module to ensure that the
335 /// partitions retain access to each other's symbols.
336 void makeAllSymbolsExternallyAccessible(Module &M);
337
338 /// @brief Clone a function declaration into a new module.
339 ///
340 ///   This function can be used as the first step towards creating a callback
341 /// stub (see makeStub), or moving a function body (see moveFunctionBody).
342 ///
343 ///   If the VMap argument is non-null, a mapping will be added between F and
344 /// the new declaration, and between each of F's arguments and the new
345 /// declaration's arguments. This map can then be passed in to moveFunction to
346 /// move the function body if required. Note: When moving functions between
347 /// modules with these utilities, all decls should be cloned (and added to a
348 /// single VMap) before any bodies are moved. This will ensure that references
349 /// between functions all refer to the versions in the new module.
350 Function* cloneFunctionDecl(Module &Dst, const Function &F,
351                             ValueToValueMapTy *VMap = nullptr);
352
353 /// @brief Move the body of function 'F' to a cloned function declaration in a
354 ///        different module (See related cloneFunctionDecl).
355 ///
356 ///   If the target function declaration is not supplied via the NewF parameter
357 /// then it will be looked up via the VMap.
358 ///
359 ///   This will delete the body of function 'F' from its original parent module,
360 /// but leave its declaration.
361 void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
362                       ValueMaterializer *Materializer = nullptr,
363                       Function *NewF = nullptr);
364
365 /// @brief Clone a global variable declaration into a new module.
366 GlobalVariable* cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
367                                         ValueToValueMapTy *VMap = nullptr);
368
369 /// @brief Move global variable GV from its parent module to cloned global
370 ///        declaration in a different module.
371 ///
372 ///   If the target global declaration is not supplied via the NewGV parameter
373 /// then it will be looked up via the VMap.
374 ///
375 ///   This will delete the initializer of GV from its original parent module,
376 /// but leave its declaration.
377 void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
378                                    ValueToValueMapTy &VMap,
379                                    ValueMaterializer *Materializer = nullptr,
380                                    GlobalVariable *NewGV = nullptr);
381
382 /// @brief Clone 
383 GlobalAlias* cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
384                                   ValueToValueMapTy &VMap);
385
386 } // End namespace orc.
387 } // End namespace llvm.
388
389 #endif // LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H