1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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/ErrorHandling.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/Memory.h"
42 #include "llvm/Support/MutexGuard.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetJITInfo.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "jit"
56 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
57 STATISTIC(NumRelos, "Number of relocations applied");
58 STATISTIC(NumRetries, "Number of retries with more memory");
61 // A declaration may stop being a declaration once it's fully read from bitcode.
62 // This function returns true if F is fully read and is still a declaration.
63 static bool isNonGhostDeclaration(const Function *F) {
64 return F->isDeclaration() && !F->isMaterializable();
67 //===----------------------------------------------------------------------===//
68 // JIT lazy compilation code.
72 class JITResolverState;
74 template<typename ValueTy>
75 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
76 typedef JITResolverState *ExtraData;
77 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
78 llvm_unreachable("The JIT doesn't know how to handle a"
79 " RAUW on a value it has emitted.");
83 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
84 typedef JITResolverState *ExtraData;
85 static void onDelete(JITResolverState *JRS, Function *F);
88 class JITResolverState {
90 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
91 FunctionToLazyStubMapTy;
92 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
93 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
94 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
95 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
97 /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
98 /// particular function so that we can reuse them if necessary.
99 FunctionToLazyStubMapTy FunctionToLazyStubMap;
101 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
102 /// site corresponds to, and vice versa.
103 CallSiteToFunctionMapTy CallSiteToFunctionMap;
104 FunctionToCallSitesMapTy FunctionToCallSitesMap;
106 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
107 /// particular GlobalVariable so that we can reuse them if necessary.
108 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
111 /// Instance of the JIT this ResolverState serves.
116 JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
117 FunctionToCallSitesMap(this) {
123 FunctionToLazyStubMapTy& getFunctionToLazyStubMap() {
124 return FunctionToLazyStubMap;
127 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap() {
128 return GlobalToIndirectSymMap;
131 std::pair<void *, Function *> LookupFunctionFromCallSite(
132 void *CallSite) const {
133 // The address given to us for the stub may not be exactly right, it
134 // might be a little bit after the stub. As such, use upper_bound to
136 CallSiteToFunctionMapTy::const_iterator I =
137 CallSiteToFunctionMap.upper_bound(CallSite);
138 assert(I != CallSiteToFunctionMap.begin() &&
139 "This is not a known call site!");
144 void AddCallSite(void *CallSite, Function *F) {
145 bool Inserted = CallSiteToFunctionMap.insert(
146 std::make_pair(CallSite, F)).second;
148 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
149 FunctionToCallSitesMap[F].insert(CallSite);
152 void EraseAllCallSitesForPrelocked(Function *F);
154 // Erases _all_ call sites regardless of their function. This is used to
155 // unregister the stub addresses from the StubToResolverMap in
157 void EraseAllCallSitesPrelocked();
160 /// JITResolver - Keep track of, and resolve, call sites for functions that
161 /// have not yet been compiled.
163 typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
164 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
165 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
167 /// LazyResolverFn - The target lazy resolver function that we actually
168 /// rewrite instructions to use.
169 TargetJITInfo::LazyResolverFn LazyResolverFn;
171 JITResolverState state;
173 /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
174 /// for external functions. TODO: Of course, external functions don't need
175 /// a lazy stub. It's actually here to make it more likely that far calls
176 /// succeed, but no single stub can guarantee that. I'll remove this in a
177 /// subsequent checkin when I actually fix far calls.
178 std::map<void*, void*> ExternalFnToStubMap;
180 /// revGOTMap - map addresses to indexes in the GOT
181 std::map<void*, unsigned> revGOTMap;
182 unsigned nextGOTIndex;
186 /// Instance of JIT corresponding to this Resolver.
190 explicit JITResolver(JIT &jit, JITEmitter &je)
191 : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
192 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
197 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
198 /// lazy-compilation stub if it has already been created.
199 void *getLazyFunctionStubIfAvailable(Function *F);
201 /// getLazyFunctionStub - This returns a pointer to a function's
202 /// lazy-compilation stub, creating one on demand as needed.
203 void *getLazyFunctionStub(Function *F);
205 /// getExternalFunctionStub - Return a stub for the function at the
206 /// specified address, created lazily on demand.
207 void *getExternalFunctionStub(void *FnAddr);
209 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
210 /// specified GV address.
211 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
213 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
214 /// an address. This function only manages slots, it does not manage the
215 /// contents of the slots or the memory associated with the GOT.
216 unsigned getGOTIndexForAddr(void *addr);
218 /// JITCompilerFn - This function is called to resolve a stub to a compiled
219 /// address. If the LLVM Function corresponding to the stub has not yet
220 /// been compiled, this function compiles it first.
221 static void *JITCompilerFn(void *Stub);
224 class StubToResolverMapTy {
225 /// Map a stub address to a specific instance of a JITResolver so that
226 /// lazily-compiled functions can find the right resolver to use.
229 std::map<void*, JITResolver*> Map;
231 /// Guards Map from concurrent accesses.
232 mutable sys::Mutex Lock;
235 /// Registers a Stub to be resolved by Resolver.
236 void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
237 MutexGuard guard(Lock);
238 Map.insert(std::make_pair(Stub, Resolver));
240 /// Unregisters the Stub when it's invalidated.
241 void UnregisterStubResolver(void *Stub) {
242 MutexGuard guard(Lock);
245 /// Returns the JITResolver instance that owns the Stub.
246 JITResolver *getResolverFromStub(void *Stub) const {
247 MutexGuard guard(Lock);
248 // The address given to us for the stub may not be exactly right, it might
249 // be a little bit after the stub. As such, use upper_bound to find it.
250 // This is the same trick as in LookupFunctionFromCallSite from
252 std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
253 assert(I != Map.begin() && "This is not a known stub!");
257 /// True if any stubs refer to the given resolver. Only used in an assert().
259 bool ResolverHasStubs(JITResolver* Resolver) const {
260 MutexGuard guard(Lock);
261 for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
262 E = Map.end(); I != E; ++I) {
263 if (I->second == Resolver)
269 /// This needs to be static so that a lazy call stub can access it with no
270 /// context except the address of the stub.
271 ManagedStatic<StubToResolverMapTy> StubToResolverMap;
273 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
274 /// used to output functions to memory for execution.
275 class JITEmitter : public JITCodeEmitter {
276 JITMemoryManager *MemMgr;
278 // When outputting a function stub in the context of some other function, we
279 // save BufferBegin/BufferEnd/CurBufferPtr here.
280 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
282 // When reattempting to JIT a function after running out of space, we store
283 // the estimated size of the function we're trying to JIT here, so we can
284 // ask the memory manager for at least this much space. When we
285 // successfully emit the function, we reset this back to zero.
286 uintptr_t SizeEstimate;
288 /// Relocations - These are the relocations that the function needs, as
290 std::vector<MachineRelocation> Relocations;
292 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
293 /// It is filled in by the StartMachineBasicBlock callback and queried by
294 /// the getMachineBasicBlockAddress callback.
295 std::vector<uintptr_t> MBBLocations;
297 /// ConstantPool - The constant pool for the current function.
299 MachineConstantPool *ConstantPool;
301 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
303 void *ConstantPoolBase;
305 /// ConstPoolAddresses - Addresses of individual constant pool entries.
307 SmallVector<uintptr_t, 8> ConstPoolAddresses;
309 /// JumpTable - The jump tables for the current function.
311 MachineJumpTableInfo *JumpTable;
313 /// JumpTableBase - A pointer to the first entry in the jump table.
317 /// Resolver - This contains info about the currently resolved functions.
318 JITResolver Resolver;
320 /// LabelLocations - This vector is a mapping from Label ID's to their
322 DenseMap<MCSymbol*, uintptr_t> LabelLocations;
324 /// MMI - Machine module info for exception informations
325 MachineModuleInfo* MMI;
327 // CurFn - The llvm function being emitted. Only valid during
329 const Function *CurFn;
331 /// Information about emitted code, which is passed to the
332 /// JITEventListeners. This is reset in startFunction and used in
334 JITEvent_EmittedFunctionDetails EmissionDetails;
337 void *FunctionBody; // Beginning of the function's allocation.
338 void *Code; // The address the function's code actually starts at.
339 void *ExceptionTable;
340 EmittedCode() : FunctionBody(nullptr), Code(nullptr),
341 ExceptionTable(nullptr) {}
343 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
344 typedef JITEmitter *ExtraData;
345 static void onDelete(JITEmitter *, const Function*);
346 static void onRAUW(JITEmitter *, const Function*, const Function*);
348 ValueMap<const Function *, EmittedCode,
349 EmittedFunctionConfig> EmittedFunctions;
353 /// Instance of the JIT
357 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
358 : SizeEstimate(0), Resolver(jit, *this), MMI(nullptr), CurFn(nullptr),
359 EmittedFunctions(this), TheJIT(&jit) {
360 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
361 if (jit.getJITInfo().needsGOT()) {
362 MemMgr->AllocateGOT();
363 DEBUG(dbgs() << "JIT is managing a GOT\n");
371 JITResolver &getJITResolver() { return Resolver; }
373 void startFunction(MachineFunction &F) override;
374 bool finishFunction(MachineFunction &F) override;
376 void emitConstantPool(MachineConstantPool *MCP);
377 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
378 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
380 void startGVStub(const GlobalValue* GV,
381 unsigned StubSize, unsigned Alignment = 1);
382 void startGVStub(void *Buffer, unsigned StubSize);
384 void *allocIndirectGV(const GlobalValue *GV, const uint8_t *Buffer,
385 size_t Size, unsigned Alignment) override;
387 /// allocateSpace - Reserves space in the current block if any, or
388 /// allocate a new one of the given size.
389 void *allocateSpace(uintptr_t Size, unsigned Alignment) override;
391 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
392 /// this method does not allocate memory in the current output buffer,
393 /// because a global may live longer than the current function.
394 void *allocateGlobal(uintptr_t Size, unsigned Alignment) override;
396 void addRelocation(const MachineRelocation &MR) override {
397 Relocations.push_back(MR);
400 void StartMachineBasicBlock(MachineBasicBlock *MBB) override {
401 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
402 MBBLocations.resize((MBB->getNumber()+1)*2);
403 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
404 if (MBB->hasAddressTaken())
405 TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
406 (void*)getCurrentPCValue());
407 DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
408 << (void*) getCurrentPCValue() << "]\n");
411 uintptr_t getConstantPoolEntryAddress(unsigned Entry) const override;
412 uintptr_t getJumpTableEntryAddress(unsigned Entry) const override;
415 getMachineBasicBlockAddress(MachineBasicBlock *MBB) const override {
416 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
417 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
418 return MBBLocations[MBB->getNumber()];
421 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
422 /// given function. Increase the minimum allocation size so that we get
423 /// more memory next time.
424 void retryWithMoreMemory(MachineFunction &F);
426 /// deallocateMemForFunction - Deallocate all memory for the specified
428 void deallocateMemForFunction(const Function *F);
430 void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) override;
432 void emitLabel(MCSymbol *Label) override {
433 LabelLocations[Label] = getCurrentPCValue();
436 DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() override {
437 return &LabelLocations;
440 uintptr_t getLabelAddress(MCSymbol *Label) const override {
441 assert(LabelLocations.count(Label) && "Label not emitted!");
442 return LabelLocations.find(Label)->second;
445 void setModuleInfo(MachineModuleInfo* Info) override {
450 void *getPointerToGlobal(GlobalValue *GV, void *Reference,
451 bool MayNeedFarStub);
452 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
456 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
457 JRS->EraseAllCallSitesForPrelocked(F);
460 void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
461 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
462 if (F2C == FunctionToCallSitesMap.end())
464 StubToResolverMapTy &S2RMap = *StubToResolverMap;
465 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
466 E = F2C->second.end(); I != E; ++I) {
467 S2RMap.UnregisterStubResolver(*I);
468 bool Erased = CallSiteToFunctionMap.erase(*I);
470 assert(Erased && "Missing call site->function mapping");
472 FunctionToCallSitesMap.erase(F2C);
475 void JITResolverState::EraseAllCallSitesPrelocked() {
476 StubToResolverMapTy &S2RMap = *StubToResolverMap;
477 for (CallSiteToFunctionMapTy::const_iterator
478 I = CallSiteToFunctionMap.begin(),
479 E = CallSiteToFunctionMap.end(); I != E; ++I) {
480 S2RMap.UnregisterStubResolver(I->first);
482 CallSiteToFunctionMap.clear();
483 FunctionToCallSitesMap.clear();
486 JITResolver::~JITResolver() {
487 // No need to lock because we're in the destructor, and state isn't shared.
488 state.EraseAllCallSitesPrelocked();
489 assert(!StubToResolverMap->ResolverHasStubs(this) &&
490 "Resolver destroyed with stubs still alive.");
493 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
494 /// if it has already been created.
495 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
496 MutexGuard locked(TheJIT->lock);
498 // If we already have a stub for this function, recycle it.
499 return state.getFunctionToLazyStubMap().lookup(F);
502 /// getFunctionStub - This returns a pointer to a function stub, creating
503 /// one on demand as needed.
504 void *JITResolver::getLazyFunctionStub(Function *F) {
505 MutexGuard locked(TheJIT->lock);
507 // If we already have a lazy stub for this function, recycle it.
508 void *&Stub = state.getFunctionToLazyStubMap()[F];
509 if (Stub) return Stub;
511 // Call the lazy resolver function if we are JIT'ing lazily. Otherwise we
512 // must resolve the symbol now.
513 void *Actual = TheJIT->isCompilingLazily()
514 ? (void *)(intptr_t)LazyResolverFn : (void *)nullptr;
516 // If this is an external declaration, attempt to resolve the address now
517 // to place in the stub.
518 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
519 Actual = TheJIT->getPointerToFunction(F);
521 // If we resolved the symbol to a null address (eg. a weak external)
522 // don't emit a stub. Return a null pointer to the application.
523 if (!Actual) return nullptr;
526 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
527 JE.startGVStub(F, SL.Size, SL.Alignment);
528 // Codegen a new stub, calling the lazy resolver or the actual address of the
529 // external function, if it was resolved.
530 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
533 if (Actual != (void*)(intptr_t)LazyResolverFn) {
534 // If we are getting the stub for an external function, we really want the
535 // address of the stub in the GlobalAddressMap for the JIT, not the address
536 // of the external function.
537 TheJIT->updateGlobalMapping(F, Stub);
540 DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
541 << F->getName() << "'\n");
543 if (TheJIT->isCompilingLazily()) {
544 // Register this JITResolver as the one corresponding to this call site so
545 // JITCompilerFn will be able to find it.
546 StubToResolverMap->RegisterStubResolver(Stub, this);
548 // Finally, keep track of the stub-to-Function mapping so that the
549 // JITCompilerFn knows which function to compile!
550 state.AddCallSite(Stub, F);
551 } else if (!Actual) {
552 // If we are JIT'ing non-lazily but need to call a function that does not
553 // exist yet, add it to the JIT's work list so that we can fill in the
554 // stub address later.
555 assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
556 "'Actual' should have been set above.");
557 TheJIT->addPendingFunction(F);
563 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
565 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
566 MutexGuard locked(TheJIT->lock);
568 // If we already have a stub for this global variable, recycle it.
569 void *&IndirectSym = state.getGlobalToIndirectSymMap()[GV];
570 if (IndirectSym) return IndirectSym;
572 // Otherwise, codegen a new indirect symbol.
573 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
576 DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
577 << "] for GV '" << GV->getName() << "'\n");
582 /// getExternalFunctionStub - Return a stub for the function at the
583 /// specified address, created lazily on demand.
584 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
585 // If we already have a stub for this function, recycle it.
586 void *&Stub = ExternalFnToStubMap[FnAddr];
587 if (Stub) return Stub;
589 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
590 JE.startGVStub(nullptr, SL.Size, SL.Alignment);
591 Stub = TheJIT->getJITInfo().emitFunctionStub(nullptr, FnAddr, JE);
594 DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
595 << "] for external function at '" << FnAddr << "'\n");
599 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
600 unsigned idx = revGOTMap[addr];
602 idx = ++nextGOTIndex;
603 revGOTMap[addr] = idx;
604 DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
610 /// JITCompilerFn - This function is called when a lazy compilation stub has
611 /// been entered. It looks up which function this stub corresponds to, compiles
612 /// it if necessary, then returns the resultant function pointer.
613 void *JITResolver::JITCompilerFn(void *Stub) {
614 JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
615 assert(JR && "Unable to find the corresponding JITResolver to the call site");
617 Function* F = nullptr;
618 void* ActualPtr = nullptr;
621 // Only lock for getting the Function. The call getPointerToFunction made
622 // in this function might trigger function materializing, which requires
623 // JIT lock to be unlocked.
624 MutexGuard locked(JR->TheJIT->lock);
626 // The address given to us for the stub may not be exactly right, it might
627 // be a little bit after the stub. As such, use upper_bound to find it.
628 std::pair<void*, Function*> I =
629 JR->state.LookupFunctionFromCallSite(Stub);
634 // If we have already code generated the function, just return the address.
635 void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
638 // Otherwise we don't have it, do lazy compilation now.
640 // If lazy compilation is disabled, emit a useful error message and abort.
641 if (!JR->TheJIT->isCompilingLazily()) {
642 report_fatal_error("LLVM JIT requested to do lazy compilation of"
644 + F->getName() + "' when lazy compiles are disabled!");
647 DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
648 << "' In stub ptr = " << Stub << " actual ptr = "
649 << ActualPtr << "\n");
652 Result = JR->TheJIT->getPointerToFunction(F);
655 // Reacquire the lock to update the GOT map.
656 MutexGuard locked(JR->TheJIT->lock);
658 // We might like to remove the call site from the CallSiteToFunction map, but
659 // we can't do that! Multiple threads could be stuck, waiting to acquire the
660 // lock above. As soon as the 1st function finishes compiling the function,
661 // the next one will be released, and needs to be able to find the function it
664 // FIXME: We could rewrite all references to this stub if we knew them.
666 // What we will do is set the compiled function address to map to the
667 // same GOT entry as the stub so that later clients may update the GOT
668 // if they see it still using the stub address.
669 // Note: this is done so the Resolver doesn't have to manage GOT memory
670 // Do this without allocating map space if the target isn't using a GOT
671 if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
672 JR->revGOTMap[Result] = JR->revGOTMap[Stub];
677 //===----------------------------------------------------------------------===//
681 static GlobalObject *getSimpleAliasee(Constant *C) {
682 C = C->stripPointerCasts();
683 return dyn_cast<GlobalObject>(C);
686 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
687 bool MayNeedFarStub) {
688 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
689 return TheJIT->getOrEmitGlobalVariable(GV);
691 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
692 // We can only handle simple cases.
693 if (GlobalValue *GV = getSimpleAliasee(GA->getAliasee()))
694 return TheJIT->getPointerToGlobal(GV);
698 // If we have already compiled the function, return a pointer to its body.
699 Function *F = cast<Function>(V);
701 void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
703 // Return the function stub if it's already created. We do this first so
704 // that we're returning the same address for the function as any previous
705 // call. TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
706 // close enough to call.
710 // If we know the target can handle arbitrary-distance calls, try to
711 // return a direct pointer.
712 if (!MayNeedFarStub) {
713 // If we have code, go ahead and return that.
714 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
715 if (ResultPtr) return ResultPtr;
717 // If this is an external function pointer, we can force the JIT to
718 // 'compile' it, which really just adds it to the map.
719 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
720 return TheJIT->getPointerToFunction(F);
723 // Otherwise, we may need a to emit a stub, and, conservatively, we always do
724 // so. Note that it's possible to return null from getLazyFunctionStub in the
725 // case of a weak extern that fails to resolve.
726 return Resolver.getLazyFunctionStub(F);
729 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
730 // Make sure GV is emitted first, and create a stub containing the fully
732 void *GVAddress = getPointerToGlobal(V, Reference, false);
733 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
737 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
738 if (DL.isUnknown()) return;
739 if (!BeforePrintingInsn) return;
741 const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
743 if (DL.getScope(Context) != nullptr && PrevDL != DL) {
744 JITEvent_EmittedFunctionDetails::LineStart NextLine;
745 NextLine.Address = getCurrentPCValue();
747 EmissionDetails.LineStarts.push_back(NextLine);
753 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
754 const DataLayout *TD) {
755 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
756 if (Constants.empty()) return 0;
759 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
760 MachineConstantPoolEntry CPE = Constants[i];
761 unsigned AlignMask = CPE.getAlignment() - 1;
762 Size = (Size + AlignMask) & ~AlignMask;
763 Type *Ty = CPE.getType();
764 Size += TD->getTypeAllocSize(Ty);
769 void JITEmitter::startFunction(MachineFunction &F) {
770 DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
771 << F.getName() << "\n");
773 uintptr_t ActualSize = 0;
774 // Set the memory writable, if it's not already
775 MemMgr->setMemoryWritable();
777 if (SizeEstimate > 0) {
778 // SizeEstimate will be non-zero on reallocation attempts.
779 ActualSize = SizeEstimate;
782 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
784 BufferEnd = BufferBegin+ActualSize;
785 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
787 // Ensure the constant pool/jump table info is at least 4-byte aligned.
790 emitConstantPool(F.getConstantPool());
791 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
792 initJumpTableInfo(MJTI);
794 // About to start emitting the machine code for the function.
795 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
796 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
797 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
799 MBBLocations.clear();
801 EmissionDetails.MF = &F;
802 EmissionDetails.LineStarts.clear();
805 bool JITEmitter::finishFunction(MachineFunction &F) {
806 if (CurBufferPtr == BufferEnd) {
807 // We must call endFunctionBody before retrying, because
808 // deallocateMemForFunction requires it.
809 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
810 retryWithMoreMemory(F);
814 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
815 emitJumpTableInfo(MJTI);
817 // FnStart is the start of the text, not the start of the constant pool and
818 // other per-function data.
820 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
822 // FnEnd is the end of the function's machine code.
823 uint8_t *FnEnd = CurBufferPtr;
825 if (!Relocations.empty()) {
826 CurFn = F.getFunction();
827 NumRelos += Relocations.size();
829 // Resolve the relocations to concrete pointers.
830 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
831 MachineRelocation &MR = Relocations[i];
832 void *ResultPtr = nullptr;
833 if (!MR.letTargetResolve()) {
834 if (MR.isExternalSymbol()) {
835 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
837 DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
838 << ResultPtr << "]\n");
840 // If the target REALLY wants a stub for this function, emit it now.
841 if (MR.mayNeedFarStub()) {
842 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
844 } else if (MR.isGlobalValue()) {
845 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
846 BufferBegin+MR.getMachineCodeOffset(),
847 MR.mayNeedFarStub());
848 } else if (MR.isIndirectSymbol()) {
849 ResultPtr = getPointerToGVIndirectSym(
850 MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
851 } else if (MR.isBasicBlock()) {
852 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
853 } else if (MR.isConstantPoolIndex()) {
855 (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
857 assert(MR.isJumpTableIndex());
858 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
861 MR.setResultPointer(ResultPtr);
864 // if we are managing the GOT and the relocation wants an index,
866 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
867 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
869 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
870 DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
871 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
873 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
879 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
880 Relocations.size(), MemMgr->getGOTBase());
883 // Update the GOT entry for F to point to the new code.
884 if (MemMgr->isManagingGOT()) {
885 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
886 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
887 DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
888 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
890 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
894 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
895 // global variables that were referenced in the relocations.
896 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
898 if (CurBufferPtr == BufferEnd) {
899 retryWithMoreMemory(F);
902 // Now that we've succeeded in emitting the function, reset the
903 // SizeEstimate back down to zero.
907 BufferBegin = CurBufferPtr = nullptr;
908 NumBytes += FnEnd-FnStart;
910 // Invalidate the icache if necessary.
911 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
913 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
916 // Reset the previous debug location.
919 DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
920 << "] Function: " << F.getName()
921 << ": " << (FnEnd-FnStart) << " bytes of text, "
922 << Relocations.size() << " relocations\n");
925 ConstPoolAddresses.clear();
927 // Mark code region readable and executable if it's not so already.
928 MemMgr->setMemoryExecutable();
931 dbgs() << "JIT: Binary code:\n";
932 uint8_t* q = FnStart;
933 for (int i = 0; q < FnEnd; q += 4, ++i) {
937 dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
939 for (int j = 3; j >= 0; --j) {
943 dbgs() << (unsigned short)q[j];
960 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
961 DEBUG(dbgs() << "JIT: Ran out of space for native code. Reattempting.\n");
962 Relocations.clear(); // Clear the old relocations or we'll reapply them.
963 ConstPoolAddresses.clear();
965 deallocateMemForFunction(F.getFunction());
966 // Try again with at least twice as much free space.
967 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
969 for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
970 if (MBB->hasAddressTaken())
971 TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
975 /// deallocateMemForFunction - Deallocate all memory for the specified
976 /// function body. Also drop any references the function has to stubs.
977 /// May be called while the Function is being destroyed inside ~Value().
978 void JITEmitter::deallocateMemForFunction(const Function *F) {
979 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
980 Emitted = EmittedFunctions.find(F);
981 if (Emitted != EmittedFunctions.end()) {
982 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
983 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
985 EmittedFunctions.erase(Emitted);
990 void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
992 return JITCodeEmitter::allocateSpace(Size, Alignment);
994 // create a new memory block if there is no active one.
995 // care must be taken so that BufferBegin is invalidated when a
997 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
998 BufferEnd = BufferBegin+Size;
1002 void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1003 // Delegate this call through the memory manager.
1004 return MemMgr->allocateGlobal(Size, Alignment);
1007 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1008 if (TheJIT->getJITInfo().hasCustomConstantPool())
1011 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1012 if (Constants.empty()) return;
1014 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
1015 unsigned Align = MCP->getConstantPoolAlignment();
1016 ConstantPoolBase = allocateSpace(Size, Align);
1019 if (!ConstantPoolBase) return; // Buffer overflow.
1021 DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1022 << "] (size: " << Size << ", alignment: " << Align << ")\n");
1024 // Initialize the memory for all of the constant pool entries.
1025 unsigned Offset = 0;
1026 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1027 MachineConstantPoolEntry CPE = Constants[i];
1028 unsigned AlignMask = CPE.getAlignment() - 1;
1029 Offset = (Offset + AlignMask) & ~AlignMask;
1031 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1032 ConstPoolAddresses.push_back(CAddr);
1033 if (CPE.isMachineConstantPoolEntry()) {
1034 // FIXME: add support to lower machine constant pool values into bytes!
1035 report_fatal_error("Initialize memory with machine specific constant pool"
1036 "entry has not been implemented!");
1038 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1039 DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
1040 dbgs().write_hex(CAddr) << "]\n");
1042 Type *Ty = CPE.Val.ConstVal->getType();
1043 Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
1047 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1048 if (TheJIT->getJITInfo().hasCustomJumpTables())
1050 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1053 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1054 if (JT.empty()) return;
1056 unsigned NumEntries = 0;
1057 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1058 NumEntries += JT[i].MBBs.size();
1060 unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
1062 // Just allocate space for all the jump tables now. We will fix up the actual
1063 // MBB entries in the tables after we emit the code for each block, since then
1064 // we will know the final locations of the MBBs in memory.
1066 JumpTableBase = allocateSpace(NumEntries * EntrySize,
1067 MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
1070 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1071 if (TheJIT->getJITInfo().hasCustomJumpTables())
1074 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1075 if (JT.empty() || !JumpTableBase) return;
1078 switch (MJTI->getEntryKind()) {
1079 case MachineJumpTableInfo::EK_Inline:
1081 case MachineJumpTableInfo::EK_BlockAddress: {
1082 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1084 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
1087 // For each jump table, map each target in the jump table to the address of
1088 // an emitted MachineBasicBlock.
1089 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1091 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1092 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1093 // Store the address of the basic block for this jump table slot in the
1094 // memory we allocated for the jump table in 'initJumpTableInfo'
1095 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1096 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1101 case MachineJumpTableInfo::EK_Custom32:
1102 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1103 case MachineJumpTableInfo::EK_LabelDifference32: {
1104 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == 4&&"Cross JIT'ing?");
1105 // For each jump table, place the offset from the beginning of the table
1106 // to the target address.
1107 int *SlotPtr = (int*)JumpTableBase;
1109 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1110 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1111 // Store the offset of the basic block for this jump table slot in the
1112 // memory we allocated for the jump table in 'initJumpTableInfo'
1113 uintptr_t Base = (uintptr_t)SlotPtr;
1114 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1115 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1116 /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
1117 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1122 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1124 "JT Info emission not implemented for GPRel64BlockAddress yet.");
1128 void JITEmitter::startGVStub(const GlobalValue* GV,
1129 unsigned StubSize, unsigned Alignment) {
1130 SavedBufferBegin = BufferBegin;
1131 SavedBufferEnd = BufferEnd;
1132 SavedCurBufferPtr = CurBufferPtr;
1134 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1135 BufferEnd = BufferBegin+StubSize+1;
1138 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1139 SavedBufferBegin = BufferBegin;
1140 SavedBufferEnd = BufferEnd;
1141 SavedCurBufferPtr = CurBufferPtr;
1143 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1144 BufferEnd = BufferBegin+StubSize+1;
1147 void JITEmitter::finishGVStub() {
1148 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1149 NumBytes += getCurrentPCOffset();
1150 BufferBegin = SavedBufferBegin;
1151 BufferEnd = SavedBufferEnd;
1152 CurBufferPtr = SavedCurBufferPtr;
1155 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1156 const uint8_t *Buffer, size_t Size,
1157 unsigned Alignment) {
1158 uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1159 memcpy(IndGV, Buffer, Size);
1163 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1164 // in the constant pool that was last emitted with the 'emitConstantPool'
1167 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1168 assert(ConstantNum < ConstantPool->getConstants().size() &&
1169 "Invalid ConstantPoolIndex!");
1170 return ConstPoolAddresses[ConstantNum];
1173 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1174 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1176 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1177 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1178 assert(Index < JT.size() && "Invalid jump table index!");
1180 unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
1182 unsigned Offset = 0;
1183 for (unsigned i = 0; i < Index; ++i)
1184 Offset += JT[i].MBBs.size();
1186 Offset *= EntrySize;
1188 return (uintptr_t)((char *)JumpTableBase + Offset);
1191 void JITEmitter::EmittedFunctionConfig::onDelete(
1192 JITEmitter *Emitter, const Function *F) {
1193 Emitter->deallocateMemForFunction(F);
1195 void JITEmitter::EmittedFunctionConfig::onRAUW(
1196 JITEmitter *, const Function*, const Function*) {
1197 llvm_unreachable("The JIT doesn't know how to handle a"
1198 " RAUW on a value it has emitted.");
1202 //===----------------------------------------------------------------------===//
1203 // Public interface to this file
1204 //===----------------------------------------------------------------------===//
1206 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1207 TargetMachine &tm) {
1208 return new JITEmitter(jit, JMM, tm);
1211 // getPointerToFunctionOrStub - If the specified function has been
1212 // code-gen'd, return a pointer to the function. If not, compile it, or use
1213 // a stub to implement lazy compilation if available.
1215 void *JIT::getPointerToFunctionOrStub(Function *F) {
1216 // If we have already code generated the function, just return the address.
1217 if (void *Addr = getPointerToGlobalIfAvailable(F))
1220 // Get a stub if the target supports it.
1221 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1222 return JE->getJITResolver().getLazyFunctionStub(F);
1225 void JIT::updateFunctionStubUnlocked(Function *F) {
1226 // Get the empty stub we generated earlier.
1227 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1228 void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1229 void *Addr = getPointerToGlobalIfAvailable(F);
1230 assert(Addr != Stub && "Function must have non-stub address to be updated.");
1232 // Tell the target jit info to rewrite the stub at the specified address,
1233 // rather than creating a new one.
1234 TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1235 JE->startGVStub(Stub, layout.Size);
1236 getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1240 /// freeMachineCodeForFunction - release machine code memory for given Function.
1242 void JIT::freeMachineCodeForFunction(Function *F) {
1243 // Delete translation for this from the ExecutionEngine, so it will get
1244 // retranslated next time it is used.
1245 updateGlobalMapping(F, nullptr);
1247 // Free the actual memory for the function body and related stuff.
1248 static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);