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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
17 #include "JITDwarfEmitter.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/ValueMap.h"
24 #include "llvm/CodeGen/JITCodeEmitter.h"
25 #include "llvm/CodeGen/MachineCodeInfo.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRelocation.h"
31 #include "llvm/DebugInfo.h"
32 #include "llvm/ExecutionEngine/GenericValue.h"
33 #include "llvm/ExecutionEngine/JITEventListener.h"
34 #include "llvm/ExecutionEngine/JITMemoryManager.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Disassembler.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/Memory.h"
44 #include "llvm/Support/MutexGuard.h"
45 #include "llvm/Support/ValueHandle.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetJITInfo.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetOptions.h"
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");
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.
64 static bool isNonGhostDeclaration(const Function *F) {
65 return F->isDeclaration() && !F->isMaterializable();
68 //===----------------------------------------------------------------------===//
69 // JIT lazy compilation code.
73 class JITResolverState;
75 template<typename ValueTy>
76 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
77 typedef JITResolverState *ExtraData;
78 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.");
84 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
85 typedef JITResolverState *ExtraData;
86 static void onDelete(JITResolverState *JRS, Function *F);
89 class JITResolverState {
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;
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;
102 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
103 /// site corresponds to, and vice versa.
104 CallSiteToFunctionMapTy CallSiteToFunctionMap;
105 FunctionToCallSitesMapTy FunctionToCallSitesMap;
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;
112 /// Instance of the JIT this ResolverState serves.
117 JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
118 FunctionToCallSitesMap(this) {
124 FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
125 const MutexGuard& locked) {
126 assert(locked.holds(TheJIT->lock));
127 return FunctionToLazyStubMap;
130 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& lck) {
131 assert(lck.holds(TheJIT->lock));
132 return GlobalToIndirectSymMap;
135 std::pair<void *, Function *> LookupFunctionFromCallSite(
136 const MutexGuard &locked, void *CallSite) const {
137 assert(locked.holds(TheJIT->lock));
139 // The address given to us for the stub may not be exactly right, it
140 // might be a little bit after the stub. As such, use upper_bound to
142 CallSiteToFunctionMapTy::const_iterator I =
143 CallSiteToFunctionMap.upper_bound(CallSite);
144 assert(I != CallSiteToFunctionMap.begin() &&
145 "This is not a known call site!");
150 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
151 assert(locked.holds(TheJIT->lock));
153 bool Inserted = CallSiteToFunctionMap.insert(
154 std::make_pair(CallSite, F)).second;
156 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
157 FunctionToCallSitesMap[F].insert(CallSite);
160 void EraseAllCallSitesForPrelocked(Function *F);
162 // Erases _all_ call sites regardless of their function. This is used to
163 // unregister the stub addresses from the StubToResolverMap in
165 void EraseAllCallSitesPrelocked();
168 /// JITResolver - Keep track of, and resolve, call sites for functions that
169 /// have not yet been compiled.
171 typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
172 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
173 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
175 /// LazyResolverFn - The target lazy resolver function that we actually
176 /// rewrite instructions to use.
177 TargetJITInfo::LazyResolverFn LazyResolverFn;
179 JITResolverState state;
181 /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
182 /// for external functions. TODO: Of course, external functions don't need
183 /// a lazy stub. It's actually here to make it more likely that far calls
184 /// succeed, but no single stub can guarantee that. I'll remove this in a
185 /// subsequent checkin when I actually fix far calls.
186 std::map<void*, void*> ExternalFnToStubMap;
188 /// revGOTMap - map addresses to indexes in the GOT
189 std::map<void*, unsigned> revGOTMap;
190 unsigned nextGOTIndex;
194 /// Instance of JIT corresponding to this Resolver.
198 explicit JITResolver(JIT &jit, JITEmitter &je)
199 : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
200 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
205 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
206 /// lazy-compilation stub if it has already been created.
207 void *getLazyFunctionStubIfAvailable(Function *F);
209 /// getLazyFunctionStub - This returns a pointer to a function's
210 /// lazy-compilation stub, creating one on demand as needed.
211 void *getLazyFunctionStub(Function *F);
213 /// getExternalFunctionStub - Return a stub for the function at the
214 /// specified address, created lazily on demand.
215 void *getExternalFunctionStub(void *FnAddr);
217 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
218 /// specified GV address.
219 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
221 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
222 /// an address. This function only manages slots, it does not manage the
223 /// contents of the slots or the memory associated with the GOT.
224 unsigned getGOTIndexForAddr(void *addr);
226 /// JITCompilerFn - This function is called to resolve a stub to a compiled
227 /// address. If the LLVM Function corresponding to the stub has not yet
228 /// been compiled, this function compiles it first.
229 static void *JITCompilerFn(void *Stub);
232 class StubToResolverMapTy {
233 /// Map a stub address to a specific instance of a JITResolver so that
234 /// lazily-compiled functions can find the right resolver to use.
237 std::map<void*, JITResolver*> Map;
239 /// Guards Map from concurrent accesses.
240 mutable sys::Mutex Lock;
243 /// Registers a Stub to be resolved by Resolver.
244 void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
245 MutexGuard guard(Lock);
246 Map.insert(std::make_pair(Stub, Resolver));
248 /// Unregisters the Stub when it's invalidated.
249 void UnregisterStubResolver(void *Stub) {
250 MutexGuard guard(Lock);
253 /// Returns the JITResolver instance that owns the Stub.
254 JITResolver *getResolverFromStub(void *Stub) const {
255 MutexGuard guard(Lock);
256 // The address given to us for the stub may not be exactly right, it might
257 // be a little bit after the stub. As such, use upper_bound to find it.
258 // This is the same trick as in LookupFunctionFromCallSite from
260 std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
261 assert(I != Map.begin() && "This is not a known stub!");
265 /// True if any stubs refer to the given resolver. Only used in an assert().
267 bool ResolverHasStubs(JITResolver* Resolver) const {
268 MutexGuard guard(Lock);
269 for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
270 E = Map.end(); I != E; ++I) {
271 if (I->second == Resolver)
277 /// This needs to be static so that a lazy call stub can access it with no
278 /// context except the address of the stub.
279 ManagedStatic<StubToResolverMapTy> StubToResolverMap;
281 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
282 /// used to output functions to memory for execution.
283 class JITEmitter : public JITCodeEmitter {
284 JITMemoryManager *MemMgr;
286 // When outputting a function stub in the context of some other function, we
287 // save BufferBegin/BufferEnd/CurBufferPtr here.
288 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
290 // When reattempting to JIT a function after running out of space, we store
291 // the estimated size of the function we're trying to JIT here, so we can
292 // ask the memory manager for at least this much space. When we
293 // successfully emit the function, we reset this back to zero.
294 uintptr_t SizeEstimate;
296 /// Relocations - These are the relocations that the function needs, as
298 std::vector<MachineRelocation> Relocations;
300 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
301 /// It is filled in by the StartMachineBasicBlock callback and queried by
302 /// the getMachineBasicBlockAddress callback.
303 std::vector<uintptr_t> MBBLocations;
305 /// ConstantPool - The constant pool for the current function.
307 MachineConstantPool *ConstantPool;
309 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
311 void *ConstantPoolBase;
313 /// ConstPoolAddresses - Addresses of individual constant pool entries.
315 SmallVector<uintptr_t, 8> ConstPoolAddresses;
317 /// JumpTable - The jump tables for the current function.
319 MachineJumpTableInfo *JumpTable;
321 /// JumpTableBase - A pointer to the first entry in the jump table.
325 /// Resolver - This contains info about the currently resolved functions.
326 JITResolver Resolver;
328 /// DE - The dwarf emitter for the jit.
329 OwningPtr<JITDwarfEmitter> DE;
331 /// LabelLocations - This vector is a mapping from Label ID's to their
333 DenseMap<MCSymbol*, uintptr_t> LabelLocations;
335 /// MMI - Machine module info for exception informations
336 MachineModuleInfo* MMI;
338 // CurFn - The llvm function being emitted. Only valid during
340 const Function *CurFn;
342 /// Information about emitted code, which is passed to the
343 /// JITEventListeners. This is reset in startFunction and used in
345 JITEvent_EmittedFunctionDetails EmissionDetails;
348 void *FunctionBody; // Beginning of the function's allocation.
349 void *Code; // The address the function's code actually starts at.
350 void *ExceptionTable;
351 EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
353 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
354 typedef JITEmitter *ExtraData;
355 static void onDelete(JITEmitter *, const Function*);
356 static void onRAUW(JITEmitter *, const Function*, const Function*);
358 ValueMap<const Function *, EmittedCode,
359 EmittedFunctionConfig> EmittedFunctions;
363 /// Instance of the JIT
367 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
368 : SizeEstimate(0), Resolver(jit, *this), MMI(0), CurFn(0),
369 EmittedFunctions(this), TheJIT(&jit) {
370 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
371 if (jit.getJITInfo().needsGOT()) {
372 MemMgr->AllocateGOT();
373 DEBUG(dbgs() << "JIT is managing a GOT\n");
381 JITResolver &getJITResolver() { return Resolver; }
383 virtual void startFunction(MachineFunction &F);
384 virtual bool finishFunction(MachineFunction &F);
386 void emitConstantPool(MachineConstantPool *MCP);
387 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
388 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
390 void startGVStub(const GlobalValue* GV,
391 unsigned StubSize, unsigned Alignment = 1);
392 void startGVStub(void *Buffer, unsigned StubSize);
394 virtual void *allocIndirectGV(const GlobalValue *GV,
395 const uint8_t *Buffer, size_t Size,
398 /// allocateSpace - Reserves space in the current block if any, or
399 /// allocate a new one of the given size.
400 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
402 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
403 /// this method does not allocate memory in the current output buffer,
404 /// because a global may live longer than the current function.
405 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
407 virtual void addRelocation(const MachineRelocation &MR) {
408 Relocations.push_back(MR);
411 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
412 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
413 MBBLocations.resize((MBB->getNumber()+1)*2);
414 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
415 if (MBB->hasAddressTaken())
416 TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
417 (void*)getCurrentPCValue());
418 DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
419 << (void*) getCurrentPCValue() << "]\n");
422 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
423 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
425 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const{
426 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
427 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
428 return MBBLocations[MBB->getNumber()];
431 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
432 /// given function. Increase the minimum allocation size so that we get
433 /// more memory next time.
434 void retryWithMoreMemory(MachineFunction &F);
436 /// deallocateMemForFunction - Deallocate all memory for the specified
438 void deallocateMemForFunction(const Function *F);
440 virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
442 virtual void emitLabel(MCSymbol *Label) {
443 LabelLocations[Label] = getCurrentPCValue();
446 virtual DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() {
447 return &LabelLocations;
450 virtual uintptr_t getLabelAddress(MCSymbol *Label) const {
451 assert(LabelLocations.count(Label) && "Label not emitted!");
452 return LabelLocations.find(Label)->second;
455 virtual void setModuleInfo(MachineModuleInfo* Info) {
457 if (DE.get()) DE->setModuleInfo(Info);
461 void *getPointerToGlobal(GlobalValue *GV, void *Reference,
462 bool MayNeedFarStub);
463 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
467 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
468 JRS->EraseAllCallSitesForPrelocked(F);
471 void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
472 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
473 if (F2C == FunctionToCallSitesMap.end())
475 StubToResolverMapTy &S2RMap = *StubToResolverMap;
476 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
477 E = F2C->second.end(); I != E; ++I) {
478 S2RMap.UnregisterStubResolver(*I);
479 bool Erased = CallSiteToFunctionMap.erase(*I);
481 assert(Erased && "Missing call site->function mapping");
483 FunctionToCallSitesMap.erase(F2C);
486 void JITResolverState::EraseAllCallSitesPrelocked() {
487 StubToResolverMapTy &S2RMap = *StubToResolverMap;
488 for (CallSiteToFunctionMapTy::const_iterator
489 I = CallSiteToFunctionMap.begin(),
490 E = CallSiteToFunctionMap.end(); I != E; ++I) {
491 S2RMap.UnregisterStubResolver(I->first);
493 CallSiteToFunctionMap.clear();
494 FunctionToCallSitesMap.clear();
497 JITResolver::~JITResolver() {
498 // No need to lock because we're in the destructor, and state isn't shared.
499 state.EraseAllCallSitesPrelocked();
500 assert(!StubToResolverMap->ResolverHasStubs(this) &&
501 "Resolver destroyed with stubs still alive.");
504 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
505 /// if it has already been created.
506 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
507 MutexGuard locked(TheJIT->lock);
509 // If we already have a stub for this function, recycle it.
510 return state.getFunctionToLazyStubMap(locked).lookup(F);
513 /// getFunctionStub - This returns a pointer to a function stub, creating
514 /// one on demand as needed.
515 void *JITResolver::getLazyFunctionStub(Function *F) {
516 MutexGuard locked(TheJIT->lock);
518 // If we already have a lazy stub for this function, recycle it.
519 void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
520 if (Stub) return Stub;
522 // Call the lazy resolver function if we are JIT'ing lazily. Otherwise we
523 // must resolve the symbol now.
524 void *Actual = TheJIT->isCompilingLazily()
525 ? (void *)(intptr_t)LazyResolverFn : (void *)0;
527 // If this is an external declaration, attempt to resolve the address now
528 // to place in the stub.
529 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
530 Actual = TheJIT->getPointerToFunction(F);
532 // If we resolved the symbol to a null address (eg. a weak external)
533 // don't emit a stub. Return a null pointer to the application.
534 if (!Actual) return 0;
537 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
538 JE.startGVStub(F, SL.Size, SL.Alignment);
539 // Codegen a new stub, calling the lazy resolver or the actual address of the
540 // external function, if it was resolved.
541 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
544 if (Actual != (void*)(intptr_t)LazyResolverFn) {
545 // If we are getting the stub for an external function, we really want the
546 // address of the stub in the GlobalAddressMap for the JIT, not the address
547 // of the external function.
548 TheJIT->updateGlobalMapping(F, Stub);
551 DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
552 << F->getName() << "'\n");
554 if (TheJIT->isCompilingLazily()) {
555 // Register this JITResolver as the one corresponding to this call site so
556 // JITCompilerFn will be able to find it.
557 StubToResolverMap->RegisterStubResolver(Stub, this);
559 // Finally, keep track of the stub-to-Function mapping so that the
560 // JITCompilerFn knows which function to compile!
561 state.AddCallSite(locked, Stub, F);
562 } else if (!Actual) {
563 // If we are JIT'ing non-lazily but need to call a function that does not
564 // exist yet, add it to the JIT's work list so that we can fill in the
565 // stub address later.
566 assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
567 "'Actual' should have been set above.");
568 TheJIT->addPendingFunction(F);
574 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
576 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
577 MutexGuard locked(TheJIT->lock);
579 // If we already have a stub for this global variable, recycle it.
580 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
581 if (IndirectSym) return IndirectSym;
583 // Otherwise, codegen a new indirect symbol.
584 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
587 DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
588 << "] for GV '" << GV->getName() << "'\n");
593 /// getExternalFunctionStub - Return a stub for the function at the
594 /// specified address, created lazily on demand.
595 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
596 // If we already have a stub for this function, recycle it.
597 void *&Stub = ExternalFnToStubMap[FnAddr];
598 if (Stub) return Stub;
600 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
601 JE.startGVStub(0, SL.Size, SL.Alignment);
602 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr, JE);
605 DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
606 << "] for external function at '" << FnAddr << "'\n");
610 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
611 unsigned idx = revGOTMap[addr];
613 idx = ++nextGOTIndex;
614 revGOTMap[addr] = idx;
615 DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
621 /// JITCompilerFn - This function is called when a lazy compilation stub has
622 /// been entered. It looks up which function this stub corresponds to, compiles
623 /// it if necessary, then returns the resultant function pointer.
624 void *JITResolver::JITCompilerFn(void *Stub) {
625 JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
626 assert(JR && "Unable to find the corresponding JITResolver to the call site");
632 // Only lock for getting the Function. The call getPointerToFunction made
633 // in this function might trigger function materializing, which requires
634 // JIT lock to be unlocked.
635 MutexGuard locked(JR->TheJIT->lock);
637 // The address given to us for the stub may not be exactly right, it might
638 // be a little bit after the stub. As such, use upper_bound to find it.
639 std::pair<void*, Function*> I =
640 JR->state.LookupFunctionFromCallSite(locked, Stub);
645 // If we have already code generated the function, just return the address.
646 void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
649 // Otherwise we don't have it, do lazy compilation now.
651 // If lazy compilation is disabled, emit a useful error message and abort.
652 if (!JR->TheJIT->isCompilingLazily()) {
653 report_fatal_error("LLVM JIT requested to do lazy compilation of"
655 + F->getName() + "' when lazy compiles are disabled!");
658 DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
659 << "' In stub ptr = " << Stub << " actual ptr = "
660 << ActualPtr << "\n");
663 Result = JR->TheJIT->getPointerToFunction(F);
666 // Reacquire the lock to update the GOT map.
667 MutexGuard locked(JR->TheJIT->lock);
669 // We might like to remove the call site from the CallSiteToFunction map, but
670 // we can't do that! Multiple threads could be stuck, waiting to acquire the
671 // lock above. As soon as the 1st function finishes compiling the function,
672 // the next one will be released, and needs to be able to find the function it
675 // FIXME: We could rewrite all references to this stub if we knew them.
677 // What we will do is set the compiled function address to map to the
678 // same GOT entry as the stub so that later clients may update the GOT
679 // if they see it still using the stub address.
680 // Note: this is done so the Resolver doesn't have to manage GOT memory
681 // Do this without allocating map space if the target isn't using a GOT
682 if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
683 JR->revGOTMap[Result] = JR->revGOTMap[Stub];
688 //===----------------------------------------------------------------------===//
691 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
692 bool MayNeedFarStub) {
693 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
694 return TheJIT->getOrEmitGlobalVariable(GV);
696 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
697 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
699 // If we have already compiled the function, return a pointer to its body.
700 Function *F = cast<Function>(V);
702 void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
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.
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;
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);
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);
730 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
731 // Make sure GV is emitted first, and create a stub containing the fully
733 void *GVAddress = getPointerToGlobal(V, Reference, false);
734 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
738 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
739 if (DL.isUnknown()) return;
740 if (!BeforePrintingInsn) return;
742 const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
744 if (DL.getScope(Context) != 0 && PrevDL != DL) {
745 JITEvent_EmittedFunctionDetails::LineStart NextLine;
746 NextLine.Address = getCurrentPCValue();
748 EmissionDetails.LineStarts.push_back(NextLine);
754 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
755 const DataLayout *TD) {
756 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
757 if (Constants.empty()) return 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);
770 void JITEmitter::startFunction(MachineFunction &F) {
771 DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
772 << F.getName() << "\n");
774 uintptr_t ActualSize = 0;
775 // Set the memory writable, if it's not already
776 MemMgr->setMemoryWritable();
778 if (SizeEstimate > 0) {
779 // SizeEstimate will be non-zero on reallocation attempts.
780 ActualSize = SizeEstimate;
783 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
785 BufferEnd = BufferBegin+ActualSize;
786 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
788 // Ensure the constant pool/jump table info is at least 4-byte aligned.
791 emitConstantPool(F.getConstantPool());
792 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
793 initJumpTableInfo(MJTI);
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;
800 MBBLocations.clear();
802 EmissionDetails.MF = &F;
803 EmissionDetails.LineStarts.clear();
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);
815 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
816 emitJumpTableInfo(MJTI);
818 // FnStart is the start of the text, not the start of the constant pool and
819 // other per-function data.
821 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
823 // FnEnd is the end of the function's machine code.
824 uint8_t *FnEnd = CurBufferPtr;
826 if (!Relocations.empty()) {
827 CurFn = F.getFunction();
828 NumRelos += Relocations.size();
830 // Resolve the relocations to concrete pointers.
831 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
832 MachineRelocation &MR = Relocations[i];
834 if (!MR.letTargetResolve()) {
835 if (MR.isExternalSymbol()) {
836 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
838 DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
839 << ResultPtr << "]\n");
841 // If the target REALLY wants a stub for this function, emit it now.
842 if (MR.mayNeedFarStub()) {
843 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
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()) {
856 (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
858 assert(MR.isJumpTableIndex());
859 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
862 MR.setResultPointer(ResultPtr);
865 // if we are managing the GOT and the relocation wants an index,
867 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
868 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
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]
874 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
880 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
881 Relocations.size(), MemMgr->getGOTBase());
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]
891 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
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);
899 if (CurBufferPtr == BufferEnd) {
900 retryWithMoreMemory(F);
903 // Now that we've succeeded in emitting the function, reset the
904 // SizeEstimate back down to zero.
908 BufferBegin = CurBufferPtr = 0;
909 NumBytes += FnEnd-FnStart;
911 // Invalidate the icache if necessary.
912 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
914 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
917 // Reset the previous debug location.
920 DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
921 << "] Function: " << F.getName()
922 << ": " << (FnEnd-FnStart) << " bytes of text, "
923 << Relocations.size() << " relocations\n");
926 ConstPoolAddresses.clear();
928 // Mark code region readable and executable if it's not so already.
929 MemMgr->setMemoryExecutable();
932 if (sys::hasDisassembler()) {
933 dbgs() << "JIT: Disassembled code:\n";
934 dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
937 dbgs() << "JIT: Binary code:\n";
938 uint8_t* q = FnStart;
939 for (int i = 0; q < FnEnd; q += 4, ++i) {
943 dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
945 for (int j = 3; j >= 0; --j) {
949 dbgs() << (unsigned short)q[j];
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();
972 deallocateMemForFunction(F.getFunction());
973 // Try again with at least twice as much free space.
974 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
976 for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
977 if (MBB->hasAddressTaken())
978 TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
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().
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);
992 EmittedFunctions.erase(Emitted);
997 void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
999 return JITCodeEmitter::allocateSpace(Size, Alignment);
1001 // create a new memory block if there is no active one.
1002 // care must be taken so that BufferBegin is invalidated when a
1004 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1005 BufferEnd = BufferBegin+Size;
1006 return CurBufferPtr;
1009 void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1010 // Delegate this call through the memory manager.
1011 return MemMgr->allocateGlobal(Size, Alignment);
1014 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1015 if (TheJIT->getJITInfo().hasCustomConstantPool())
1018 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1019 if (Constants.empty()) return;
1021 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
1022 unsigned Align = MCP->getConstantPoolAlignment();
1023 ConstantPoolBase = allocateSpace(Size, Align);
1026 if (ConstantPoolBase == 0) return; // Buffer overflow.
1028 DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1029 << "] (size: " << Size << ", alignment: " << Align << ")\n");
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;
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!");
1045 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1046 DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
1047 dbgs().write_hex(CAddr) << "]\n");
1049 Type *Ty = CPE.Val.ConstVal->getType();
1050 Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
1054 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1055 if (TheJIT->getJITInfo().hasCustomJumpTables())
1057 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1060 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1061 if (JT.empty()) return;
1063 unsigned NumEntries = 0;
1064 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1065 NumEntries += JT[i].MBBs.size();
1067 unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
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.
1073 JumpTableBase = allocateSpace(NumEntries * EntrySize,
1074 MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
1077 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1078 if (TheJIT->getJITInfo().hasCustomJumpTables())
1081 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1082 if (JT.empty() || JumpTableBase == 0) return;
1085 switch (MJTI->getEntryKind()) {
1086 case MachineJumpTableInfo::EK_Inline:
1088 case MachineJumpTableInfo::EK_BlockAddress: {
1089 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1091 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
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;
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]);
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;
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);
1129 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1131 "JT Info emission not implemented for GPRel64BlockAddress yet.");
1135 void JITEmitter::startGVStub(const GlobalValue* GV,
1136 unsigned StubSize, unsigned Alignment) {
1137 SavedBufferBegin = BufferBegin;
1138 SavedBufferEnd = BufferEnd;
1139 SavedCurBufferPtr = CurBufferPtr;
1141 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1142 BufferEnd = BufferBegin+StubSize+1;
1145 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1146 SavedBufferBegin = BufferBegin;
1147 SavedBufferEnd = BufferEnd;
1148 SavedCurBufferPtr = CurBufferPtr;
1150 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1151 BufferEnd = BufferBegin+StubSize+1;
1154 void JITEmitter::finishGVStub() {
1155 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1156 NumBytes += getCurrentPCOffset();
1157 BufferBegin = SavedBufferBegin;
1158 BufferEnd = SavedBufferEnd;
1159 CurBufferPtr = SavedCurBufferPtr;
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);
1170 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1171 // in the constant pool that was last emitted with the 'emitConstantPool'
1174 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1175 assert(ConstantNum < ConstantPool->getConstants().size() &&
1176 "Invalid ConstantPoolIndex!");
1177 return ConstPoolAddresses[ConstantNum];
1180 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1181 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1183 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1184 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1185 assert(Index < JT.size() && "Invalid jump table index!");
1187 unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
1189 unsigned Offset = 0;
1190 for (unsigned i = 0; i < Index; ++i)
1191 Offset += JT[i].MBBs.size();
1193 Offset *= EntrySize;
1195 return (uintptr_t)((char *)JumpTableBase + Offset);
1198 void JITEmitter::EmittedFunctionConfig::onDelete(
1199 JITEmitter *Emitter, const Function *F) {
1200 Emitter->deallocateMemForFunction(F);
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.");
1209 //===----------------------------------------------------------------------===//
1210 // Public interface to this file
1211 //===----------------------------------------------------------------------===//
1213 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1214 TargetMachine &tm) {
1215 return new JITEmitter(jit, JMM, tm);
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.
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))
1227 // Get a stub if the target supports it.
1228 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1229 return JE->getJITResolver().getLazyFunctionStub(F);
1232 void JIT::updateFunctionStub(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.");
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());
1247 /// freeMachineCodeForFunction - release machine code memory for given Function.
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, 0);
1254 // Free the actual memory for the function body and related stuff.
1255 static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);