1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
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 // This file defines a MachineCodeEmitter object that is used by the JIT to
11 // write machine code to memory and remember where relocatable values are.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "JIT.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/JITCodeEmitter.h"
21 #include "llvm/CodeGen/MachineCodeInfo.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRelocation.h"
27 #include "llvm/ExecutionEngine/GenericValue.h"
28 #include "llvm/ExecutionEngine/JITEventListener.h"
29 #include "llvm/ExecutionEngine/JITMemoryManager.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include "llvm/IR/ValueMap.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Disassembler.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/Memory.h"
43 #include "llvm/Support/MutexGuard.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetJITInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <algorithm>
50 #ifndef NDEBUG
51 #include <iomanip>
52 #endif
53 using namespace llvm;
54
55 #define DEBUG_TYPE "jit"
56
57 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
58 STATISTIC(NumRelos, "Number of relocations applied");
59 STATISTIC(NumRetries, "Number of retries with more memory");
60
61
62 // A declaration may stop being a declaration once it's fully read from bitcode.
63 // This function returns true if F is fully read and is still a declaration.
isNonGhostDeclaration(const Function * F)64 static bool isNonGhostDeclaration(const Function *F) {
65 return F->isDeclaration() && !F->isMaterializable();
66 }
67
68 //===----------------------------------------------------------------------===//
69 // JIT lazy compilation code.
70 //
71 namespace {
72 class JITEmitter;
73 class JITResolverState;
74
75 template<typename ValueTy>
76 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
77 typedef JITResolverState *ExtraData;
onRAUW__anonda3058b90111::NoRAUWValueMapConfig78 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
79 llvm_unreachable("The JIT doesn't know how to handle a"
80 " RAUW on a value it has emitted.");
81 }
82 };
83
84 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
85 typedef JITResolverState *ExtraData;
86 static void onDelete(JITResolverState *JRS, Function *F);
87 };
88
89 class JITResolverState {
90 public:
91 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
92 FunctionToLazyStubMapTy;
93 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
94 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
95 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
96 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
97 private:
98 /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
99 /// particular function so that we can reuse them if necessary.
100 FunctionToLazyStubMapTy FunctionToLazyStubMap;
101
102 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
103 /// site corresponds to, and vice versa.
104 CallSiteToFunctionMapTy CallSiteToFunctionMap;
105 FunctionToCallSitesMapTy FunctionToCallSitesMap;
106
107 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
108 /// particular GlobalVariable so that we can reuse them if necessary.
109 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
110
111 #ifndef NDEBUG
112 /// Instance of the JIT this ResolverState serves.
113 JIT *TheJIT;
114 #endif
115
116 public:
JITResolverState(JIT * jit)117 JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
118 FunctionToCallSitesMap(this) {
119 #ifndef NDEBUG
120 TheJIT = jit;
121 #endif
122 }
123
getFunctionToLazyStubMap()124 FunctionToLazyStubMapTy& getFunctionToLazyStubMap() {
125 return FunctionToLazyStubMap;
126 }
127
getGlobalToIndirectSymMap()128 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap() {
129 return GlobalToIndirectSymMap;
130 }
131
LookupFunctionFromCallSite(void * CallSite) const132 std::pair<void *, Function *> LookupFunctionFromCallSite(
133 void *CallSite) const {
134 // The address given to us for the stub may not be exactly right, it
135 // might be a little bit after the stub. As such, use upper_bound to
136 // find it.
137 CallSiteToFunctionMapTy::const_iterator I =
138 CallSiteToFunctionMap.upper_bound(CallSite);
139 assert(I != CallSiteToFunctionMap.begin() &&
140 "This is not a known call site!");
141 --I;
142 return *I;
143 }
144
AddCallSite(void * CallSite,Function * F)145 void AddCallSite(void *CallSite, Function *F) {
146 bool Inserted = CallSiteToFunctionMap.insert(
147 std::make_pair(CallSite, F)).second;
148 (void)Inserted;
149 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
150 FunctionToCallSitesMap[F].insert(CallSite);
151 }
152
153 void EraseAllCallSitesForPrelocked(Function *F);
154
155 // Erases _all_ call sites regardless of their function. This is used to
156 // unregister the stub addresses from the StubToResolverMap in
157 // ~JITResolver().
158 void EraseAllCallSitesPrelocked();
159 };
160
161 /// JITResolver - Keep track of, and resolve, call sites for functions that
162 /// have not yet been compiled.
163 class JITResolver {
164 typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
165 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
166 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
167
168 /// LazyResolverFn - The target lazy resolver function that we actually
169 /// rewrite instructions to use.
170 TargetJITInfo::LazyResolverFn LazyResolverFn;
171
172 JITResolverState state;
173
174 /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
175 /// for external functions. TODO: Of course, external functions don't need
176 /// a lazy stub. It's actually here to make it more likely that far calls
177 /// succeed, but no single stub can guarantee that. I'll remove this in a
178 /// subsequent checkin when I actually fix far calls.
179 std::map<void*, void*> ExternalFnToStubMap;
180
181 /// revGOTMap - map addresses to indexes in the GOT
182 std::map<void*, unsigned> revGOTMap;
183 unsigned nextGOTIndex;
184
185 JITEmitter &JE;
186
187 /// Instance of JIT corresponding to this Resolver.
188 JIT *TheJIT;
189
190 public:
JITResolver(JIT & jit,JITEmitter & je)191 explicit JITResolver(JIT &jit, JITEmitter &je)
192 : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
193 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
194 }
195
196 ~JITResolver();
197
198 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
199 /// lazy-compilation stub if it has already been created.
200 void *getLazyFunctionStubIfAvailable(Function *F);
201
202 /// getLazyFunctionStub - This returns a pointer to a function's
203 /// lazy-compilation stub, creating one on demand as needed.
204 void *getLazyFunctionStub(Function *F);
205
206 /// getExternalFunctionStub - Return a stub for the function at the
207 /// specified address, created lazily on demand.
208 void *getExternalFunctionStub(void *FnAddr);
209
210 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
211 /// specified GV address.
212 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
213
214 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
215 /// an address. This function only manages slots, it does not manage the
216 /// contents of the slots or the memory associated with the GOT.
217 unsigned getGOTIndexForAddr(void *addr);
218
219 /// JITCompilerFn - This function is called to resolve a stub to a compiled
220 /// address. If the LLVM Function corresponding to the stub has not yet
221 /// been compiled, this function compiles it first.
222 static void *JITCompilerFn(void *Stub);
223 };
224
225 class StubToResolverMapTy {
226 /// Map a stub address to a specific instance of a JITResolver so that
227 /// lazily-compiled functions can find the right resolver to use.
228 ///
229 /// Guarded by Lock.
230 std::map<void*, JITResolver*> Map;
231
232 /// Guards Map from concurrent accesses.
233 mutable sys::Mutex Lock;
234
235 public:
236 /// Registers a Stub to be resolved by Resolver.
RegisterStubResolver(void * Stub,JITResolver * Resolver)237 void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
238 MutexGuard guard(Lock);
239 Map.insert(std::make_pair(Stub, Resolver));
240 }
241 /// Unregisters the Stub when it's invalidated.
UnregisterStubResolver(void * Stub)242 void UnregisterStubResolver(void *Stub) {
243 MutexGuard guard(Lock);
244 Map.erase(Stub);
245 }
246 /// Returns the JITResolver instance that owns the Stub.
getResolverFromStub(void * Stub) const247 JITResolver *getResolverFromStub(void *Stub) const {
248 MutexGuard guard(Lock);
249 // The address given to us for the stub may not be exactly right, it might
250 // be a little bit after the stub. As such, use upper_bound to find it.
251 // This is the same trick as in LookupFunctionFromCallSite from
252 // JITResolverState.
253 std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
254 assert(I != Map.begin() && "This is not a known stub!");
255 --I;
256 return I->second;
257 }
258 /// True if any stubs refer to the given resolver. Only used in an assert().
259 /// O(N)
ResolverHasStubs(JITResolver * Resolver) const260 bool ResolverHasStubs(JITResolver* Resolver) const {
261 MutexGuard guard(Lock);
262 for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
263 E = Map.end(); I != E; ++I) {
264 if (I->second == Resolver)
265 return true;
266 }
267 return false;
268 }
269 };
270 /// This needs to be static so that a lazy call stub can access it with no
271 /// context except the address of the stub.
272 ManagedStatic<StubToResolverMapTy> StubToResolverMap;
273
274 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
275 /// used to output functions to memory for execution.
276 class JITEmitter : public JITCodeEmitter {
277 JITMemoryManager *MemMgr;
278
279 // When outputting a function stub in the context of some other function, we
280 // save BufferBegin/BufferEnd/CurBufferPtr here.
281 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
282
283 // When reattempting to JIT a function after running out of space, we store
284 // the estimated size of the function we're trying to JIT here, so we can
285 // ask the memory manager for at least this much space. When we
286 // successfully emit the function, we reset this back to zero.
287 uintptr_t SizeEstimate;
288
289 /// Relocations - These are the relocations that the function needs, as
290 /// emitted.
291 std::vector<MachineRelocation> Relocations;
292
293 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
294 /// It is filled in by the StartMachineBasicBlock callback and queried by
295 /// the getMachineBasicBlockAddress callback.
296 std::vector<uintptr_t> MBBLocations;
297
298 /// ConstantPool - The constant pool for the current function.
299 ///
300 MachineConstantPool *ConstantPool;
301
302 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
303 ///
304 void *ConstantPoolBase;
305
306 /// ConstPoolAddresses - Addresses of individual constant pool entries.
307 ///
308 SmallVector<uintptr_t, 8> ConstPoolAddresses;
309
310 /// JumpTable - The jump tables for the current function.
311 ///
312 MachineJumpTableInfo *JumpTable;
313
314 /// JumpTableBase - A pointer to the first entry in the jump table.
315 ///
316 void *JumpTableBase;
317
318 /// Resolver - This contains info about the currently resolved functions.
319 JITResolver Resolver;
320
321 /// LabelLocations - This vector is a mapping from Label ID's to their
322 /// address.
323 DenseMap<MCSymbol*, uintptr_t> LabelLocations;
324
325 /// MMI - Machine module info for exception informations
326 MachineModuleInfo* MMI;
327
328 // CurFn - The llvm function being emitted. Only valid during
329 // finishFunction().
330 const Function *CurFn;
331
332 /// Information about emitted code, which is passed to the
333 /// JITEventListeners. This is reset in startFunction and used in
334 /// finishFunction.
335 JITEvent_EmittedFunctionDetails EmissionDetails;
336
337 struct EmittedCode {
338 void *FunctionBody; // Beginning of the function's allocation.
339 void *Code; // The address the function's code actually starts at.
340 void *ExceptionTable;
EmittedCode__anonda3058b90111::JITEmitter::EmittedCode341 EmittedCode() : FunctionBody(nullptr), Code(nullptr),
342 ExceptionTable(nullptr) {}
343 };
344 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
345 typedef JITEmitter *ExtraData;
346 static void onDelete(JITEmitter *, const Function*);
347 static void onRAUW(JITEmitter *, const Function*, const Function*);
348 };
349 ValueMap<const Function *, EmittedCode,
350 EmittedFunctionConfig> EmittedFunctions;
351
352 DebugLoc PrevDL;
353
354 /// Instance of the JIT
355 JIT *TheJIT;
356
357 public:
JITEmitter(JIT & jit,JITMemoryManager * JMM,TargetMachine & TM)358 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
359 : SizeEstimate(0), Resolver(jit, *this), MMI(nullptr), CurFn(nullptr),
360 EmittedFunctions(this), TheJIT(&jit) {
361 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
362 if (jit.getJITInfo().needsGOT()) {
363 MemMgr->AllocateGOT();
364 DEBUG(dbgs() << "JIT is managing a GOT\n");
365 }
366
367 }
~JITEmitter()368 ~JITEmitter() {
369 delete MemMgr;
370 }
371
getJITResolver()372 JITResolver &getJITResolver() { return Resolver; }
373
374 void startFunction(MachineFunction &F) override;
375 bool finishFunction(MachineFunction &F) override;
376
377 void emitConstantPool(MachineConstantPool *MCP);
378 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
379 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
380
381 void startGVStub(const GlobalValue* GV,
382 unsigned StubSize, unsigned Alignment = 1);
383 void startGVStub(void *Buffer, unsigned StubSize);
384 void finishGVStub();
385 void *allocIndirectGV(const GlobalValue *GV, const uint8_t *Buffer,
386 size_t Size, unsigned Alignment) override;
387
388 /// allocateSpace - Reserves space in the current block if any, or
389 /// allocate a new one of the given size.
390 void *allocateSpace(uintptr_t Size, unsigned Alignment) override;
391
392 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
393 /// this method does not allocate memory in the current output buffer,
394 /// because a global may live longer than the current function.
395 void *allocateGlobal(uintptr_t Size, unsigned Alignment) override;
396
addRelocation(const MachineRelocation & MR)397 void addRelocation(const MachineRelocation &MR) override {
398 Relocations.push_back(MR);
399 }
400
StartMachineBasicBlock(MachineBasicBlock * MBB)401 void StartMachineBasicBlock(MachineBasicBlock *MBB) override {
402 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
403 MBBLocations.resize((MBB->getNumber()+1)*2);
404 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
405 if (MBB->hasAddressTaken())
406 TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
407 (void*)getCurrentPCValue());
408 DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
409 << (void*) getCurrentPCValue() << "]\n");
410 }
411
412 uintptr_t getConstantPoolEntryAddress(unsigned Entry) const override;
413 uintptr_t getJumpTableEntryAddress(unsigned Entry) const override;
414
415 uintptr_t
getMachineBasicBlockAddress(MachineBasicBlock * MBB) const416 getMachineBasicBlockAddress(MachineBasicBlock *MBB) const override {
417 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
418 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
419 return MBBLocations[MBB->getNumber()];
420 }
421
422 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
423 /// given function. Increase the minimum allocation size so that we get
424 /// more memory next time.
425 void retryWithMoreMemory(MachineFunction &F);
426
427 /// deallocateMemForFunction - Deallocate all memory for the specified
428 /// function body.
429 void deallocateMemForFunction(const Function *F);
430
431 void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) override;
432
emitLabel(MCSymbol * Label)433 void emitLabel(MCSymbol *Label) override {
434 LabelLocations[Label] = getCurrentPCValue();
435 }
436
getLabelLocations()437 DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() override {
438 return &LabelLocations;
439 }
440
getLabelAddress(MCSymbol * Label) const441 uintptr_t getLabelAddress(MCSymbol *Label) const override {
442 assert(LabelLocations.count(Label) && "Label not emitted!");
443 return LabelLocations.find(Label)->second;
444 }
445
setModuleInfo(MachineModuleInfo * Info)446 void setModuleInfo(MachineModuleInfo* Info) override {
447 MMI = Info;
448 }
449
450 private:
451 void *getPointerToGlobal(GlobalValue *GV, void *Reference,
452 bool MayNeedFarStub);
453 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
454 };
455 }
456
onDelete(JITResolverState * JRS,Function * F)457 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
458 JRS->EraseAllCallSitesForPrelocked(F);
459 }
460
EraseAllCallSitesForPrelocked(Function * F)461 void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
462 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
463 if (F2C == FunctionToCallSitesMap.end())
464 return;
465 StubToResolverMapTy &S2RMap = *StubToResolverMap;
466 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
467 E = F2C->second.end(); I != E; ++I) {
468 S2RMap.UnregisterStubResolver(*I);
469 bool Erased = CallSiteToFunctionMap.erase(*I);
470 (void)Erased;
471 assert(Erased && "Missing call site->function mapping");
472 }
473 FunctionToCallSitesMap.erase(F2C);
474 }
475
EraseAllCallSitesPrelocked()476 void JITResolverState::EraseAllCallSitesPrelocked() {
477 StubToResolverMapTy &S2RMap = *StubToResolverMap;
478 for (CallSiteToFunctionMapTy::const_iterator
479 I = CallSiteToFunctionMap.begin(),
480 E = CallSiteToFunctionMap.end(); I != E; ++I) {
481 S2RMap.UnregisterStubResolver(I->first);
482 }
483 CallSiteToFunctionMap.clear();
484 FunctionToCallSitesMap.clear();
485 }
486
~JITResolver()487 JITResolver::~JITResolver() {
488 // No need to lock because we're in the destructor, and state isn't shared.
489 state.EraseAllCallSitesPrelocked();
490 assert(!StubToResolverMap->ResolverHasStubs(this) &&
491 "Resolver destroyed with stubs still alive.");
492 }
493
494 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
495 /// if it has already been created.
getLazyFunctionStubIfAvailable(Function * F)496 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
497 MutexGuard locked(TheJIT->lock);
498
499 // If we already have a stub for this function, recycle it.
500 return state.getFunctionToLazyStubMap().lookup(F);
501 }
502
503 /// getFunctionStub - This returns a pointer to a function stub, creating
504 /// one on demand as needed.
getLazyFunctionStub(Function * F)505 void *JITResolver::getLazyFunctionStub(Function *F) {
506 MutexGuard locked(TheJIT->lock);
507
508 // If we already have a lazy stub for this function, recycle it.
509 void *&Stub = state.getFunctionToLazyStubMap()[F];
510 if (Stub) return Stub;
511
512 // Call the lazy resolver function if we are JIT'ing lazily. Otherwise we
513 // must resolve the symbol now.
514 void *Actual = TheJIT->isCompilingLazily()
515 ? (void *)(intptr_t)LazyResolverFn : (void *)nullptr;
516
517 // If this is an external declaration, attempt to resolve the address now
518 // to place in the stub.
519 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
520 Actual = TheJIT->getPointerToFunction(F);
521
522 // If we resolved the symbol to a null address (eg. a weak external)
523 // don't emit a stub. Return a null pointer to the application.
524 if (!Actual) return nullptr;
525 }
526
527 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
528 JE.startGVStub(F, SL.Size, SL.Alignment);
529 // Codegen a new stub, calling the lazy resolver or the actual address of the
530 // external function, if it was resolved.
531 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
532 JE.finishGVStub();
533
534 if (Actual != (void*)(intptr_t)LazyResolverFn) {
535 // If we are getting the stub for an external function, we really want the
536 // address of the stub in the GlobalAddressMap for the JIT, not the address
537 // of the external function.
538 TheJIT->updateGlobalMapping(F, Stub);
539 }
540
541 DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
542 << F->getName() << "'\n");
543
544 if (TheJIT->isCompilingLazily()) {
545 // Register this JITResolver as the one corresponding to this call site so
546 // JITCompilerFn will be able to find it.
547 StubToResolverMap->RegisterStubResolver(Stub, this);
548
549 // Finally, keep track of the stub-to-Function mapping so that the
550 // JITCompilerFn knows which function to compile!
551 state.AddCallSite(Stub, F);
552 } else if (!Actual) {
553 // If we are JIT'ing non-lazily but need to call a function that does not
554 // exist yet, add it to the JIT's work list so that we can fill in the
555 // stub address later.
556 assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
557 "'Actual' should have been set above.");
558 TheJIT->addPendingFunction(F);
559 }
560
561 return Stub;
562 }
563
564 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
565 /// GV address.
getGlobalValueIndirectSym(GlobalValue * GV,void * GVAddress)566 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
567 MutexGuard locked(TheJIT->lock);
568
569 // If we already have a stub for this global variable, recycle it.
570 void *&IndirectSym = state.getGlobalToIndirectSymMap()[GV];
571 if (IndirectSym) return IndirectSym;
572
573 // Otherwise, codegen a new indirect symbol.
574 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
575 JE);
576
577 DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
578 << "] for GV '" << GV->getName() << "'\n");
579
580 return IndirectSym;
581 }
582
583 /// getExternalFunctionStub - Return a stub for the function at the
584 /// specified address, created lazily on demand.
getExternalFunctionStub(void * FnAddr)585 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
586 // If we already have a stub for this function, recycle it.
587 void *&Stub = ExternalFnToStubMap[FnAddr];
588 if (Stub) return Stub;
589
590 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
591 JE.startGVStub(nullptr, SL.Size, SL.Alignment);
592 Stub = TheJIT->getJITInfo().emitFunctionStub(nullptr, FnAddr, JE);
593 JE.finishGVStub();
594
595 DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
596 << "] for external function at '" << FnAddr << "'\n");
597 return Stub;
598 }
599
getGOTIndexForAddr(void * addr)600 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
601 unsigned idx = revGOTMap[addr];
602 if (!idx) {
603 idx = ++nextGOTIndex;
604 revGOTMap[addr] = idx;
605 DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
606 << addr << "]\n");
607 }
608 return idx;
609 }
610
611 /// JITCompilerFn - This function is called when a lazy compilation stub has
612 /// been entered. It looks up which function this stub corresponds to, compiles
613 /// it if necessary, then returns the resultant function pointer.
JITCompilerFn(void * Stub)614 void *JITResolver::JITCompilerFn(void *Stub) {
615 JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
616 assert(JR && "Unable to find the corresponding JITResolver to the call site");
617
618 Function* F = nullptr;
619 void* ActualPtr = nullptr;
620
621 {
622 // Only lock for getting the Function. The call getPointerToFunction made
623 // in this function might trigger function materializing, which requires
624 // JIT lock to be unlocked.
625 MutexGuard locked(JR->TheJIT->lock);
626
627 // The address given to us for the stub may not be exactly right, it might
628 // be a little bit after the stub. As such, use upper_bound to find it.
629 std::pair<void*, Function*> I =
630 JR->state.LookupFunctionFromCallSite(Stub);
631 F = I.second;
632 ActualPtr = I.first;
633 }
634
635 // If we have already code generated the function, just return the address.
636 void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
637
638 if (!Result) {
639 // Otherwise we don't have it, do lazy compilation now.
640
641 // If lazy compilation is disabled, emit a useful error message and abort.
642 if (!JR->TheJIT->isCompilingLazily()) {
643 report_fatal_error("LLVM JIT requested to do lazy compilation of"
644 " function '"
645 + F->getName() + "' when lazy compiles are disabled!");
646 }
647
648 DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
649 << "' In stub ptr = " << Stub << " actual ptr = "
650 << ActualPtr << "\n");
651 (void)ActualPtr;
652
653 Result = JR->TheJIT->getPointerToFunction(F);
654 }
655
656 // Reacquire the lock to update the GOT map.
657 MutexGuard locked(JR->TheJIT->lock);
658
659 // We might like to remove the call site from the CallSiteToFunction map, but
660 // we can't do that! Multiple threads could be stuck, waiting to acquire the
661 // lock above. As soon as the 1st function finishes compiling the function,
662 // the next one will be released, and needs to be able to find the function it
663 // needs to call.
664
665 // FIXME: We could rewrite all references to this stub if we knew them.
666
667 // What we will do is set the compiled function address to map to the
668 // same GOT entry as the stub so that later clients may update the GOT
669 // if they see it still using the stub address.
670 // Note: this is done so the Resolver doesn't have to manage GOT memory
671 // Do this without allocating map space if the target isn't using a GOT
672 if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
673 JR->revGOTMap[Result] = JR->revGOTMap[Stub];
674
675 return Result;
676 }
677
678 //===----------------------------------------------------------------------===//
679 // JITEmitter code.
680 //
681
getSimpleAliasee(Constant * C)682 static GlobalObject *getSimpleAliasee(Constant *C) {
683 C = C->stripPointerCasts();
684 return dyn_cast<GlobalObject>(C);
685 }
686
getPointerToGlobal(GlobalValue * V,void * Reference,bool MayNeedFarStub)687 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
688 bool MayNeedFarStub) {
689 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
690 return TheJIT->getOrEmitGlobalVariable(GV);
691
692 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
693 // We can only handle simple cases.
694 if (GlobalValue *GV = getSimpleAliasee(GA->getAliasee()))
695 return TheJIT->getPointerToGlobal(GV);
696 return nullptr;
697 }
698
699 // If we have already compiled the function, return a pointer to its body.
700 Function *F = cast<Function>(V);
701
702 void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
703 if (FnStub) {
704 // Return the function stub if it's already created. We do this first so
705 // that we're returning the same address for the function as any previous
706 // call. TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
707 // close enough to call.
708 return FnStub;
709 }
710
711 // If we know the target can handle arbitrary-distance calls, try to
712 // return a direct pointer.
713 if (!MayNeedFarStub) {
714 // If we have code, go ahead and return that.
715 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
716 if (ResultPtr) return ResultPtr;
717
718 // If this is an external function pointer, we can force the JIT to
719 // 'compile' it, which really just adds it to the map.
720 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
721 return TheJIT->getPointerToFunction(F);
722 }
723
724 // Otherwise, we may need a to emit a stub, and, conservatively, we always do
725 // so. Note that it's possible to return null from getLazyFunctionStub in the
726 // case of a weak extern that fails to resolve.
727 return Resolver.getLazyFunctionStub(F);
728 }
729
getPointerToGVIndirectSym(GlobalValue * V,void * Reference)730 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
731 // Make sure GV is emitted first, and create a stub containing the fully
732 // resolved address.
733 void *GVAddress = getPointerToGlobal(V, Reference, false);
734 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
735 return StubAddr;
736 }
737
processDebugLoc(DebugLoc DL,bool BeforePrintingInsn)738 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
739 if (DL.isUnknown()) return;
740 if (!BeforePrintingInsn) return;
741
742 const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
743
744 if (DL.getScope(Context) != nullptr && PrevDL != DL) {
745 JITEvent_EmittedFunctionDetails::LineStart NextLine;
746 NextLine.Address = getCurrentPCValue();
747 NextLine.Loc = DL;
748 EmissionDetails.LineStarts.push_back(NextLine);
749 }
750
751 PrevDL = DL;
752 }
753
GetConstantPoolSizeInBytes(MachineConstantPool * MCP,const DataLayout * TD)754 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
755 const DataLayout *TD) {
756 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
757 if (Constants.empty()) return 0;
758
759 unsigned Size = 0;
760 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
761 MachineConstantPoolEntry CPE = Constants[i];
762 unsigned AlignMask = CPE.getAlignment() - 1;
763 Size = (Size + AlignMask) & ~AlignMask;
764 Type *Ty = CPE.getType();
765 Size += TD->getTypeAllocSize(Ty);
766 }
767 return Size;
768 }
769
startFunction(MachineFunction & F)770 void JITEmitter::startFunction(MachineFunction &F) {
771 DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
772 << F.getName() << "\n");
773
774 uintptr_t ActualSize = 0;
775 // Set the memory writable, if it's not already
776 MemMgr->setMemoryWritable();
777
778 if (SizeEstimate > 0) {
779 // SizeEstimate will be non-zero on reallocation attempts.
780 ActualSize = SizeEstimate;
781 }
782
783 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
784 ActualSize);
785 BufferEnd = BufferBegin+ActualSize;
786 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
787
788 // Ensure the constant pool/jump table info is at least 4-byte aligned.
789 emitAlignment(16);
790
791 emitConstantPool(F.getConstantPool());
792 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
793 initJumpTableInfo(MJTI);
794
795 // About to start emitting the machine code for the function.
796 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
797 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
798 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
799
800 MBBLocations.clear();
801
802 EmissionDetails.MF = &F;
803 EmissionDetails.LineStarts.clear();
804 }
805
finishFunction(MachineFunction & F)806 bool JITEmitter::finishFunction(MachineFunction &F) {
807 if (CurBufferPtr == BufferEnd) {
808 // We must call endFunctionBody before retrying, because
809 // deallocateMemForFunction requires it.
810 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
811 retryWithMoreMemory(F);
812 return true;
813 }
814
815 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
816 emitJumpTableInfo(MJTI);
817
818 // FnStart is the start of the text, not the start of the constant pool and
819 // other per-function data.
820 uint8_t *FnStart =
821 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
822
823 // FnEnd is the end of the function's machine code.
824 uint8_t *FnEnd = CurBufferPtr;
825
826 if (!Relocations.empty()) {
827 CurFn = F.getFunction();
828 NumRelos += Relocations.size();
829
830 // Resolve the relocations to concrete pointers.
831 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
832 MachineRelocation &MR = Relocations[i];
833 void *ResultPtr = nullptr;
834 if (!MR.letTargetResolve()) {
835 if (MR.isExternalSymbol()) {
836 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
837 false);
838 DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
839 << ResultPtr << "]\n");
840
841 // If the target REALLY wants a stub for this function, emit it now.
842 if (MR.mayNeedFarStub()) {
843 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
844 }
845 } else if (MR.isGlobalValue()) {
846 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
847 BufferBegin+MR.getMachineCodeOffset(),
848 MR.mayNeedFarStub());
849 } else if (MR.isIndirectSymbol()) {
850 ResultPtr = getPointerToGVIndirectSym(
851 MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
852 } else if (MR.isBasicBlock()) {
853 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
854 } else if (MR.isConstantPoolIndex()) {
855 ResultPtr =
856 (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
857 } else {
858 assert(MR.isJumpTableIndex());
859 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
860 }
861
862 MR.setResultPointer(ResultPtr);
863 }
864
865 // if we are managing the GOT and the relocation wants an index,
866 // give it one
867 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
868 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
869 MR.setGOTIndex(idx);
870 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
871 DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
872 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
873 << "\n");
874 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
875 }
876 }
877 }
878
879 CurFn = nullptr;
880 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
881 Relocations.size(), MemMgr->getGOTBase());
882 }
883
884 // Update the GOT entry for F to point to the new code.
885 if (MemMgr->isManagingGOT()) {
886 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
887 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
888 DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
889 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
890 << "\n");
891 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
892 }
893 }
894
895 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
896 // global variables that were referenced in the relocations.
897 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
898
899 if (CurBufferPtr == BufferEnd) {
900 retryWithMoreMemory(F);
901 return true;
902 } else {
903 // Now that we've succeeded in emitting the function, reset the
904 // SizeEstimate back down to zero.
905 SizeEstimate = 0;
906 }
907
908 BufferBegin = CurBufferPtr = nullptr;
909 NumBytes += FnEnd-FnStart;
910
911 // Invalidate the icache if necessary.
912 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
913
914 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
915 EmissionDetails);
916
917 // Reset the previous debug location.
918 PrevDL = DebugLoc();
919
920 DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
921 << "] Function: " << F.getName()
922 << ": " << (FnEnd-FnStart) << " bytes of text, "
923 << Relocations.size() << " relocations\n");
924
925 Relocations.clear();
926 ConstPoolAddresses.clear();
927
928 // Mark code region readable and executable if it's not so already.
929 MemMgr->setMemoryExecutable();
930
931 DEBUG({
932 if (sys::hasDisassembler()) {
933 dbgs() << "JIT: Disassembled code:\n";
934 dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
935 (uintptr_t)FnStart);
936 } else {
937 dbgs() << "JIT: Binary code:\n";
938 uint8_t* q = FnStart;
939 for (int i = 0; q < FnEnd; q += 4, ++i) {
940 if (i == 4)
941 i = 0;
942 if (i == 0)
943 dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
944 bool Done = false;
945 for (int j = 3; j >= 0; --j) {
946 if (q + j >= FnEnd)
947 Done = true;
948 else
949 dbgs() << (unsigned short)q[j];
950 }
951 if (Done)
952 break;
953 dbgs() << ' ';
954 if (i == 3)
955 dbgs() << '\n';
956 }
957 dbgs()<< '\n';
958 }
959 });
960
961 if (MMI)
962 MMI->EndFunction();
963
964 return false;
965 }
966
retryWithMoreMemory(MachineFunction & F)967 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
968 DEBUG(dbgs() << "JIT: Ran out of space for native code. Reattempting.\n");
969 Relocations.clear(); // Clear the old relocations or we'll reapply them.
970 ConstPoolAddresses.clear();
971 ++NumRetries;
972 deallocateMemForFunction(F.getFunction());
973 // Try again with at least twice as much free space.
974 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
975
976 for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
977 if (MBB->hasAddressTaken())
978 TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
979 }
980 }
981
982 /// deallocateMemForFunction - Deallocate all memory for the specified
983 /// function body. Also drop any references the function has to stubs.
984 /// May be called while the Function is being destroyed inside ~Value().
deallocateMemForFunction(const Function * F)985 void JITEmitter::deallocateMemForFunction(const Function *F) {
986 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
987 Emitted = EmittedFunctions.find(F);
988 if (Emitted != EmittedFunctions.end()) {
989 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
990 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
991
992 EmittedFunctions.erase(Emitted);
993 }
994 }
995
996
allocateSpace(uintptr_t Size,unsigned Alignment)997 void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
998 if (BufferBegin)
999 return JITCodeEmitter::allocateSpace(Size, Alignment);
1000
1001 // create a new memory block if there is no active one.
1002 // care must be taken so that BufferBegin is invalidated when a
1003 // block is trimmed
1004 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1005 BufferEnd = BufferBegin+Size;
1006 return CurBufferPtr;
1007 }
1008
allocateGlobal(uintptr_t Size,unsigned Alignment)1009 void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1010 // Delegate this call through the memory manager.
1011 return MemMgr->allocateGlobal(Size, Alignment);
1012 }
1013
emitConstantPool(MachineConstantPool * MCP)1014 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1015 if (TheJIT->getJITInfo().hasCustomConstantPool())
1016 return;
1017
1018 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1019 if (Constants.empty()) return;
1020
1021 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
1022 unsigned Align = MCP->getConstantPoolAlignment();
1023 ConstantPoolBase = allocateSpace(Size, Align);
1024 ConstantPool = MCP;
1025
1026 if (!ConstantPoolBase) return; // Buffer overflow.
1027
1028 DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1029 << "] (size: " << Size << ", alignment: " << Align << ")\n");
1030
1031 // Initialize the memory for all of the constant pool entries.
1032 unsigned Offset = 0;
1033 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1034 MachineConstantPoolEntry CPE = Constants[i];
1035 unsigned AlignMask = CPE.getAlignment() - 1;
1036 Offset = (Offset + AlignMask) & ~AlignMask;
1037
1038 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1039 ConstPoolAddresses.push_back(CAddr);
1040 if (CPE.isMachineConstantPoolEntry()) {
1041 // FIXME: add support to lower machine constant pool values into bytes!
1042 report_fatal_error("Initialize memory with machine specific constant pool"
1043 "entry has not been implemented!");
1044 }
1045 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1046 DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
1047 dbgs().write_hex(CAddr) << "]\n");
1048
1049 Type *Ty = CPE.Val.ConstVal->getType();
1050 Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
1051 }
1052 }
1053
initJumpTableInfo(MachineJumpTableInfo * MJTI)1054 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1055 if (TheJIT->getJITInfo().hasCustomJumpTables())
1056 return;
1057 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1058 return;
1059
1060 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1061 if (JT.empty()) return;
1062
1063 unsigned NumEntries = 0;
1064 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1065 NumEntries += JT[i].MBBs.size();
1066
1067 unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
1068
1069 // Just allocate space for all the jump tables now. We will fix up the actual
1070 // MBB entries in the tables after we emit the code for each block, since then
1071 // we will know the final locations of the MBBs in memory.
1072 JumpTable = MJTI;
1073 JumpTableBase = allocateSpace(NumEntries * EntrySize,
1074 MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
1075 }
1076
emitJumpTableInfo(MachineJumpTableInfo * MJTI)1077 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1078 if (TheJIT->getJITInfo().hasCustomJumpTables())
1079 return;
1080
1081 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1082 if (JT.empty() || !JumpTableBase) return;
1083
1084
1085 switch (MJTI->getEntryKind()) {
1086 case MachineJumpTableInfo::EK_Inline:
1087 return;
1088 case MachineJumpTableInfo::EK_BlockAddress: {
1089 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1090 // .word LBB123
1091 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
1092 "Cross JIT'ing?");
1093
1094 // For each jump table, map each target in the jump table to the address of
1095 // an emitted MachineBasicBlock.
1096 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1097
1098 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1099 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1100 // Store the address of the basic block for this jump table slot in the
1101 // memory we allocated for the jump table in 'initJumpTableInfo'
1102 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1103 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1104 }
1105 break;
1106 }
1107
1108 case MachineJumpTableInfo::EK_Custom32:
1109 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1110 case MachineJumpTableInfo::EK_LabelDifference32: {
1111 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == 4&&"Cross JIT'ing?");
1112 // For each jump table, place the offset from the beginning of the table
1113 // to the target address.
1114 int *SlotPtr = (int*)JumpTableBase;
1115
1116 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1117 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1118 // Store the offset of the basic block for this jump table slot in the
1119 // memory we allocated for the jump table in 'initJumpTableInfo'
1120 uintptr_t Base = (uintptr_t)SlotPtr;
1121 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1122 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1123 /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
1124 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1125 }
1126 }
1127 break;
1128 }
1129 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1130 llvm_unreachable(
1131 "JT Info emission not implemented for GPRel64BlockAddress yet.");
1132 }
1133 }
1134
startGVStub(const GlobalValue * GV,unsigned StubSize,unsigned Alignment)1135 void JITEmitter::startGVStub(const GlobalValue* GV,
1136 unsigned StubSize, unsigned Alignment) {
1137 SavedBufferBegin = BufferBegin;
1138 SavedBufferEnd = BufferEnd;
1139 SavedCurBufferPtr = CurBufferPtr;
1140
1141 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1142 BufferEnd = BufferBegin+StubSize+1;
1143 }
1144
startGVStub(void * Buffer,unsigned StubSize)1145 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1146 SavedBufferBegin = BufferBegin;
1147 SavedBufferEnd = BufferEnd;
1148 SavedCurBufferPtr = CurBufferPtr;
1149
1150 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1151 BufferEnd = BufferBegin+StubSize+1;
1152 }
1153
finishGVStub()1154 void JITEmitter::finishGVStub() {
1155 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1156 NumBytes += getCurrentPCOffset();
1157 BufferBegin = SavedBufferBegin;
1158 BufferEnd = SavedBufferEnd;
1159 CurBufferPtr = SavedCurBufferPtr;
1160 }
1161
allocIndirectGV(const GlobalValue * GV,const uint8_t * Buffer,size_t Size,unsigned Alignment)1162 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1163 const uint8_t *Buffer, size_t Size,
1164 unsigned Alignment) {
1165 uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1166 memcpy(IndGV, Buffer, Size);
1167 return IndGV;
1168 }
1169
1170 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1171 // in the constant pool that was last emitted with the 'emitConstantPool'
1172 // method.
1173 //
getConstantPoolEntryAddress(unsigned ConstantNum) const1174 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1175 assert(ConstantNum < ConstantPool->getConstants().size() &&
1176 "Invalid ConstantPoolIndex!");
1177 return ConstPoolAddresses[ConstantNum];
1178 }
1179
1180 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1181 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1182 //
getJumpTableEntryAddress(unsigned Index) const1183 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1184 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1185 assert(Index < JT.size() && "Invalid jump table index!");
1186
1187 unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
1188
1189 unsigned Offset = 0;
1190 for (unsigned i = 0; i < Index; ++i)
1191 Offset += JT[i].MBBs.size();
1192
1193 Offset *= EntrySize;
1194
1195 return (uintptr_t)((char *)JumpTableBase + Offset);
1196 }
1197
onDelete(JITEmitter * Emitter,const Function * F)1198 void JITEmitter::EmittedFunctionConfig::onDelete(
1199 JITEmitter *Emitter, const Function *F) {
1200 Emitter->deallocateMemForFunction(F);
1201 }
onRAUW(JITEmitter *,const Function *,const Function *)1202 void JITEmitter::EmittedFunctionConfig::onRAUW(
1203 JITEmitter *, const Function*, const Function*) {
1204 llvm_unreachable("The JIT doesn't know how to handle a"
1205 " RAUW on a value it has emitted.");
1206 }
1207
1208
1209 //===----------------------------------------------------------------------===//
1210 // Public interface to this file
1211 //===----------------------------------------------------------------------===//
1212
createEmitter(JIT & jit,JITMemoryManager * JMM,TargetMachine & tm)1213 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1214 TargetMachine &tm) {
1215 return new JITEmitter(jit, JMM, tm);
1216 }
1217
1218 // getPointerToFunctionOrStub - If the specified function has been
1219 // code-gen'd, return a pointer to the function. If not, compile it, or use
1220 // a stub to implement lazy compilation if available.
1221 //
getPointerToFunctionOrStub(Function * F)1222 void *JIT::getPointerToFunctionOrStub(Function *F) {
1223 // If we have already code generated the function, just return the address.
1224 if (void *Addr = getPointerToGlobalIfAvailable(F))
1225 return Addr;
1226
1227 // Get a stub if the target supports it.
1228 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1229 return JE->getJITResolver().getLazyFunctionStub(F);
1230 }
1231
updateFunctionStubUnlocked(Function * F)1232 void JIT::updateFunctionStubUnlocked(Function *F) {
1233 // Get the empty stub we generated earlier.
1234 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1235 void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1236 void *Addr = getPointerToGlobalIfAvailable(F);
1237 assert(Addr != Stub && "Function must have non-stub address to be updated.");
1238
1239 // Tell the target jit info to rewrite the stub at the specified address,
1240 // rather than creating a new one.
1241 TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1242 JE->startGVStub(Stub, layout.Size);
1243 getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1244 JE->finishGVStub();
1245 }
1246
1247 /// freeMachineCodeForFunction - release machine code memory for given Function.
1248 ///
freeMachineCodeForFunction(Function * F)1249 void JIT::freeMachineCodeForFunction(Function *F) {
1250 // Delete translation for this from the ExecutionEngine, so it will get
1251 // retranslated next time it is used.
1252 updateGlobalMapping(F, nullptr);
1253
1254 // Free the actual memory for the function body and related stuff.
1255 static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);
1256 }
1257