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/CodeGen/JITCodeEmitter.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRelocation.h"
29 #include "llvm/ExecutionEngine/GenericValue.h"
30 #include "llvm/ExecutionEngine/JITEventListener.h"
31 #include "llvm/ExecutionEngine/JITMemoryManager.h"
32 #include "llvm/CodeGen/MachineCodeInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetJITInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MutexGuard.h"
40 #include "llvm/Support/ValueHandle.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/System/Disassembler.h"
43 #include "llvm/System/Memory.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/Statistic.h"
55 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
56 STATISTIC(NumRelos, "Number of relocations applied");
57 STATISTIC(NumRetries, "Number of retries with more memory");
58 static JIT *TheJIT = 0;
61 //===----------------------------------------------------------------------===//
62 // JIT lazy compilation code.
65 class JITResolverState {
67 typedef DenseMap<AssertingVH<Function>, void*> FunctionToStubMapTy;
68 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
69 typedef DenseMap<AssertingVH<Function>, SmallPtrSet<void*, 1> >
70 FunctionToCallSitesMapTy;
71 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
73 /// FunctionToStubMap - Keep track of the stub created for a particular
74 /// function so that we can reuse them if necessary.
75 FunctionToStubMapTy FunctionToStubMap;
77 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
78 /// site corresponds to, and vice versa.
79 CallSiteToFunctionMapTy CallSiteToFunctionMap;
80 FunctionToCallSitesMapTy FunctionToCallSitesMap;
82 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
83 /// particular GlobalVariable so that we can reuse them if necessary.
84 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
87 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
88 assert(locked.holds(TheJIT->lock));
89 return FunctionToStubMap;
92 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
93 assert(locked.holds(TheJIT->lock));
94 return GlobalToIndirectSymMap;
97 pair<void *, Function *> LookupFunctionFromCallSite(
98 const MutexGuard &locked, void *CallSite) const {
99 assert(locked.holds(TheJIT->lock));
101 // The address given to us for the stub may not be exactly right, it might be
102 // a little bit after the stub. As such, use upper_bound to find it.
103 CallSiteToFunctionMapTy::const_iterator I =
104 CallSiteToFunctionMap.upper_bound(CallSite);
105 assert(I != CallSiteToFunctionMap.begin() &&
106 "This is not a known call site!");
111 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
112 assert(locked.holds(TheJIT->lock));
114 assert(CallSiteToFunctionMap.insert(std::make_pair(CallSite, F)).second &&
115 "Pair was already in CallSiteToFunctionMap");
116 FunctionToCallSitesMap[F].insert(CallSite);
119 // Returns the Function of the stub if a stub was erased, or NULL if there
120 // was no stub. This function uses the call-site->function map to find a
121 // relevant function, but asserts that only stubs and not other call sites
122 // will be passed in.
123 Function *EraseStub(const MutexGuard &locked, void *Stub) {
124 CallSiteToFunctionMapTy::iterator C2F_I =
125 CallSiteToFunctionMap.find(Stub);
126 if (C2F_I == CallSiteToFunctionMap.end()) {
131 Function *const F = C2F_I->second;
133 void *RealStub = FunctionToStubMap.lookup(F);
134 assert(RealStub == Stub &&
135 "Call-site that wasn't a stub pass in to EraseStub");
137 FunctionToStubMap.erase(F);
138 CallSiteToFunctionMap.erase(C2F_I);
140 // Remove the stub from the function->call-sites map, and remove the whole
141 // entry from the map if that was the last call site.
142 FunctionToCallSitesMapTy::iterator F2C_I = FunctionToCallSitesMap.find(F);
143 assert(F2C_I != FunctionToCallSitesMap.end() &&
144 "FunctionToCallSitesMap broken");
145 assert(F2C_I->second.erase(Stub) &&
146 "FunctionToCallSitesMap broken");
147 if (F2C_I->second.empty())
148 FunctionToCallSitesMap.erase(F2C_I);
153 void EraseAllCallSites(const MutexGuard &locked, Function *F) {
154 assert(locked.holds(TheJIT->lock));
155 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
156 if (F2C == FunctionToCallSitesMap.end())
158 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
159 E = F2C->second.end(); I != E; ++I) {
160 assert(CallSiteToFunctionMap.erase(*I) == 1 &&
161 "Missing call site->function mapping");
163 FunctionToCallSitesMap.erase(F2C);
167 /// JITResolver - Keep track of, and resolve, call sites for functions that
168 /// have not yet been compiled.
170 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
171 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
172 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
174 /// LazyResolverFn - The target lazy resolver function that we actually
175 /// rewrite instructions to use.
176 TargetJITInfo::LazyResolverFn LazyResolverFn;
178 JITResolverState state;
180 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
181 /// external functions.
182 std::map<void*, void*> ExternalFnToStubMap;
184 /// revGOTMap - map addresses to indexes in the GOT
185 std::map<void*, unsigned> revGOTMap;
186 unsigned nextGOTIndex;
188 static JITResolver *TheJITResolver;
190 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
193 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
194 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
195 TheJITResolver = this;
202 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
203 /// if it has already been created.
204 void *getFunctionStubIfAvailable(Function *F);
206 /// getFunctionStub - This returns a pointer to a function stub, creating
207 /// one on demand as needed. If empty is true, create a function stub
208 /// pointing at address 0, to be filled in later.
209 void *getFunctionStub(Function *F);
211 /// getExternalFunctionStub - Return a stub for the function at the
212 /// specified address, created lazily on demand.
213 void *getExternalFunctionStub(void *FnAddr);
215 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
216 /// specified GV address.
217 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
219 /// AddCallbackAtLocation - If the target is capable of rewriting an
220 /// instruction without the use of a stub, record the location of the use so
221 /// we know which function is being used at the location.
222 void *AddCallbackAtLocation(Function *F, void *Location) {
223 MutexGuard locked(TheJIT->lock);
224 /// Get the target-specific JIT resolver function.
225 state.AddCallSite(locked, Location, F);
226 return (void*)(intptr_t)LazyResolverFn;
229 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
230 SmallVectorImpl<void*> &Ptrs);
232 GlobalValue *invalidateStub(void *Stub);
234 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
235 /// an address. This function only manages slots, it does not manage the
236 /// contents of the slots or the memory associated with the GOT.
237 unsigned getGOTIndexForAddr(void *addr);
239 /// JITCompilerFn - This function is called to resolve a stub to a compiled
240 /// address. If the LLVM Function corresponding to the stub has not yet
241 /// been compiled, this function compiles it first.
242 static void *JITCompilerFn(void *Stub);
246 JITResolver *JITResolver::TheJITResolver = 0;
248 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
249 /// if it has already been created.
250 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
251 MutexGuard locked(TheJIT->lock);
253 // If we already have a stub for this function, recycle it.
254 return state.getFunctionToStubMap(locked).lookup(F);
257 /// getFunctionStub - This returns a pointer to a function stub, creating
258 /// one on demand as needed.
259 void *JITResolver::getFunctionStub(Function *F) {
260 MutexGuard locked(TheJIT->lock);
262 // If we already have a stub for this function, recycle it.
263 void *&Stub = state.getFunctionToStubMap(locked)[F];
264 if (Stub) return Stub;
266 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
267 // case we must resolve the symbol now.
268 void *Actual = TheJIT->isLazyCompilationDisabled()
269 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
271 // If this is an external declaration, attempt to resolve the address now
272 // to place in the stub.
273 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
274 Actual = TheJIT->getPointerToFunction(F);
276 // If we resolved the symbol to a null address (eg. a weak external)
277 // don't emit a stub. Return a null pointer to the application. If dlsym
278 // stubs are enabled, not being able to resolve the address is not
280 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
283 // Codegen a new stub, calling the lazy resolver or the actual address of the
284 // external function, if it was resolved.
285 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
286 *TheJIT->getCodeEmitter());
288 if (Actual != (void*)(intptr_t)LazyResolverFn) {
289 // If we are getting the stub for an external function, we really want the
290 // address of the stub in the GlobalAddressMap for the JIT, not the address
291 // of the external function.
292 TheJIT->updateGlobalMapping(F, Stub);
295 DEBUG(errs() << "JIT: Stub emitted at [" << Stub << "] for function '"
296 << F->getName() << "'\n");
298 // Finally, keep track of the stub-to-Function mapping so that the
299 // JITCompilerFn knows which function to compile!
300 state.AddCallSite(locked, Stub, F);
302 // If we are JIT'ing non-lazily but need to call a function that does not
303 // exist yet, add it to the JIT's work list so that we can fill in the stub
305 if (!Actual && TheJIT->isLazyCompilationDisabled())
306 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
307 TheJIT->addPendingFunction(F);
312 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
314 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
315 MutexGuard locked(TheJIT->lock);
317 // If we already have a stub for this global variable, recycle it.
318 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
319 if (IndirectSym) return IndirectSym;
321 // Otherwise, codegen a new indirect symbol.
322 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
323 *TheJIT->getCodeEmitter());
325 DEBUG(errs() << "JIT: Indirect symbol emitted at [" << IndirectSym
326 << "] for GV '" << GV->getName() << "'\n");
331 /// getExternalFunctionStub - Return a stub for the function at the
332 /// specified address, created lazily on demand.
333 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
334 // If we already have a stub for this function, recycle it.
335 void *&Stub = ExternalFnToStubMap[FnAddr];
336 if (Stub) return Stub;
338 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
339 *TheJIT->getCodeEmitter());
341 DEBUG(errs() << "JIT: Stub emitted at [" << Stub
342 << "] for external function at '" << FnAddr << "'\n");
346 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
347 unsigned idx = revGOTMap[addr];
349 idx = ++nextGOTIndex;
350 revGOTMap[addr] = idx;
351 DEBUG(errs() << "JIT: Adding GOT entry " << idx << " for addr ["
357 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
358 SmallVectorImpl<void*> &Ptrs) {
359 MutexGuard locked(TheJIT->lock);
361 const FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
362 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
364 for (FunctionToStubMapTy::const_iterator i = FM.begin(), e = FM.end();
366 Function *F = i->first;
367 if (F->isDeclaration() && F->hasExternalLinkage()) {
368 GVs.push_back(i->first);
369 Ptrs.push_back(i->second);
372 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
374 GVs.push_back(i->first);
375 Ptrs.push_back(i->second);
379 GlobalValue *JITResolver::invalidateStub(void *Stub) {
380 MutexGuard locked(TheJIT->lock);
382 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
384 // Look up the cheap way first, to see if it's a function stub we are
385 // invalidating. If so, remove it from both the forward and reverse maps.
386 if (Function *F = state.EraseStub(locked, Stub)) {
390 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
391 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
393 if (i->second != Stub)
395 GlobalValue *GV = i->first;
400 // Lastly, check to see if it's in the ExternalFnToStubMap.
401 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
402 e = ExternalFnToStubMap.end(); i != e; ++i) {
403 if (i->second != Stub)
405 ExternalFnToStubMap.erase(i);
412 /// JITCompilerFn - This function is called when a lazy compilation stub has
413 /// been entered. It looks up which function this stub corresponds to, compiles
414 /// it if necessary, then returns the resultant function pointer.
415 void *JITResolver::JITCompilerFn(void *Stub) {
416 JITResolver &JR = *TheJITResolver;
422 // Only lock for getting the Function. The call getPointerToFunction made
423 // in this function might trigger function materializing, which requires
424 // JIT lock to be unlocked.
425 MutexGuard locked(TheJIT->lock);
427 // The address given to us for the stub may not be exactly right, it might
428 // be a little bit after the stub. As such, use upper_bound to find it.
429 pair<void*, Function*> I =
430 JR.state.LookupFunctionFromCallSite(locked, Stub);
435 // If we have already code generated the function, just return the address.
436 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
439 // Otherwise we don't have it, do lazy compilation now.
441 // If lazy compilation is disabled, emit a useful error message and abort.
442 if (TheJIT->isLazyCompilationDisabled()) {
443 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
444 + F->getName() + "' when lazy compiles are disabled!");
447 DEBUG(errs() << "JIT: Lazily resolving function '" << F->getName()
448 << "' In stub ptr = " << Stub << " actual ptr = "
449 << ActualPtr << "\n");
451 Result = TheJIT->getPointerToFunction(F);
454 // Reacquire the lock to update the GOT map.
455 MutexGuard locked(TheJIT->lock);
457 // We might like to remove the call site from the CallSiteToFunction map, but
458 // we can't do that! Multiple threads could be stuck, waiting to acquire the
459 // lock above. As soon as the 1st function finishes compiling the function,
460 // the next one will be released, and needs to be able to find the function it
463 // FIXME: We could rewrite all references to this stub if we knew them.
465 // What we will do is set the compiled function address to map to the
466 // same GOT entry as the stub so that later clients may update the GOT
467 // if they see it still using the stub address.
468 // Note: this is done so the Resolver doesn't have to manage GOT memory
469 // Do this without allocating map space if the target isn't using a GOT
470 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
471 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
476 //===----------------------------------------------------------------------===//
480 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
481 /// used to output functions to memory for execution.
482 class JITEmitter : public JITCodeEmitter {
483 JITMemoryManager *MemMgr;
485 // When outputting a function stub in the context of some other function, we
486 // save BufferBegin/BufferEnd/CurBufferPtr here.
487 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
489 // When reattempting to JIT a function after running out of space, we store
490 // the estimated size of the function we're trying to JIT here, so we can
491 // ask the memory manager for at least this much space. When we
492 // successfully emit the function, we reset this back to zero.
493 uintptr_t SizeEstimate;
495 /// Relocations - These are the relocations that the function needs, as
497 std::vector<MachineRelocation> Relocations;
499 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
500 /// It is filled in by the StartMachineBasicBlock callback and queried by
501 /// the getMachineBasicBlockAddress callback.
502 std::vector<uintptr_t> MBBLocations;
504 /// ConstantPool - The constant pool for the current function.
506 MachineConstantPool *ConstantPool;
508 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
510 void *ConstantPoolBase;
512 /// ConstPoolAddresses - Addresses of individual constant pool entries.
514 SmallVector<uintptr_t, 8> ConstPoolAddresses;
516 /// JumpTable - The jump tables for the current function.
518 MachineJumpTableInfo *JumpTable;
520 /// JumpTableBase - A pointer to the first entry in the jump table.
524 /// Resolver - This contains info about the currently resolved functions.
525 JITResolver Resolver;
527 /// DE - The dwarf emitter for the jit.
528 OwningPtr<JITDwarfEmitter> DE;
530 /// DR - The debug registerer for the jit.
531 OwningPtr<JITDebugRegisterer> DR;
533 /// LabelLocations - This vector is a mapping from Label ID's to their
535 std::vector<uintptr_t> LabelLocations;
537 /// MMI - Machine module info for exception informations
538 MachineModuleInfo* MMI;
540 // GVSet - a set to keep track of which globals have been seen
541 SmallPtrSet<const GlobalVariable*, 8> GVSet;
543 // CurFn - The llvm function being emitted. Only valid during
545 const Function *CurFn;
547 /// Information about emitted code, which is passed to the
548 /// JITEventListeners. This is reset in startFunction and used in
550 JITEvent_EmittedFunctionDetails EmissionDetails;
554 void *ExceptionTable;
555 EmittedCode() : FunctionBody(0), ExceptionTable(0) {}
557 DenseMap<const Function *, EmittedCode> EmittedFunctions;
559 // CurFnStubUses - For a given Function, a vector of stubs that it
560 // references. This facilitates the JIT detecting that a stub is no
561 // longer used, so that it may be deallocated.
562 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
564 // StubFnRefs - For a given pointer to a stub, a set of Functions which
565 // reference the stub. When the count of a stub's references drops to zero,
566 // the stub is unused.
567 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
569 // ExtFnStubs - A map of external function names to stubs which have entries
570 // in the JITResolver's ExternalFnToStubMap.
571 StringMap<void *> ExtFnStubs;
573 DebugLocTuple PrevDLT;
576 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
577 : SizeEstimate(0), Resolver(jit), MMI(0), CurFn(0) {
578 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
579 if (jit.getJITInfo().needsGOT()) {
580 MemMgr->AllocateGOT();
581 DEBUG(errs() << "JIT is managing a GOT\n");
584 if (DwarfExceptionHandling || JITEmitDebugInfo) {
585 DE.reset(new JITDwarfEmitter(jit));
587 if (JITEmitDebugInfo) {
588 DR.reset(new JITDebugRegisterer(TM));
595 /// classof - Methods for support type inquiry through isa, cast, and
598 static inline bool classof(const JITEmitter*) { return true; }
599 static inline bool classof(const MachineCodeEmitter*) { return true; }
601 JITResolver &getJITResolver() { return Resolver; }
603 virtual void startFunction(MachineFunction &F);
604 virtual bool finishFunction(MachineFunction &F);
606 void emitConstantPool(MachineConstantPool *MCP);
607 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
608 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
610 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
611 unsigned Alignment = 1);
612 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
614 virtual void* finishGVStub(const GlobalValue *GV);
616 /// allocateSpace - Reserves space in the current block if any, or
617 /// allocate a new one of the given size.
618 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
620 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
621 /// this method does not allocate memory in the current output buffer,
622 /// because a global may live longer than the current function.
623 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
625 virtual void addRelocation(const MachineRelocation &MR) {
626 Relocations.push_back(MR);
629 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
630 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
631 MBBLocations.resize((MBB->getNumber()+1)*2);
632 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
633 DEBUG(errs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
634 << (void*) getCurrentPCValue() << "]\n");
637 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
638 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
640 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
641 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
642 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
643 return MBBLocations[MBB->getNumber()];
646 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
647 /// given function. Increase the minimum allocation size so that we get
648 /// more memory next time.
649 void retryWithMoreMemory(MachineFunction &F);
651 /// deallocateMemForFunction - Deallocate all memory for the specified
653 void deallocateMemForFunction(const Function *F);
655 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
656 /// using the stub at the specified address. Allows
657 /// deallocateMemForFunction to also remove stubs no longer referenced.
658 void AddStubToCurrentFunction(void *Stub);
660 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
661 /// MachineRelocations that reference external functions by name.
662 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
664 virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
666 virtual void emitLabel(uint64_t LabelID) {
667 if (LabelLocations.size() <= LabelID)
668 LabelLocations.resize((LabelID+1)*2);
669 LabelLocations[LabelID] = getCurrentPCValue();
672 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
673 assert(LabelLocations.size() > (unsigned)LabelID &&
674 LabelLocations[LabelID] && "Label not emitted!");
675 return LabelLocations[LabelID];
678 virtual void setModuleInfo(MachineModuleInfo* Info) {
680 if (DE.get()) DE->setModuleInfo(Info);
683 void setMemoryExecutable() {
684 MemMgr->setMemoryExecutable();
687 JITMemoryManager *getMemMgr() const { return MemMgr; }
690 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
691 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
693 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
694 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
695 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
696 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
700 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
701 bool DoesntNeedStub) {
702 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
703 return TheJIT->getOrEmitGlobalVariable(GV);
705 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
706 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
708 // If we have already compiled the function, return a pointer to its body.
709 Function *F = cast<Function>(V);
711 if (!DoesntNeedStub) {
712 // Return the function stub if it's already created.
713 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
715 AddStubToCurrentFunction(ResultPtr);
717 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
719 if (ResultPtr) return ResultPtr;
721 // If this is an external function pointer, we can force the JIT to
722 // 'compile' it, which really just adds it to the map. In dlsym mode,
723 // external functions are forced through a stub, regardless of reloc type.
724 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
725 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
726 return TheJIT->getPointerToFunction(F);
728 // Okay, the function has not been compiled yet, if the target callback
729 // mechanism is capable of rewriting the instruction directly, prefer to do
730 // that instead of emitting a stub. This uses the lazy resolver, so is not
731 // legal if lazy compilation is disabled.
732 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
733 return Resolver.AddCallbackAtLocation(F, Reference);
735 // Otherwise, we have to emit a stub.
736 void *StubAddr = Resolver.getFunctionStub(F);
738 // Add the stub to the current function's list of referenced stubs, so we can
739 // deallocate them if the current function is ever freed. It's possible to
740 // return null from getFunctionStub in the case of a weak extern that fails
743 AddStubToCurrentFunction(StubAddr);
748 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
750 // Make sure GV is emitted first, and create a stub containing the fully
752 void *GVAddress = getPointerToGlobal(V, Reference, true);
753 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
755 // Add the stub to the current function's list of referenced stubs, so we can
756 // deallocate them if the current function is ever freed.
757 AddStubToCurrentFunction(StubAddr);
762 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
763 assert(CurFn && "Stub added to current function, but current function is 0!");
765 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
766 StubsUsed.push_back(StubAddr);
768 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
769 FnRefs.insert(CurFn);
772 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
773 if (!DL.isUnknown()) {
774 DebugLocTuple CurDLT = EmissionDetails.MF->getDebugLocTuple(DL);
776 if (BeforePrintingInsn) {
777 if (CurDLT.Scope != 0 && PrevDLT != CurDLT) {
778 JITEvent_EmittedFunctionDetails::LineStart NextLine;
779 NextLine.Address = getCurrentPCValue();
781 EmissionDetails.LineStarts.push_back(NextLine);
789 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
790 const TargetData *TD) {
791 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
792 if (Constants.empty()) return 0;
795 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
796 MachineConstantPoolEntry CPE = Constants[i];
797 unsigned AlignMask = CPE.getAlignment() - 1;
798 Size = (Size + AlignMask) & ~AlignMask;
799 const Type *Ty = CPE.getType();
800 Size += TD->getTypeAllocSize(Ty);
805 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
806 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
807 if (JT.empty()) return 0;
809 unsigned NumEntries = 0;
810 for (unsigned i = 0, e = JT.size(); i != e; ++i)
811 NumEntries += JT[i].MBBs.size();
813 unsigned EntrySize = MJTI->getEntrySize();
815 return NumEntries * EntrySize;
818 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
819 if (Alignment == 0) Alignment = 1;
820 // Since we do not know where the buffer will be allocated, be pessimistic.
821 return Size + Alignment;
824 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
825 /// into the running total Size.
827 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
828 const Type *ElTy = GV->getType()->getElementType();
829 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
831 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
832 DEBUG(errs() << "JIT: Adding in size " << GVSize << " alignment " << GVAlign);
834 // Assume code section ends with worst possible alignment, so first
835 // variable needs maximal padding.
838 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
843 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
844 /// but are referenced from the constant; put them in GVSet and add their
845 /// size into the running total Size.
847 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
849 // If its undefined, return the garbage.
850 if (isa<UndefValue>(C))
853 // If the value is a ConstantExpr
854 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
855 Constant *Op0 = CE->getOperand(0);
856 switch (CE->getOpcode()) {
857 case Instruction::GetElementPtr:
858 case Instruction::Trunc:
859 case Instruction::ZExt:
860 case Instruction::SExt:
861 case Instruction::FPTrunc:
862 case Instruction::FPExt:
863 case Instruction::UIToFP:
864 case Instruction::SIToFP:
865 case Instruction::FPToUI:
866 case Instruction::FPToSI:
867 case Instruction::PtrToInt:
868 case Instruction::IntToPtr:
869 case Instruction::BitCast: {
870 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
873 case Instruction::Add:
874 case Instruction::FAdd:
875 case Instruction::Sub:
876 case Instruction::FSub:
877 case Instruction::Mul:
878 case Instruction::FMul:
879 case Instruction::UDiv:
880 case Instruction::SDiv:
881 case Instruction::URem:
882 case Instruction::SRem:
883 case Instruction::And:
884 case Instruction::Or:
885 case Instruction::Xor: {
886 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
887 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
892 raw_string_ostream Msg(msg);
893 Msg << "ConstantExpr not handled: " << *CE;
894 llvm_report_error(Msg.str());
899 if (C->getType()->getTypeID() == Type::PointerTyID)
900 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
901 if (GVSet.insert(GV))
902 Size = addSizeOfGlobal(GV, Size);
907 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
908 /// but are referenced from the given initializer.
910 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
912 if (!isa<UndefValue>(Init) &&
913 !isa<ConstantVector>(Init) &&
914 !isa<ConstantAggregateZero>(Init) &&
915 !isa<ConstantArray>(Init) &&
916 !isa<ConstantStruct>(Init) &&
917 Init->getType()->isFirstClassType())
918 Size = addSizeOfGlobalsInConstantVal(Init, Size);
922 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
923 /// globals; then walk the initializers of those globals looking for more.
924 /// If their size has not been considered yet, add it into the running total
927 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
931 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
933 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
935 const TargetInstrDesc &Desc = I->getDesc();
936 const MachineInstr &MI = *I;
937 unsigned NumOps = Desc.getNumOperands();
938 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
939 const MachineOperand &MO = MI.getOperand(CurOp);
941 GlobalValue* V = MO.getGlobal();
942 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
945 // If seen in previous function, it will have an entry here.
946 if (TheJIT->getPointerToGlobalIfAvailable(GV))
948 // If seen earlier in this function, it will have an entry here.
949 // FIXME: it should be possible to combine these tables, by
950 // assuming the addresses of the new globals in this module
951 // start at 0 (or something) and adjusting them after codegen
952 // complete. Another possibility is to grab a marker bit in GV.
953 if (GVSet.insert(GV))
954 // A variable as yet unseen. Add in its size.
955 Size = addSizeOfGlobal(GV, Size);
960 DEBUG(errs() << "JIT: About to look through initializers\n");
961 // Look for more globals that are referenced only from initializers.
962 // GVSet.end is computed each time because the set can grow as we go.
963 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
964 I != GVSet.end(); I++) {
965 const GlobalVariable* GV = *I;
966 if (GV->hasInitializer())
967 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
973 void JITEmitter::startFunction(MachineFunction &F) {
974 DEBUG(errs() << "JIT: Starting CodeGen of Function "
975 << F.getFunction()->getName() << "\n");
977 uintptr_t ActualSize = 0;
978 // Set the memory writable, if it's not already
979 MemMgr->setMemoryWritable();
980 if (MemMgr->NeedsExactSize()) {
981 DEBUG(errs() << "JIT: ExactSize\n");
982 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
983 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
984 MachineConstantPool *MCP = F.getConstantPool();
986 // Ensure the constant pool/jump table info is at least 4-byte aligned.
987 ActualSize = RoundUpToAlign(ActualSize, 16);
989 // Add the alignment of the constant pool
990 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
992 // Add the constant pool size
993 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
995 // Add the aligment of the jump table info
996 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
998 // Add the jump table size
999 ActualSize += GetJumpTableSizeInBytes(MJTI);
1001 // Add the alignment for the function
1002 ActualSize = RoundUpToAlign(ActualSize,
1003 std::max(F.getFunction()->getAlignment(), 8U));
1005 // Add the function size
1006 ActualSize += TII->GetFunctionSizeInBytes(F);
1008 DEBUG(errs() << "JIT: ActualSize before globals " << ActualSize << "\n");
1009 // Add the size of the globals that will be allocated after this function.
1010 // These are all the ones referenced from this function that were not
1011 // previously allocated.
1012 ActualSize += GetSizeOfGlobalsInBytes(F);
1013 DEBUG(errs() << "JIT: ActualSize after globals " << ActualSize << "\n");
1014 } else if (SizeEstimate > 0) {
1015 // SizeEstimate will be non-zero on reallocation attempts.
1016 ActualSize = SizeEstimate;
1019 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1021 BufferEnd = BufferBegin+ActualSize;
1022 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
1024 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1027 emitConstantPool(F.getConstantPool());
1028 initJumpTableInfo(F.getJumpTableInfo());
1030 // About to start emitting the machine code for the function.
1031 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
1032 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
1034 MBBLocations.clear();
1036 EmissionDetails.MF = &F;
1037 EmissionDetails.LineStarts.clear();
1040 bool JITEmitter::finishFunction(MachineFunction &F) {
1041 if (CurBufferPtr == BufferEnd) {
1042 // We must call endFunctionBody before retrying, because
1043 // deallocateMemForFunction requires it.
1044 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1045 retryWithMoreMemory(F);
1049 emitJumpTableInfo(F.getJumpTableInfo());
1051 // FnStart is the start of the text, not the start of the constant pool and
1052 // other per-function data.
1054 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
1056 // FnEnd is the end of the function's machine code.
1057 uint8_t *FnEnd = CurBufferPtr;
1059 if (!Relocations.empty()) {
1060 CurFn = F.getFunction();
1061 NumRelos += Relocations.size();
1063 // Resolve the relocations to concrete pointers.
1064 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1065 MachineRelocation &MR = Relocations[i];
1066 void *ResultPtr = 0;
1067 if (!MR.letTargetResolve()) {
1068 if (MR.isExternalSymbol()) {
1069 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1071 DEBUG(errs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1072 << ResultPtr << "]\n");
1074 // If the target REALLY wants a stub for this function, emit it now.
1075 if (!MR.doesntNeedStub()) {
1076 if (!TheJIT->areDlsymStubsEnabled()) {
1077 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1079 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1081 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1082 AddStubToCurrentFunction(Stub);
1087 } else if (MR.isGlobalValue()) {
1088 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1089 BufferBegin+MR.getMachineCodeOffset(),
1090 MR.doesntNeedStub());
1091 } else if (MR.isIndirectSymbol()) {
1092 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
1093 BufferBegin+MR.getMachineCodeOffset(),
1094 MR.doesntNeedStub());
1095 } else if (MR.isBasicBlock()) {
1096 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1097 } else if (MR.isConstantPoolIndex()) {
1098 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1100 assert(MR.isJumpTableIndex());
1101 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1104 MR.setResultPointer(ResultPtr);
1107 // if we are managing the GOT and the relocation wants an index,
1109 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1110 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1111 MR.setGOTIndex(idx);
1112 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1113 DEBUG(errs() << "JIT: GOT was out of date for " << ResultPtr
1114 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1116 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1122 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1123 Relocations.size(), MemMgr->getGOTBase());
1126 // Update the GOT entry for F to point to the new code.
1127 if (MemMgr->isManagingGOT()) {
1128 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1129 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1130 DEBUG(errs() << "JIT: GOT was out of date for " << (void*)BufferBegin
1131 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1133 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1137 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1138 // global variables that were referenced in the relocations.
1139 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1141 if (CurBufferPtr == BufferEnd) {
1142 retryWithMoreMemory(F);
1145 // Now that we've succeeded in emitting the function, reset the
1146 // SizeEstimate back down to zero.
1150 BufferBegin = CurBufferPtr = 0;
1151 NumBytes += FnEnd-FnStart;
1153 // Invalidate the icache if necessary.
1154 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1156 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
1159 DEBUG(errs() << "JIT: Finished CodeGen of [" << (void*)FnStart
1160 << "] Function: " << F.getFunction()->getName()
1161 << ": " << (FnEnd-FnStart) << " bytes of text, "
1162 << Relocations.size() << " relocations\n");
1164 Relocations.clear();
1165 ConstPoolAddresses.clear();
1167 // Mark code region readable and executable if it's not so already.
1168 MemMgr->setMemoryExecutable();
1171 if (sys::hasDisassembler()) {
1172 errs() << "JIT: Disassembled code:\n";
1173 errs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
1174 (uintptr_t)FnStart);
1176 errs() << "JIT: Binary code:\n";
1177 uint8_t* q = FnStart;
1178 for (int i = 0; q < FnEnd; q += 4, ++i) {
1182 errs() << "JIT: " << (long)(q - FnStart) << ": ";
1184 for (int j = 3; j >= 0; --j) {
1188 errs() << (unsigned short)q[j];
1200 if (DwarfExceptionHandling || JITEmitDebugInfo) {
1201 uintptr_t ActualSize = 0;
1202 SavedBufferBegin = BufferBegin;
1203 SavedBufferEnd = BufferEnd;
1204 SavedCurBufferPtr = CurBufferPtr;
1206 if (MemMgr->NeedsExactSize()) {
1207 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1210 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1212 BufferEnd = BufferBegin+ActualSize;
1213 EmittedFunctions[F.getFunction()].ExceptionTable = BufferBegin;
1215 uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
1217 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1219 uint8_t *EhEnd = CurBufferPtr;
1220 BufferBegin = SavedBufferBegin;
1221 BufferEnd = SavedBufferEnd;
1222 CurBufferPtr = SavedCurBufferPtr;
1224 if (DwarfExceptionHandling) {
1225 TheJIT->RegisterTable(FrameRegister);
1228 if (JITEmitDebugInfo) {
1230 I.FnStart = FnStart;
1232 I.EhStart = EhStart;
1234 DR->RegisterFunction(F.getFunction(), I);
1244 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
1245 DEBUG(errs() << "JIT: Ran out of space for native code. Reattempting.\n");
1246 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1247 ConstPoolAddresses.clear();
1249 deallocateMemForFunction(F.getFunction());
1250 // Try again with at least twice as much free space.
1251 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1254 /// deallocateMemForFunction - Deallocate all memory for the specified
1255 /// function body. Also drop any references the function has to stubs.
1256 void JITEmitter::deallocateMemForFunction(const Function *F) {
1257 DenseMap<const Function *, EmittedCode>::iterator Emitted =
1258 EmittedFunctions.find(F);
1259 if (Emitted != EmittedFunctions.end()) {
1260 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
1261 MemMgr->deallocateExceptionTable(Emitted->second.ExceptionTable);
1262 EmittedFunctions.erase(Emitted);
1265 // TODO: Do we need to unregister exception handling information from libgcc
1268 if (JITEmitDebugInfo) {
1269 DR->UnregisterFunction(F);
1272 // If the function did not reference any stubs, return.
1273 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1276 // For each referenced stub, erase the reference to this function, and then
1277 // erase the list of referenced stubs.
1278 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1279 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1280 void *Stub = StubList[i];
1282 // If we already invalidated this stub for this function, continue.
1283 if (StubFnRefs.count(Stub) == 0)
1286 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1289 // If this function was the last reference to the stub, invalidate the stub
1290 // in the JITResolver. Were there a memory manager deallocateStub routine,
1291 // we could call that at this point too.
1292 if (FnRefs.empty()) {
1293 DEBUG(errs() << "\nJIT: Invalidated Stub at [" << Stub << "]\n");
1294 StubFnRefs.erase(Stub);
1296 // Invalidate the stub. If it is a GV stub, update the JIT's global
1297 // mapping for that GV to zero, otherwise, search the string map of
1298 // external function names to stubs and remove the entry for this stub.
1299 GlobalValue *GV = Resolver.invalidateStub(Stub);
1301 TheJIT->updateGlobalMapping(GV, 0);
1303 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1304 e = ExtFnStubs.end(); i != e; ++i) {
1305 if (i->second == Stub) {
1306 ExtFnStubs.erase(i);
1313 CurFnStubUses.erase(F);
1317 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1319 return JITCodeEmitter::allocateSpace(Size, Alignment);
1321 // create a new memory block if there is no active one.
1322 // care must be taken so that BufferBegin is invalidated when a
1324 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1325 BufferEnd = BufferBegin+Size;
1326 return CurBufferPtr;
1329 void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1330 // Delegate this call through the memory manager.
1331 return MemMgr->allocateGlobal(Size, Alignment);
1334 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1335 if (TheJIT->getJITInfo().hasCustomConstantPool())
1338 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1339 if (Constants.empty()) return;
1341 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1342 unsigned Align = MCP->getConstantPoolAlignment();
1343 ConstantPoolBase = allocateSpace(Size, Align);
1346 if (ConstantPoolBase == 0) return; // Buffer overflow.
1348 DEBUG(errs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1349 << "] (size: " << Size << ", alignment: " << Align << ")\n");
1351 // Initialize the memory for all of the constant pool entries.
1352 unsigned Offset = 0;
1353 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1354 MachineConstantPoolEntry CPE = Constants[i];
1355 unsigned AlignMask = CPE.getAlignment() - 1;
1356 Offset = (Offset + AlignMask) & ~AlignMask;
1358 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1359 ConstPoolAddresses.push_back(CAddr);
1360 if (CPE.isMachineConstantPoolEntry()) {
1361 // FIXME: add support to lower machine constant pool values into bytes!
1362 llvm_report_error("Initialize memory with machine specific constant pool"
1363 "entry has not been implemented!");
1365 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1366 DEBUG(errs() << "JIT: CP" << i << " at [0x";
1367 errs().write_hex(CAddr) << "]\n");
1369 const Type *Ty = CPE.Val.ConstVal->getType();
1370 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
1374 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1375 if (TheJIT->getJITInfo().hasCustomJumpTables())
1378 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1379 if (JT.empty()) return;
1381 unsigned NumEntries = 0;
1382 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1383 NumEntries += JT[i].MBBs.size();
1385 unsigned EntrySize = MJTI->getEntrySize();
1387 // Just allocate space for all the jump tables now. We will fix up the actual
1388 // MBB entries in the tables after we emit the code for each block, since then
1389 // we will know the final locations of the MBBs in memory.
1391 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1394 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1395 if (TheJIT->getJITInfo().hasCustomJumpTables())
1398 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1399 if (JT.empty() || JumpTableBase == 0) return;
1401 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1402 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1403 // For each jump table, place the offset from the beginning of the table
1404 // to the target address.
1405 int *SlotPtr = (int*)JumpTableBase;
1407 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1408 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1409 // Store the offset of the basic block for this jump table slot in the
1410 // memory we allocated for the jump table in 'initJumpTableInfo'
1411 uintptr_t Base = (uintptr_t)SlotPtr;
1412 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1413 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1414 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1418 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1420 // For each jump table, map each target in the jump table to the address of
1421 // an emitted MachineBasicBlock.
1422 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1424 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1425 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1426 // Store the address of the basic block for this jump table slot in the
1427 // memory we allocated for the jump table in 'initJumpTableInfo'
1428 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1429 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1434 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1435 unsigned Alignment) {
1436 SavedBufferBegin = BufferBegin;
1437 SavedBufferEnd = BufferEnd;
1438 SavedCurBufferPtr = CurBufferPtr;
1440 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1441 BufferEnd = BufferBegin+StubSize+1;
1444 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1445 unsigned StubSize) {
1446 SavedBufferBegin = BufferBegin;
1447 SavedBufferEnd = BufferEnd;
1448 SavedCurBufferPtr = CurBufferPtr;
1450 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1451 BufferEnd = BufferBegin+StubSize+1;
1454 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1455 NumBytes += getCurrentPCOffset();
1456 std::swap(SavedBufferBegin, BufferBegin);
1457 BufferEnd = SavedBufferEnd;
1458 CurBufferPtr = SavedCurBufferPtr;
1459 return SavedBufferBegin;
1462 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1463 // in the constant pool that was last emitted with the 'emitConstantPool'
1466 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1467 assert(ConstantNum < ConstantPool->getConstants().size() &&
1468 "Invalid ConstantPoolIndex!");
1469 return ConstPoolAddresses[ConstantNum];
1472 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1473 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1475 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1476 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1477 assert(Index < JT.size() && "Invalid jump table index!");
1479 unsigned Offset = 0;
1480 unsigned EntrySize = JumpTable->getEntrySize();
1482 for (unsigned i = 0; i < Index; ++i)
1483 Offset += JT[i].MBBs.size();
1485 Offset *= EntrySize;
1487 return (uintptr_t)((char *)JumpTableBase + Offset);
1490 //===----------------------------------------------------------------------===//
1491 // Public interface to this file
1492 //===----------------------------------------------------------------------===//
1494 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1495 TargetMachine &tm) {
1496 return new JITEmitter(jit, JMM, tm);
1499 // getPointerToNamedFunction - This function is used as a global wrapper to
1500 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1501 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1502 // need to resolve function(s) that are being mis-codegenerated, so we need to
1503 // resolve their addresses at runtime, and this is the way to do it.
1505 void *getPointerToNamedFunction(const char *Name) {
1506 if (Function *F = TheJIT->FindFunctionNamed(Name))
1507 return TheJIT->getPointerToFunction(F);
1508 return TheJIT->getPointerToNamedFunction(Name);
1512 // getPointerToFunctionOrStub - If the specified function has been
1513 // code-gen'd, return a pointer to the function. If not, compile it, or use
1514 // a stub to implement lazy compilation if available.
1516 void *JIT::getPointerToFunctionOrStub(Function *F) {
1517 // If we have already code generated the function, just return the address.
1518 if (void *Addr = getPointerToGlobalIfAvailable(F))
1521 // Get a stub if the target supports it.
1522 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1523 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1524 return JE->getJITResolver().getFunctionStub(F);
1527 void JIT::updateFunctionStub(Function *F) {
1528 // Get the empty stub we generated earlier.
1529 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1530 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1531 void *Stub = JE->getJITResolver().getFunctionStub(F);
1533 // Tell the target jit info to rewrite the stub at the specified address,
1534 // rather than creating a new one.
1535 void *Addr = getPointerToGlobalIfAvailable(F);
1536 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1539 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1540 /// that were emitted during code generation.
1542 void JIT::updateDlsymStubTable() {
1543 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1544 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1546 SmallVector<GlobalValue*, 8> GVs;
1547 SmallVector<void*, 8> Ptrs;
1548 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
1550 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1552 unsigned nStubs = GVs.size() + ExtFns.size();
1554 // If there are no relocatable stubs, return.
1558 // If there are no new relocatable stubs, return.
1559 void *CurTable = JE->getMemMgr()->getDlsymTable();
1560 if (CurTable && (*(unsigned *)CurTable == nStubs))
1563 // Calculate the size of the stub info
1564 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
1566 SmallVector<unsigned, 8> Offsets;
1567 for (unsigned i = 0; i != GVs.size(); ++i) {
1568 Offsets.push_back(offset);
1569 offset += GVs[i]->getName().size() + 1;
1571 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1573 Offsets.push_back(offset);
1574 offset += strlen(i->first()) + 1;
1577 // Allocate space for the new "stub", which contains the dlsym table.
1578 JE->startGVStub(0, offset, 4);
1580 // Emit the number of records
1581 JE->emitInt32(nStubs);
1583 // Emit the string offsets
1584 for (unsigned i = 0; i != nStubs; ++i)
1585 JE->emitInt32(Offsets[i]);
1587 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1588 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1589 // relocation can write the relocated pointer at the appropriate place in
1591 for (unsigned i = 0; i != GVs.size(); ++i) {
1592 intptr_t Ptr = (intptr_t)Ptrs[i];
1593 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1595 if (isa<Function>(GVs[i]))
1598 if (sizeof(Ptr) == 8)
1603 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1605 intptr_t Ptr = (intptr_t)i->second | 1;
1607 if (sizeof(Ptr) == 8)
1613 // Emit the strings.
1614 for (unsigned i = 0; i != GVs.size(); ++i)
1615 JE->emitString(GVs[i]->getName());
1616 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1618 JE->emitString(i->first());
1620 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1621 // deallocate space for the old one, if one existed.
1622 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1625 /// freeMachineCodeForFunction - release machine code memory for given Function.
1627 void JIT::freeMachineCodeForFunction(Function *F) {
1629 // Delete translation for this from the ExecutionEngine, so it will get
1630 // retranslated next time it is used.
1631 void *OldPtr = updateGlobalMapping(F, 0);
1634 TheJIT->NotifyFreeingMachineCode(*F, OldPtr);
1636 // Free the actual memory for the function body and related stuff.
1637 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1638 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);