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 "JITDebugRegisterer.h"
18 #include "JITDwarfEmitter.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Module.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Analysis/DebugInfo.h"
24 #include "llvm/CodeGen/JITCodeEmitter.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineCodeInfo.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRelocation.h"
31 #include "llvm/ExecutionEngine/GenericValue.h"
32 #include "llvm/ExecutionEngine/JITEventListener.h"
33 #include "llvm/ExecutionEngine/JITMemoryManager.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetJITInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MutexGuard.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Support/Disassembler.h"
46 #include "llvm/Support/Memory.h"
47 #include "llvm/ADT/DenseMap.h"
48 #include "llvm/ADT/SmallPtrSet.h"
49 #include "llvm/ADT/SmallVector.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/ValueMap.h"
58 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
59 STATISTIC(NumRelos, "Number of relocations applied");
60 STATISTIC(NumRetries, "Number of retries with more memory");
63 // A declaration may stop being a declaration once it's fully read from bitcode.
64 // This function returns true if F is fully read and is still a declaration.
65 static bool isNonGhostDeclaration(const Function *F) {
66 return F->isDeclaration() && !F->isMaterializable();
69 //===----------------------------------------------------------------------===//
70 // JIT lazy compilation code.
74 class JITResolverState;
76 template<typename ValueTy>
77 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
78 typedef JITResolverState *ExtraData;
79 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
80 assert(false && "The JIT doesn't know how to handle a"
81 " RAUW on a value it has emitted.");
85 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
86 typedef JITResolverState *ExtraData;
87 static void onDelete(JITResolverState *JRS, Function *F);
90 class JITResolverState {
92 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
93 FunctionToLazyStubMapTy;
94 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
95 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
96 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
97 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
99 /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
100 /// particular function so that we can reuse them if necessary.
101 FunctionToLazyStubMapTy FunctionToLazyStubMap;
103 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
104 /// site corresponds to, and vice versa.
105 CallSiteToFunctionMapTy CallSiteToFunctionMap;
106 FunctionToCallSitesMapTy FunctionToCallSitesMap;
108 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
109 /// particular GlobalVariable so that we can reuse them if necessary.
110 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
112 /// Instance of the JIT this ResolverState serves.
116 JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
117 FunctionToCallSitesMap(this),
120 FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
121 const MutexGuard& locked) {
122 assert(locked.holds(TheJIT->lock));
123 return FunctionToLazyStubMap;
126 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& lck) {
127 assert(lck.holds(TheJIT->lock));
128 return GlobalToIndirectSymMap;
131 std::pair<void *, Function *> LookupFunctionFromCallSite(
132 const MutexGuard &locked, void *CallSite) const {
133 assert(locked.holds(TheJIT->lock));
135 // The address given to us for the stub may not be exactly right, it
136 // might be a little bit after the stub. As such, use upper_bound to
138 CallSiteToFunctionMapTy::const_iterator I =
139 CallSiteToFunctionMap.upper_bound(CallSite);
140 assert(I != CallSiteToFunctionMap.begin() &&
141 "This is not a known call site!");
146 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
147 assert(locked.holds(TheJIT->lock));
149 bool Inserted = CallSiteToFunctionMap.insert(
150 std::make_pair(CallSite, F)).second;
152 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
153 FunctionToCallSitesMap[F].insert(CallSite);
156 void EraseAllCallSitesForPrelocked(Function *F);
158 // Erases _all_ call sites regardless of their function. This is used to
159 // unregister the stub addresses from the StubToResolverMap in
161 void EraseAllCallSitesPrelocked();
164 /// JITResolver - Keep track of, and resolve, call sites for functions that
165 /// have not yet been compiled.
167 typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
168 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
169 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
171 /// LazyResolverFn - The target lazy resolver function that we actually
172 /// rewrite instructions to use.
173 TargetJITInfo::LazyResolverFn LazyResolverFn;
175 JITResolverState state;
177 /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
178 /// for external functions. TODO: Of course, external functions don't need
179 /// a lazy stub. It's actually here to make it more likely that far calls
180 /// succeed, but no single stub can guarantee that. I'll remove this in a
181 /// subsequent checkin when I actually fix far calls.
182 std::map<void*, void*> ExternalFnToStubMap;
184 /// revGOTMap - map addresses to indexes in the GOT
185 std::map<void*, unsigned> revGOTMap;
186 unsigned nextGOTIndex;
190 /// Instance of JIT corresponding to this Resolver.
194 explicit JITResolver(JIT &jit, JITEmitter &je)
195 : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
196 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
201 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
202 /// lazy-compilation stub if it has already been created.
203 void *getLazyFunctionStubIfAvailable(Function *F);
205 /// getLazyFunctionStub - This returns a pointer to a function's
206 /// lazy-compilation stub, creating one on demand as needed.
207 void *getLazyFunctionStub(Function *F);
209 /// getExternalFunctionStub - Return a stub for the function at the
210 /// specified address, created lazily on demand.
211 void *getExternalFunctionStub(void *FnAddr);
213 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
214 /// specified GV address.
215 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
217 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
218 /// an address. This function only manages slots, it does not manage the
219 /// contents of the slots or the memory associated with the GOT.
220 unsigned getGOTIndexForAddr(void *addr);
222 /// JITCompilerFn - This function is called to resolve a stub to a compiled
223 /// address. If the LLVM Function corresponding to the stub has not yet
224 /// been compiled, this function compiles it first.
225 static void *JITCompilerFn(void *Stub);
228 class StubToResolverMapTy {
229 /// Map a stub address to a specific instance of a JITResolver so that
230 /// lazily-compiled functions can find the right resolver to use.
233 std::map<void*, JITResolver*> Map;
235 /// Guards Map from concurrent accesses.
236 mutable sys::Mutex Lock;
239 /// Registers a Stub to be resolved by Resolver.
240 void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
241 MutexGuard guard(Lock);
242 Map.insert(std::make_pair(Stub, Resolver));
244 /// Unregisters the Stub when it's invalidated.
245 void UnregisterStubResolver(void *Stub) {
246 MutexGuard guard(Lock);
249 /// Returns the JITResolver instance that owns the Stub.
250 JITResolver *getResolverFromStub(void *Stub) const {
251 MutexGuard guard(Lock);
252 // The address given to us for the stub may not be exactly right, it might
253 // be a little bit after the stub. As such, use upper_bound to find it.
254 // This is the same trick as in LookupFunctionFromCallSite from
256 std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
257 assert(I != Map.begin() && "This is not a known stub!");
261 /// True if any stubs refer to the given resolver. Only used in an assert().
263 bool ResolverHasStubs(JITResolver* Resolver) const {
264 MutexGuard guard(Lock);
265 for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
266 E = Map.end(); I != E; ++I) {
267 if (I->second == Resolver)
273 /// This needs to be static so that a lazy call stub can access it with no
274 /// context except the address of the stub.
275 ManagedStatic<StubToResolverMapTy> StubToResolverMap;
277 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
278 /// used to output functions to memory for execution.
279 class JITEmitter : public JITCodeEmitter {
280 JITMemoryManager *MemMgr;
282 // When outputting a function stub in the context of some other function, we
283 // save BufferBegin/BufferEnd/CurBufferPtr here.
284 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
286 // When reattempting to JIT a function after running out of space, we store
287 // the estimated size of the function we're trying to JIT here, so we can
288 // ask the memory manager for at least this much space. When we
289 // successfully emit the function, we reset this back to zero.
290 uintptr_t SizeEstimate;
292 /// Relocations - These are the relocations that the function needs, as
294 std::vector<MachineRelocation> Relocations;
296 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
297 /// It is filled in by the StartMachineBasicBlock callback and queried by
298 /// the getMachineBasicBlockAddress callback.
299 std::vector<uintptr_t> MBBLocations;
301 /// ConstantPool - The constant pool for the current function.
303 MachineConstantPool *ConstantPool;
305 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
307 void *ConstantPoolBase;
309 /// ConstPoolAddresses - Addresses of individual constant pool entries.
311 SmallVector<uintptr_t, 8> ConstPoolAddresses;
313 /// JumpTable - The jump tables for the current function.
315 MachineJumpTableInfo *JumpTable;
317 /// JumpTableBase - A pointer to the first entry in the jump table.
321 /// Resolver - This contains info about the currently resolved functions.
322 JITResolver Resolver;
324 /// DE - The dwarf emitter for the jit.
325 OwningPtr<JITDwarfEmitter> DE;
327 /// DR - The debug registerer for the jit.
328 OwningPtr<JITDebugRegisterer> DR;
330 /// LabelLocations - This vector is a mapping from Label ID's to their
332 DenseMap<MCSymbol*, uintptr_t> LabelLocations;
334 /// MMI - Machine module info for exception informations
335 MachineModuleInfo* MMI;
337 // CurFn - The llvm function being emitted. Only valid during
339 const Function *CurFn;
341 /// Information about emitted code, which is passed to the
342 /// JITEventListeners. This is reset in startFunction and used in
344 JITEvent_EmittedFunctionDetails EmissionDetails;
347 void *FunctionBody; // Beginning of the function's allocation.
348 void *Code; // The address the function's code actually starts at.
349 void *ExceptionTable;
350 EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
352 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
353 typedef JITEmitter *ExtraData;
354 static void onDelete(JITEmitter *, const Function*);
355 static void onRAUW(JITEmitter *, const Function*, const Function*);
357 ValueMap<const Function *, EmittedCode,
358 EmittedFunctionConfig> EmittedFunctions;
362 /// Instance of the JIT
366 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
367 : SizeEstimate(0), Resolver(jit, *this), MMI(0), CurFn(0),
368 EmittedFunctions(this), TheJIT(&jit) {
369 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
370 if (jit.getJITInfo().needsGOT()) {
371 MemMgr->AllocateGOT();
372 DEBUG(dbgs() << "JIT is managing a GOT\n");
375 if (JITExceptionHandling || JITEmitDebugInfo) {
376 DE.reset(new JITDwarfEmitter(jit));
378 if (JITEmitDebugInfo) {
379 DR.reset(new JITDebugRegisterer(TM));
386 /// classof - Methods for support type inquiry through isa, cast, and
389 static inline bool classof(const MachineCodeEmitter*) { return true; }
391 JITResolver &getJITResolver() { return Resolver; }
393 virtual void startFunction(MachineFunction &F);
394 virtual bool finishFunction(MachineFunction &F);
396 void emitConstantPool(MachineConstantPool *MCP);
397 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
398 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
400 void startGVStub(const GlobalValue* GV,
401 unsigned StubSize, unsigned Alignment = 1);
402 void startGVStub(void *Buffer, unsigned StubSize);
404 virtual void *allocIndirectGV(const GlobalValue *GV,
405 const uint8_t *Buffer, size_t Size,
408 /// allocateSpace - Reserves space in the current block if any, or
409 /// allocate a new one of the given size.
410 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
412 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
413 /// this method does not allocate memory in the current output buffer,
414 /// because a global may live longer than the current function.
415 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
417 virtual void addRelocation(const MachineRelocation &MR) {
418 Relocations.push_back(MR);
421 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
422 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
423 MBBLocations.resize((MBB->getNumber()+1)*2);
424 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
425 if (MBB->hasAddressTaken())
426 TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
427 (void*)getCurrentPCValue());
428 DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
429 << (void*) getCurrentPCValue() << "]\n");
432 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
433 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
435 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const{
436 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
437 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
438 return MBBLocations[MBB->getNumber()];
441 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
442 /// given function. Increase the minimum allocation size so that we get
443 /// more memory next time.
444 void retryWithMoreMemory(MachineFunction &F);
446 /// deallocateMemForFunction - Deallocate all memory for the specified
448 void deallocateMemForFunction(const Function *F);
450 virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
452 virtual void emitLabel(MCSymbol *Label) {
453 LabelLocations[Label] = getCurrentPCValue();
456 virtual DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() {
457 return &LabelLocations;
460 virtual uintptr_t getLabelAddress(MCSymbol *Label) const {
461 assert(LabelLocations.count(Label) && "Label not emitted!");
462 return LabelLocations.find(Label)->second;
465 virtual void setModuleInfo(MachineModuleInfo* Info) {
467 if (DE.get()) DE->setModuleInfo(Info);
471 void *getPointerToGlobal(GlobalValue *GV, void *Reference,
472 bool MayNeedFarStub);
473 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
477 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
478 JRS->EraseAllCallSitesForPrelocked(F);
481 void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
482 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
483 if (F2C == FunctionToCallSitesMap.end())
485 StubToResolverMapTy &S2RMap = *StubToResolverMap;
486 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
487 E = F2C->second.end(); I != E; ++I) {
488 S2RMap.UnregisterStubResolver(*I);
489 bool Erased = CallSiteToFunctionMap.erase(*I);
491 assert(Erased && "Missing call site->function mapping");
493 FunctionToCallSitesMap.erase(F2C);
496 void JITResolverState::EraseAllCallSitesPrelocked() {
497 StubToResolverMapTy &S2RMap = *StubToResolverMap;
498 for (CallSiteToFunctionMapTy::const_iterator
499 I = CallSiteToFunctionMap.begin(),
500 E = CallSiteToFunctionMap.end(); I != E; ++I) {
501 S2RMap.UnregisterStubResolver(I->first);
503 CallSiteToFunctionMap.clear();
504 FunctionToCallSitesMap.clear();
507 JITResolver::~JITResolver() {
508 // No need to lock because we're in the destructor, and state isn't shared.
509 state.EraseAllCallSitesPrelocked();
510 assert(!StubToResolverMap->ResolverHasStubs(this) &&
511 "Resolver destroyed with stubs still alive.");
514 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
515 /// if it has already been created.
516 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
517 MutexGuard locked(TheJIT->lock);
519 // If we already have a stub for this function, recycle it.
520 return state.getFunctionToLazyStubMap(locked).lookup(F);
523 /// getFunctionStub - This returns a pointer to a function stub, creating
524 /// one on demand as needed.
525 void *JITResolver::getLazyFunctionStub(Function *F) {
526 MutexGuard locked(TheJIT->lock);
528 // If we already have a lazy stub for this function, recycle it.
529 void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
530 if (Stub) return Stub;
532 // Call the lazy resolver function if we are JIT'ing lazily. Otherwise we
533 // must resolve the symbol now.
534 void *Actual = TheJIT->isCompilingLazily()
535 ? (void *)(intptr_t)LazyResolverFn : (void *)0;
537 // If this is an external declaration, attempt to resolve the address now
538 // to place in the stub.
539 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
540 Actual = TheJIT->getPointerToFunction(F);
542 // If we resolved the symbol to a null address (eg. a weak external)
543 // don't emit a stub. Return a null pointer to the application.
544 if (!Actual) return 0;
547 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
548 JE.startGVStub(F, SL.Size, SL.Alignment);
549 // Codegen a new stub, calling the lazy resolver or the actual address of the
550 // external function, if it was resolved.
551 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
554 if (Actual != (void*)(intptr_t)LazyResolverFn) {
555 // If we are getting the stub for an external function, we really want the
556 // address of the stub in the GlobalAddressMap for the JIT, not the address
557 // of the external function.
558 TheJIT->updateGlobalMapping(F, Stub);
561 DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
562 << F->getName() << "'\n");
564 if (TheJIT->isCompilingLazily()) {
565 // Register this JITResolver as the one corresponding to this call site so
566 // JITCompilerFn will be able to find it.
567 StubToResolverMap->RegisterStubResolver(Stub, this);
569 // Finally, keep track of the stub-to-Function mapping so that the
570 // JITCompilerFn knows which function to compile!
571 state.AddCallSite(locked, Stub, F);
572 } else if (!Actual) {
573 // If we are JIT'ing non-lazily but need to call a function that does not
574 // exist yet, add it to the JIT's work list so that we can fill in the
575 // stub address later.
576 assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
577 "'Actual' should have been set above.");
578 TheJIT->addPendingFunction(F);
584 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
586 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
587 MutexGuard locked(TheJIT->lock);
589 // If we already have a stub for this global variable, recycle it.
590 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
591 if (IndirectSym) return IndirectSym;
593 // Otherwise, codegen a new indirect symbol.
594 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
597 DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
598 << "] for GV '" << GV->getName() << "'\n");
603 /// getExternalFunctionStub - Return a stub for the function at the
604 /// specified address, created lazily on demand.
605 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
606 // If we already have a stub for this function, recycle it.
607 void *&Stub = ExternalFnToStubMap[FnAddr];
608 if (Stub) return Stub;
610 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
611 JE.startGVStub(0, SL.Size, SL.Alignment);
612 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr, JE);
615 DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
616 << "] for external function at '" << FnAddr << "'\n");
620 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
621 unsigned idx = revGOTMap[addr];
623 idx = ++nextGOTIndex;
624 revGOTMap[addr] = idx;
625 DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
631 /// JITCompilerFn - This function is called when a lazy compilation stub has
632 /// been entered. It looks up which function this stub corresponds to, compiles
633 /// it if necessary, then returns the resultant function pointer.
634 void *JITResolver::JITCompilerFn(void *Stub) {
635 JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
636 assert(JR && "Unable to find the corresponding JITResolver to the call site");
642 // Only lock for getting the Function. The call getPointerToFunction made
643 // in this function might trigger function materializing, which requires
644 // JIT lock to be unlocked.
645 MutexGuard locked(JR->TheJIT->lock);
647 // The address given to us for the stub may not be exactly right, it might
648 // be a little bit after the stub. As such, use upper_bound to find it.
649 std::pair<void*, Function*> I =
650 JR->state.LookupFunctionFromCallSite(locked, Stub);
655 // If we have already code generated the function, just return the address.
656 void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
659 // Otherwise we don't have it, do lazy compilation now.
661 // If lazy compilation is disabled, emit a useful error message and abort.
662 if (!JR->TheJIT->isCompilingLazily()) {
663 report_fatal_error("LLVM JIT requested to do lazy compilation of"
665 + F->getName() + "' when lazy compiles are disabled!");
668 DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
669 << "' In stub ptr = " << Stub << " actual ptr = "
670 << ActualPtr << "\n");
673 Result = JR->TheJIT->getPointerToFunction(F);
676 // Reacquire the lock to update the GOT map.
677 MutexGuard locked(JR->TheJIT->lock);
679 // We might like to remove the call site from the CallSiteToFunction map, but
680 // we can't do that! Multiple threads could be stuck, waiting to acquire the
681 // lock above. As soon as the 1st function finishes compiling the function,
682 // the next one will be released, and needs to be able to find the function it
685 // FIXME: We could rewrite all references to this stub if we knew them.
687 // What we will do is set the compiled function address to map to the
688 // same GOT entry as the stub so that later clients may update the GOT
689 // if they see it still using the stub address.
690 // Note: this is done so the Resolver doesn't have to manage GOT memory
691 // Do this without allocating map space if the target isn't using a GOT
692 if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
693 JR->revGOTMap[Result] = JR->revGOTMap[Stub];
698 //===----------------------------------------------------------------------===//
701 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
702 bool MayNeedFarStub) {
703 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
704 return TheJIT->getOrEmitGlobalVariable(GV);
706 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
707 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
709 // If we have already compiled the function, return a pointer to its body.
710 Function *F = cast<Function>(V);
712 void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
714 // Return the function stub if it's already created. We do this first so
715 // that we're returning the same address for the function as any previous
716 // call. TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
717 // close enough to call.
721 // If we know the target can handle arbitrary-distance calls, try to
722 // return a direct pointer.
723 if (!MayNeedFarStub) {
724 // If we have code, go ahead and return that.
725 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
726 if (ResultPtr) return ResultPtr;
728 // If this is an external function pointer, we can force the JIT to
729 // 'compile' it, which really just adds it to the map.
730 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
731 return TheJIT->getPointerToFunction(F);
734 // Otherwise, we may need a to emit a stub, and, conservatively, we always do
735 // so. Note that it's possible to return null from getLazyFunctionStub in the
736 // case of a weak extern that fails to resolve.
737 return Resolver.getLazyFunctionStub(F);
740 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
741 // Make sure GV is emitted first, and create a stub containing the fully
743 void *GVAddress = getPointerToGlobal(V, Reference, false);
744 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
748 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
749 if (DL.isUnknown()) return;
750 if (!BeforePrintingInsn) return;
752 const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
754 if (DL.getScope(Context) != 0 && PrevDL != DL) {
755 JITEvent_EmittedFunctionDetails::LineStart NextLine;
756 NextLine.Address = getCurrentPCValue();
758 EmissionDetails.LineStarts.push_back(NextLine);
764 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
765 const TargetData *TD) {
766 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
767 if (Constants.empty()) return 0;
770 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
771 MachineConstantPoolEntry CPE = Constants[i];
772 unsigned AlignMask = CPE.getAlignment() - 1;
773 Size = (Size + AlignMask) & ~AlignMask;
774 Type *Ty = CPE.getType();
775 Size += TD->getTypeAllocSize(Ty);
780 void JITEmitter::startFunction(MachineFunction &F) {
781 DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
782 << F.getFunction()->getName() << "\n");
784 uintptr_t ActualSize = 0;
785 // Set the memory writable, if it's not already
786 MemMgr->setMemoryWritable();
788 if (SizeEstimate > 0) {
789 // SizeEstimate will be non-zero on reallocation attempts.
790 ActualSize = SizeEstimate;
793 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
795 BufferEnd = BufferBegin+ActualSize;
796 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
798 // Ensure the constant pool/jump table info is at least 4-byte aligned.
801 emitConstantPool(F.getConstantPool());
802 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
803 initJumpTableInfo(MJTI);
805 // About to start emitting the machine code for the function.
806 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
807 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
808 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
810 MBBLocations.clear();
812 EmissionDetails.MF = &F;
813 EmissionDetails.LineStarts.clear();
816 bool JITEmitter::finishFunction(MachineFunction &F) {
817 if (CurBufferPtr == BufferEnd) {
818 // We must call endFunctionBody before retrying, because
819 // deallocateMemForFunction requires it.
820 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
821 retryWithMoreMemory(F);
825 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
826 emitJumpTableInfo(MJTI);
828 // FnStart is the start of the text, not the start of the constant pool and
829 // other per-function data.
831 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
833 // FnEnd is the end of the function's machine code.
834 uint8_t *FnEnd = CurBufferPtr;
836 if (!Relocations.empty()) {
837 CurFn = F.getFunction();
838 NumRelos += Relocations.size();
840 // Resolve the relocations to concrete pointers.
841 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
842 MachineRelocation &MR = Relocations[i];
844 if (!MR.letTargetResolve()) {
845 if (MR.isExternalSymbol()) {
846 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
848 DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
849 << ResultPtr << "]\n");
851 // If the target REALLY wants a stub for this function, emit it now.
852 if (MR.mayNeedFarStub()) {
853 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
855 } else if (MR.isGlobalValue()) {
856 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
857 BufferBegin+MR.getMachineCodeOffset(),
858 MR.mayNeedFarStub());
859 } else if (MR.isIndirectSymbol()) {
860 ResultPtr = getPointerToGVIndirectSym(
861 MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
862 } else if (MR.isBasicBlock()) {
863 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
864 } else if (MR.isConstantPoolIndex()) {
866 (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
868 assert(MR.isJumpTableIndex());
869 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
872 MR.setResultPointer(ResultPtr);
875 // if we are managing the GOT and the relocation wants an index,
877 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
878 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
880 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
881 DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
882 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
884 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
890 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
891 Relocations.size(), MemMgr->getGOTBase());
894 // Update the GOT entry for F to point to the new code.
895 if (MemMgr->isManagingGOT()) {
896 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
897 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
898 DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
899 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
901 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
905 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
906 // global variables that were referenced in the relocations.
907 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
909 if (CurBufferPtr == BufferEnd) {
910 retryWithMoreMemory(F);
913 // Now that we've succeeded in emitting the function, reset the
914 // SizeEstimate back down to zero.
918 BufferBegin = CurBufferPtr = 0;
919 NumBytes += FnEnd-FnStart;
921 // Invalidate the icache if necessary.
922 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
924 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
927 // Reset the previous debug location.
930 DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
931 << "] Function: " << F.getFunction()->getName()
932 << ": " << (FnEnd-FnStart) << " bytes of text, "
933 << Relocations.size() << " relocations\n");
936 ConstPoolAddresses.clear();
938 // Mark code region readable and executable if it's not so already.
939 MemMgr->setMemoryExecutable();
942 if (sys::hasDisassembler()) {
943 dbgs() << "JIT: Disassembled code:\n";
944 dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
947 dbgs() << "JIT: Binary code:\n";
948 uint8_t* q = FnStart;
949 for (int i = 0; q < FnEnd; q += 4, ++i) {
953 dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
955 for (int j = 3; j >= 0; --j) {
959 dbgs() << (unsigned short)q[j];
971 if (JITExceptionHandling || JITEmitDebugInfo) {
972 uintptr_t ActualSize = 0;
973 SavedBufferBegin = BufferBegin;
974 SavedBufferEnd = BufferEnd;
975 SavedCurBufferPtr = CurBufferPtr;
977 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
979 BufferEnd = BufferBegin+ActualSize;
980 EmittedFunctions[F.getFunction()].ExceptionTable = BufferBegin;
982 uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
984 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
986 uint8_t *EhEnd = CurBufferPtr;
987 BufferBegin = SavedBufferBegin;
988 BufferEnd = SavedBufferEnd;
989 CurBufferPtr = SavedCurBufferPtr;
991 if (JITExceptionHandling) {
992 TheJIT->RegisterTable(F.getFunction(), FrameRegister);
995 if (JITEmitDebugInfo) {
1001 DR->RegisterFunction(F.getFunction(), I);
1011 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
1012 DEBUG(dbgs() << "JIT: Ran out of space for native code. Reattempting.\n");
1013 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1014 ConstPoolAddresses.clear();
1016 deallocateMemForFunction(F.getFunction());
1017 // Try again with at least twice as much free space.
1018 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1020 for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
1021 if (MBB->hasAddressTaken())
1022 TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
1026 /// deallocateMemForFunction - Deallocate all memory for the specified
1027 /// function body. Also drop any references the function has to stubs.
1028 /// May be called while the Function is being destroyed inside ~Value().
1029 void JITEmitter::deallocateMemForFunction(const Function *F) {
1030 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
1031 Emitted = EmittedFunctions.find(F);
1032 if (Emitted != EmittedFunctions.end()) {
1033 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
1034 MemMgr->deallocateExceptionTable(Emitted->second.ExceptionTable);
1035 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
1037 EmittedFunctions.erase(Emitted);
1040 if(JITExceptionHandling) {
1041 TheJIT->DeregisterTable(F);
1044 if (JITEmitDebugInfo) {
1045 DR->UnregisterFunction(F);
1050 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1052 return JITCodeEmitter::allocateSpace(Size, Alignment);
1054 // create a new memory block if there is no active one.
1055 // care must be taken so that BufferBegin is invalidated when a
1057 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1058 BufferEnd = BufferBegin+Size;
1059 return CurBufferPtr;
1062 void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1063 // Delegate this call through the memory manager.
1064 return MemMgr->allocateGlobal(Size, Alignment);
1067 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1068 if (TheJIT->getJITInfo().hasCustomConstantPool())
1071 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1072 if (Constants.empty()) return;
1074 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1075 unsigned Align = MCP->getConstantPoolAlignment();
1076 ConstantPoolBase = allocateSpace(Size, Align);
1079 if (ConstantPoolBase == 0) return; // Buffer overflow.
1081 DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1082 << "] (size: " << Size << ", alignment: " << Align << ")\n");
1084 // Initialize the memory for all of the constant pool entries.
1085 unsigned Offset = 0;
1086 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1087 MachineConstantPoolEntry CPE = Constants[i];
1088 unsigned AlignMask = CPE.getAlignment() - 1;
1089 Offset = (Offset + AlignMask) & ~AlignMask;
1091 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1092 ConstPoolAddresses.push_back(CAddr);
1093 if (CPE.isMachineConstantPoolEntry()) {
1094 // FIXME: add support to lower machine constant pool values into bytes!
1095 report_fatal_error("Initialize memory with machine specific constant pool"
1096 "entry has not been implemented!");
1098 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1099 DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
1100 dbgs().write_hex(CAddr) << "]\n");
1102 Type *Ty = CPE.Val.ConstVal->getType();
1103 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
1107 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1108 if (TheJIT->getJITInfo().hasCustomJumpTables())
1110 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1113 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1114 if (JT.empty()) return;
1116 unsigned NumEntries = 0;
1117 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1118 NumEntries += JT[i].MBBs.size();
1120 unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getTargetData());
1122 // Just allocate space for all the jump tables now. We will fix up the actual
1123 // MBB entries in the tables after we emit the code for each block, since then
1124 // we will know the final locations of the MBBs in memory.
1126 JumpTableBase = allocateSpace(NumEntries * EntrySize,
1127 MJTI->getEntryAlignment(*TheJIT->getTargetData()));
1130 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1131 if (TheJIT->getJITInfo().hasCustomJumpTables())
1134 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1135 if (JT.empty() || JumpTableBase == 0) return;
1138 switch (MJTI->getEntryKind()) {
1139 case MachineJumpTableInfo::EK_Inline:
1141 case MachineJumpTableInfo::EK_BlockAddress: {
1142 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1144 assert(MJTI->getEntrySize(*TheJIT->getTargetData()) == sizeof(void*) &&
1147 // For each jump table, map each target in the jump table to the address of
1148 // an emitted MachineBasicBlock.
1149 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1151 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1152 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1153 // Store the address of the basic block for this jump table slot in the
1154 // memory we allocated for the jump table in 'initJumpTableInfo'
1155 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1156 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1161 case MachineJumpTableInfo::EK_Custom32:
1162 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1163 case MachineJumpTableInfo::EK_LabelDifference32: {
1164 assert(MJTI->getEntrySize(*TheJIT->getTargetData()) == 4&&"Cross JIT'ing?");
1165 // For each jump table, place the offset from the beginning of the table
1166 // to the target address.
1167 int *SlotPtr = (int*)JumpTableBase;
1169 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1170 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1171 // Store the offset of the basic block for this jump table slot in the
1172 // memory we allocated for the jump table in 'initJumpTableInfo'
1173 uintptr_t Base = (uintptr_t)SlotPtr;
1174 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1175 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1176 /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
1177 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1185 void JITEmitter::startGVStub(const GlobalValue* GV,
1186 unsigned StubSize, unsigned Alignment) {
1187 SavedBufferBegin = BufferBegin;
1188 SavedBufferEnd = BufferEnd;
1189 SavedCurBufferPtr = CurBufferPtr;
1191 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1192 BufferEnd = BufferBegin+StubSize+1;
1195 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1196 SavedBufferBegin = BufferBegin;
1197 SavedBufferEnd = BufferEnd;
1198 SavedCurBufferPtr = CurBufferPtr;
1200 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1201 BufferEnd = BufferBegin+StubSize+1;
1204 void JITEmitter::finishGVStub() {
1205 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1206 NumBytes += getCurrentPCOffset();
1207 BufferBegin = SavedBufferBegin;
1208 BufferEnd = SavedBufferEnd;
1209 CurBufferPtr = SavedCurBufferPtr;
1212 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1213 const uint8_t *Buffer, size_t Size,
1214 unsigned Alignment) {
1215 uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1216 memcpy(IndGV, Buffer, Size);
1220 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1221 // in the constant pool that was last emitted with the 'emitConstantPool'
1224 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1225 assert(ConstantNum < ConstantPool->getConstants().size() &&
1226 "Invalid ConstantPoolIndex!");
1227 return ConstPoolAddresses[ConstantNum];
1230 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1231 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1233 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1234 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1235 assert(Index < JT.size() && "Invalid jump table index!");
1237 unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getTargetData());
1239 unsigned Offset = 0;
1240 for (unsigned i = 0; i < Index; ++i)
1241 Offset += JT[i].MBBs.size();
1243 Offset *= EntrySize;
1245 return (uintptr_t)((char *)JumpTableBase + Offset);
1248 void JITEmitter::EmittedFunctionConfig::onDelete(
1249 JITEmitter *Emitter, const Function *F) {
1250 Emitter->deallocateMemForFunction(F);
1252 void JITEmitter::EmittedFunctionConfig::onRAUW(
1253 JITEmitter *, const Function*, const Function*) {
1254 llvm_unreachable("The JIT doesn't know how to handle a"
1255 " RAUW on a value it has emitted.");
1259 //===----------------------------------------------------------------------===//
1260 // Public interface to this file
1261 //===----------------------------------------------------------------------===//
1263 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1264 TargetMachine &tm) {
1265 return new JITEmitter(jit, JMM, tm);
1268 // getPointerToFunctionOrStub - If the specified function has been
1269 // code-gen'd, return a pointer to the function. If not, compile it, or use
1270 // a stub to implement lazy compilation if available.
1272 void *JIT::getPointerToFunctionOrStub(Function *F) {
1273 // If we have already code generated the function, just return the address.
1274 if (void *Addr = getPointerToGlobalIfAvailable(F))
1277 // Get a stub if the target supports it.
1278 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1279 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1280 return JE->getJITResolver().getLazyFunctionStub(F);
1283 void JIT::updateFunctionStub(Function *F) {
1284 // Get the empty stub we generated earlier.
1285 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1286 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1287 void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1288 void *Addr = getPointerToGlobalIfAvailable(F);
1289 assert(Addr != Stub && "Function must have non-stub address to be updated.");
1291 // Tell the target jit info to rewrite the stub at the specified address,
1292 // rather than creating a new one.
1293 TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1294 JE->startGVStub(Stub, layout.Size);
1295 getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1299 /// freeMachineCodeForFunction - release machine code memory for given Function.
1301 void JIT::freeMachineCodeForFunction(Function *F) {
1302 // Delete translation for this from the ExecutionEngine, so it will get
1303 // retranslated next time it is used.
1304 updateGlobalMapping(F, 0);
1306 // Free the actual memory for the function body and related stuff.
1307 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1308 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);