83
|
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
|
120
|
17 #include "llvm/ADT/StringMap.h"
|
|
18 #include "llvm/ADT/StringRef.h"
|
|
19 #include "llvm/ADT/Twine.h"
|
|
20 #include "llvm/ExecutionEngine/JITSymbol.h"
|
83
|
21 #include "llvm/IR/IRBuilder.h"
|
|
22 #include "llvm/IR/Mangler.h"
|
|
23 #include "llvm/IR/Module.h"
|
120
|
24 #include "llvm/Support/Error.h"
|
|
25 #include "llvm/Support/Memory.h"
|
100
|
26 #include "llvm/Support/Process.h"
|
120
|
27 #include "llvm/Transforms/Utils/ValueMapper.h"
|
|
28 #include <algorithm>
|
|
29 #include <cassert>
|
|
30 #include <cstdint>
|
|
31 #include <functional>
|
|
32 #include <map>
|
|
33 #include <memory>
|
|
34 #include <system_error>
|
|
35 #include <utility>
|
|
36 #include <vector>
|
83
|
37
|
|
38 namespace llvm {
|
95
|
39 namespace orc {
|
83
|
40
|
100
|
41 /// @brief Target-independent base class for compile callback management.
|
|
42 class JITCompileCallbackManager {
|
83
|
43 public:
|
120
|
44 typedef std::function<JITTargetAddress()> CompileFtor;
|
95
|
45
|
|
46 /// @brief Handle to a newly created compile callback. Can be used to get an
|
|
47 /// IR constant representing the address of the trampoline, and to set
|
|
48 /// the compile action for the callback.
|
|
49 class CompileCallbackInfo {
|
|
50 public:
|
120
|
51 CompileCallbackInfo(JITTargetAddress Addr, CompileFtor &Compile)
|
|
52 : Addr(Addr), Compile(Compile) {}
|
95
|
53
|
120
|
54 JITTargetAddress getAddress() const { return Addr; }
|
95
|
55 void setCompileAction(CompileFtor Compile) {
|
|
56 this->Compile = std::move(Compile);
|
|
57 }
|
120
|
58
|
95
|
59 private:
|
120
|
60 JITTargetAddress Addr;
|
95
|
61 CompileFtor &Compile;
|
|
62 };
|
|
63
|
100
|
64 /// @brief Construct a JITCompileCallbackManager.
|
83
|
65 /// @param ErrorHandlerAddress The address of an error handler in the target
|
|
66 /// process to be used if a compile callback fails.
|
120
|
67 JITCompileCallbackManager(JITTargetAddress ErrorHandlerAddress)
|
|
68 : ErrorHandlerAddress(ErrorHandlerAddress) {}
|
83
|
69
|
120
|
70 virtual ~JITCompileCallbackManager() = default;
|
95
|
71
|
83
|
72 /// @brief Execute the callback for the given trampoline id. Called by the JIT
|
|
73 /// to compile functions on demand.
|
120
|
74 JITTargetAddress executeCompileCallback(JITTargetAddress TrampolineAddr) {
|
95
|
75 auto I = ActiveTrampolines.find(TrampolineAddr);
|
83
|
76 // FIXME: Also raise an error in the Orc error-handler when we finally have
|
|
77 // one.
|
|
78 if (I == ActiveTrampolines.end())
|
|
79 return ErrorHandlerAddress;
|
|
80
|
|
81 // Found a callback handler. Yank this trampoline out of the active list and
|
|
82 // put it back in the available trampolines list, then try to run the
|
|
83 // handler's compile and update actions.
|
120
|
84 // Moving the trampoline ID back to the available list first means there's
|
|
85 // at
|
|
86 // least one available trampoline if the compile action triggers a request
|
|
87 // for
|
83
|
88 // a new one.
|
95
|
89 auto Compile = std::move(I->second);
|
83
|
90 ActiveTrampolines.erase(I);
|
95
|
91 AvailableTrampolines.push_back(TrampolineAddr);
|
|
92
|
|
93 if (auto Addr = Compile())
|
|
94 return Addr;
|
|
95
|
|
96 return ErrorHandlerAddress;
|
|
97 }
|
|
98
|
|
99 /// @brief Reserve a compile callback.
|
100
|
100 CompileCallbackInfo getCompileCallback() {
|
120
|
101 JITTargetAddress TrampolineAddr = getAvailableTrampolineAddr();
|
100
|
102 auto &Compile = this->ActiveTrampolines[TrampolineAddr];
|
|
103 return CompileCallbackInfo(TrampolineAddr, Compile);
|
|
104 }
|
83
|
105
|
95
|
106 /// @brief Get a CompileCallbackInfo for an existing callback.
|
120
|
107 CompileCallbackInfo getCompileCallbackInfo(JITTargetAddress TrampolineAddr) {
|
95
|
108 auto I = ActiveTrampolines.find(TrampolineAddr);
|
|
109 assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
|
|
110 return CompileCallbackInfo(I->first, I->second);
|
|
111 }
|
|
112
|
|
113 /// @brief Release a compile callback.
|
|
114 ///
|
|
115 /// Note: Callbacks are auto-released after they execute. This method should
|
|
116 /// only be called to manually release a callback that is not going to
|
|
117 /// execute.
|
120
|
118 void releaseCompileCallback(JITTargetAddress TrampolineAddr) {
|
95
|
119 auto I = ActiveTrampolines.find(TrampolineAddr);
|
|
120 assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
|
|
121 ActiveTrampolines.erase(I);
|
|
122 AvailableTrampolines.push_back(TrampolineAddr);
|
83
|
123 }
|
|
124
|
|
125 protected:
|
120
|
126 JITTargetAddress ErrorHandlerAddress;
|
83
|
127
|
120
|
128 typedef std::map<JITTargetAddress, CompileFtor> TrampolineMapT;
|
83
|
129 TrampolineMapT ActiveTrampolines;
|
120
|
130 std::vector<JITTargetAddress> AvailableTrampolines;
|
83
|
131
|
|
132 private:
|
120
|
133 JITTargetAddress getAvailableTrampolineAddr() {
|
83
|
134 if (this->AvailableTrampolines.empty())
|
100
|
135 grow();
|
83
|
136 assert(!this->AvailableTrampolines.empty() &&
|
|
137 "Failed to grow available trampolines.");
|
120
|
138 JITTargetAddress TrampolineAddr = this->AvailableTrampolines.back();
|
83
|
139 this->AvailableTrampolines.pop_back();
|
|
140 return TrampolineAddr;
|
|
141 }
|
|
142
|
100
|
143 // Create new trampolines - to be implemented in subclasses.
|
|
144 virtual void grow() = 0;
|
|
145
|
|
146 virtual void anchor();
|
|
147 };
|
|
148
|
|
149 /// @brief Manage compile callbacks for in-process JITs.
|
|
150 template <typename TargetT>
|
|
151 class LocalJITCompileCallbackManager : public JITCompileCallbackManager {
|
|
152 public:
|
|
153 /// @brief Construct a InProcessJITCompileCallbackManager.
|
|
154 /// @param ErrorHandlerAddress The address of an error handler in the target
|
|
155 /// process to be used if a compile callback fails.
|
120
|
156 LocalJITCompileCallbackManager(JITTargetAddress ErrorHandlerAddress)
|
|
157 : JITCompileCallbackManager(ErrorHandlerAddress) {
|
100
|
158
|
|
159 /// Set up the resolver block.
|
|
160 std::error_code EC;
|
120
|
161 ResolverBlock = sys::OwningMemoryBlock(sys::Memory::allocateMappedMemory(
|
|
162 TargetT::ResolverCodeSize, nullptr,
|
|
163 sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC));
|
100
|
164 assert(!EC && "Failed to allocate resolver block");
|
|
165
|
|
166 TargetT::writeResolverCode(static_cast<uint8_t *>(ResolverBlock.base()),
|
|
167 &reenter, this);
|
|
168
|
|
169 EC = sys::Memory::protectMappedMemory(ResolverBlock.getMemoryBlock(),
|
|
170 sys::Memory::MF_READ |
|
|
171 sys::Memory::MF_EXEC);
|
|
172 assert(!EC && "Failed to mprotect resolver block");
|
|
173 }
|
|
174
|
|
175 private:
|
120
|
176 static JITTargetAddress reenter(void *CCMgr, void *TrampolineId) {
|
100
|
177 JITCompileCallbackManager *Mgr =
|
120
|
178 static_cast<JITCompileCallbackManager *>(CCMgr);
|
100
|
179 return Mgr->executeCompileCallback(
|
120
|
180 static_cast<JITTargetAddress>(
|
|
181 reinterpret_cast<uintptr_t>(TrampolineId)));
|
100
|
182 }
|
|
183
|
|
184 void grow() override {
|
83
|
185 assert(this->AvailableTrampolines.empty() && "Growing prematurely?");
|
100
|
186
|
|
187 std::error_code EC;
|
|
188 auto TrampolineBlock =
|
120
|
189 sys::OwningMemoryBlock(sys::Memory::allocateMappedMemory(
|
|
190 sys::Process::getPageSize(), nullptr,
|
|
191 sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC));
|
100
|
192 assert(!EC && "Failed to allocate trampoline block");
|
|
193
|
|
194 unsigned NumTrampolines =
|
120
|
195 (sys::Process::getPageSize() - TargetT::PointerSize) /
|
100
|
196 TargetT::TrampolineSize;
|
|
197
|
120
|
198 uint8_t *TrampolineMem = static_cast<uint8_t *>(TrampolineBlock.base());
|
100
|
199 TargetT::writeTrampolines(TrampolineMem, ResolverBlock.base(),
|
|
200 NumTrampolines);
|
|
201
|
|
202 for (unsigned I = 0; I < NumTrampolines; ++I)
|
|
203 this->AvailableTrampolines.push_back(
|
120
|
204 static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(
|
100
|
205 TrampolineMem + (I * TargetT::TrampolineSize))));
|
|
206
|
|
207 EC = sys::Memory::protectMappedMemory(TrampolineBlock.getMemoryBlock(),
|
|
208 sys::Memory::MF_READ |
|
|
209 sys::Memory::MF_EXEC);
|
|
210 assert(!EC && "Failed to mprotect trampoline block");
|
|
211
|
|
212 TrampolineBlocks.push_back(std::move(TrampolineBlock));
|
83
|
213 }
|
|
214
|
100
|
215 sys::OwningMemoryBlock ResolverBlock;
|
|
216 std::vector<sys::OwningMemoryBlock> TrampolineBlocks;
|
|
217 };
|
|
218
|
|
219 /// @brief Base class for managing collections of named indirect stubs.
|
|
220 class IndirectStubsManager {
|
|
221 public:
|
120
|
222 /// @brief Map type for initializing the manager. See init.
|
|
223 typedef StringMap<std::pair<JITTargetAddress, JITSymbolFlags>> StubInitsMap;
|
100
|
224
|
120
|
225 virtual ~IndirectStubsManager() = default;
|
100
|
226
|
|
227 /// @brief Create a single stub with the given name, target address and flags.
|
120
|
228 virtual Error createStub(StringRef StubName, JITTargetAddress StubAddr,
|
|
229 JITSymbolFlags StubFlags) = 0;
|
100
|
230
|
|
231 /// @brief Create StubInits.size() stubs with the given names, target
|
|
232 /// addresses, and flags.
|
120
|
233 virtual Error createStubs(const StubInitsMap &StubInits) = 0;
|
100
|
234
|
|
235 /// @brief Find the stub with the given name. If ExportedStubsOnly is true,
|
|
236 /// this will only return a result if the stub's flags indicate that it
|
|
237 /// is exported.
|
|
238 virtual JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) = 0;
|
|
239
|
|
240 /// @brief Find the implementation-pointer for the stub.
|
|
241 virtual JITSymbol findPointer(StringRef Name) = 0;
|
|
242
|
|
243 /// @brief Change the value of the implementation pointer for the stub.
|
120
|
244 virtual Error updatePointer(StringRef Name, JITTargetAddress NewAddr) = 0;
|
|
245
|
100
|
246 private:
|
|
247 virtual void anchor();
|
|
248 };
|
|
249
|
|
250 /// @brief IndirectStubsManager implementation for the host architecture, e.g.
|
|
251 /// OrcX86_64. (See OrcArchitectureSupport.h).
|
|
252 template <typename TargetT>
|
|
253 class LocalIndirectStubsManager : public IndirectStubsManager {
|
|
254 public:
|
120
|
255 Error createStub(StringRef StubName, JITTargetAddress StubAddr,
|
|
256 JITSymbolFlags StubFlags) override {
|
|
257 if (auto Err = reserveStubs(1))
|
|
258 return Err;
|
100
|
259
|
|
260 createStubInternal(StubName, StubAddr, StubFlags);
|
|
261
|
120
|
262 return Error::success();
|
100
|
263 }
|
|
264
|
120
|
265 Error createStubs(const StubInitsMap &StubInits) override {
|
|
266 if (auto Err = reserveStubs(StubInits.size()))
|
|
267 return Err;
|
100
|
268
|
|
269 for (auto &Entry : StubInits)
|
|
270 createStubInternal(Entry.first(), Entry.second.first,
|
|
271 Entry.second.second);
|
|
272
|
120
|
273 return Error::success();
|
100
|
274 }
|
|
275
|
|
276 JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
|
|
277 auto I = StubIndexes.find(Name);
|
|
278 if (I == StubIndexes.end())
|
|
279 return nullptr;
|
|
280 auto Key = I->second.first;
|
|
281 void *StubAddr = IndirectStubsInfos[Key.first].getStub(Key.second);
|
|
282 assert(StubAddr && "Missing stub address");
|
|
283 auto StubTargetAddr =
|
120
|
284 static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(StubAddr));
|
100
|
285 auto StubSymbol = JITSymbol(StubTargetAddr, I->second.second);
|
120
|
286 if (ExportedStubsOnly && !StubSymbol.getFlags().isExported())
|
100
|
287 return nullptr;
|
|
288 return StubSymbol;
|
|
289 }
|
|
290
|
|
291 JITSymbol findPointer(StringRef Name) override {
|
|
292 auto I = StubIndexes.find(Name);
|
|
293 if (I == StubIndexes.end())
|
|
294 return nullptr;
|
|
295 auto Key = I->second.first;
|
|
296 void *PtrAddr = IndirectStubsInfos[Key.first].getPtr(Key.second);
|
|
297 assert(PtrAddr && "Missing pointer address");
|
|
298 auto PtrTargetAddr =
|
120
|
299 static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(PtrAddr));
|
100
|
300 return JITSymbol(PtrTargetAddr, I->second.second);
|
|
301 }
|
|
302
|
120
|
303 Error updatePointer(StringRef Name, JITTargetAddress NewAddr) override {
|
100
|
304 auto I = StubIndexes.find(Name);
|
|
305 assert(I != StubIndexes.end() && "No stub pointer for symbol");
|
|
306 auto Key = I->second.first;
|
|
307 *IndirectStubsInfos[Key.first].getPtr(Key.second) =
|
120
|
308 reinterpret_cast<void *>(static_cast<uintptr_t>(NewAddr));
|
|
309 return Error::success();
|
100
|
310 }
|
|
311
|
|
312 private:
|
120
|
313 Error reserveStubs(unsigned NumStubs) {
|
100
|
314 if (NumStubs <= FreeStubs.size())
|
120
|
315 return Error::success();
|
100
|
316
|
|
317 unsigned NewStubsRequired = NumStubs - FreeStubs.size();
|
|
318 unsigned NewBlockId = IndirectStubsInfos.size();
|
|
319 typename TargetT::IndirectStubsInfo ISI;
|
120
|
320 if (auto Err =
|
|
321 TargetT::emitIndirectStubsBlock(ISI, NewStubsRequired, nullptr))
|
|
322 return Err;
|
100
|
323 for (unsigned I = 0; I < ISI.getNumStubs(); ++I)
|
|
324 FreeStubs.push_back(std::make_pair(NewBlockId, I));
|
|
325 IndirectStubsInfos.push_back(std::move(ISI));
|
120
|
326 return Error::success();
|
100
|
327 }
|
|
328
|
120
|
329 void createStubInternal(StringRef StubName, JITTargetAddress InitAddr,
|
100
|
330 JITSymbolFlags StubFlags) {
|
|
331 auto Key = FreeStubs.back();
|
|
332 FreeStubs.pop_back();
|
|
333 *IndirectStubsInfos[Key.first].getPtr(Key.second) =
|
120
|
334 reinterpret_cast<void *>(static_cast<uintptr_t>(InitAddr));
|
100
|
335 StubIndexes[StubName] = std::make_pair(Key, StubFlags);
|
|
336 }
|
|
337
|
|
338 std::vector<typename TargetT::IndirectStubsInfo> IndirectStubsInfos;
|
|
339 typedef std::pair<uint16_t, uint16_t> StubKey;
|
|
340 std::vector<StubKey> FreeStubs;
|
|
341 StringMap<std::pair<StubKey, JITSymbolFlags>> StubIndexes;
|
83
|
342 };
|
|
343
|
120
|
344 /// @brief Create a local compile callback manager.
|
|
345 ///
|
|
346 /// The given target triple will determine the ABI, and the given
|
|
347 /// ErrorHandlerAddress will be used by the resulting compile callback
|
|
348 /// manager if a compile callback fails.
|
|
349 std::unique_ptr<JITCompileCallbackManager>
|
|
350 createLocalCompileCallbackManager(const Triple &T,
|
|
351 JITTargetAddress ErrorHandlerAddress);
|
|
352
|
|
353 /// @brief Create a local indriect stubs manager builder.
|
|
354 ///
|
|
355 /// The given target triple will determine the ABI.
|
|
356 std::function<std::unique_ptr<IndirectStubsManager>()>
|
|
357 createLocalIndirectStubsManagerBuilder(const Triple &T);
|
|
358
|
95
|
359 /// @brief Build a function pointer of FunctionType with the given constant
|
|
360 /// address.
|
|
361 ///
|
|
362 /// Usage example: Turn a trampoline address into a function pointer constant
|
|
363 /// for use in a stub.
|
120
|
364 Constant *createIRTypedAddress(FunctionType &FT, JITTargetAddress Addr);
|
83
|
365
|
95
|
366 /// @brief Create a function pointer with the given type, name, and initializer
|
|
367 /// in the given Module.
|
120
|
368 GlobalVariable *createImplPointer(PointerType &PT, Module &M, const Twine &Name,
|
|
369 Constant *Initializer);
|
95
|
370
|
|
371 /// @brief Turn a function declaration into a stub function that makes an
|
|
372 /// indirect call using the given function pointer.
|
100
|
373 void makeStub(Function &F, Value &ImplPointer);
|
83
|
374
|
95
|
375 /// @brief Raise linkage types and rename as necessary to ensure that all
|
|
376 /// symbols are accessible for other modules.
|
|
377 ///
|
|
378 /// This should be called before partitioning a module to ensure that the
|
|
379 /// partitions retain access to each other's symbols.
|
|
380 void makeAllSymbolsExternallyAccessible(Module &M);
|
83
|
381
|
95
|
382 /// @brief Clone a function declaration into a new module.
|
|
383 ///
|
|
384 /// This function can be used as the first step towards creating a callback
|
|
385 /// stub (see makeStub), or moving a function body (see moveFunctionBody).
|
|
386 ///
|
|
387 /// If the VMap argument is non-null, a mapping will be added between F and
|
|
388 /// the new declaration, and between each of F's arguments and the new
|
|
389 /// declaration's arguments. This map can then be passed in to moveFunction to
|
|
390 /// move the function body if required. Note: When moving functions between
|
|
391 /// modules with these utilities, all decls should be cloned (and added to a
|
|
392 /// single VMap) before any bodies are moved. This will ensure that references
|
|
393 /// between functions all refer to the versions in the new module.
|
120
|
394 Function *cloneFunctionDecl(Module &Dst, const Function &F,
|
95
|
395 ValueToValueMapTy *VMap = nullptr);
|
83
|
396
|
95
|
397 /// @brief Move the body of function 'F' to a cloned function declaration in a
|
|
398 /// different module (See related cloneFunctionDecl).
|
|
399 ///
|
|
400 /// If the target function declaration is not supplied via the NewF parameter
|
|
401 /// then it will be looked up via the VMap.
|
|
402 ///
|
|
403 /// This will delete the body of function 'F' from its original parent module,
|
|
404 /// but leave its declaration.
|
|
405 void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
|
|
406 ValueMaterializer *Materializer = nullptr,
|
|
407 Function *NewF = nullptr);
|
|
408
|
|
409 /// @brief Clone a global variable declaration into a new module.
|
120
|
410 GlobalVariable *cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
|
95
|
411 ValueToValueMapTy *VMap = nullptr);
|
83
|
412
|
95
|
413 /// @brief Move global variable GV from its parent module to cloned global
|
|
414 /// declaration in a different module.
|
|
415 ///
|
|
416 /// If the target global declaration is not supplied via the NewGV parameter
|
|
417 /// then it will be looked up via the VMap.
|
|
418 ///
|
|
419 /// This will delete the initializer of GV from its original parent module,
|
|
420 /// but leave its declaration.
|
|
421 void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
|
|
422 ValueToValueMapTy &VMap,
|
|
423 ValueMaterializer *Materializer = nullptr,
|
|
424 GlobalVariable *NewGV = nullptr);
|
83
|
425
|
120
|
426 /// @brief Clone a global alias declaration into a new module.
|
|
427 GlobalAlias *cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
|
100
|
428 ValueToValueMapTy &VMap);
|
83
|
429
|
120
|
430 /// @brief Clone module flags metadata into the destination module.
|
|
431 void cloneModuleFlagsMetadata(Module &Dst, const Module &Src,
|
|
432 ValueToValueMapTy &VMap);
|
|
433
|
|
434 } // end namespace orc
|
|
435 } // end namespace llvm
|
83
|
436
|
|
437 #endif // LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H
|