1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "llvm/Constant.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineRelocation.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetJITInfo.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/System/Memory.h"
32 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
33 Statistic<> NumRelos("jit", "Number of relocations applied");
38 //===----------------------------------------------------------------------===//
39 // JITMemoryManager code.
42 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
43 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
44 /// sections, one for function stubs, one for the functions themselves. We
45 /// have to do this because we may need to emit a function stub while in the
46 /// middle of emitting a function, and we don't know how large the function we
47 /// are emitting is. This never bothers to release the memory, because when
48 /// we are ready to destroy the JIT, the program exits.
49 class JITMemoryManager {
50 sys::MemoryBlock MemBlock; // Virtual memory block allocated RWX
51 unsigned char *MemBase; // Base of block of memory, start of stub mem
52 unsigned char *FunctionBase; // Start of the function body area
53 unsigned char *ConstantPool; // Memory allocated for constant pools
54 unsigned char *CurStubPtr, *CurFunctionPtr, *CurConstantPtr;
59 inline unsigned char *allocateStub(unsigned StubSize);
60 inline unsigned char *allocateConstant(unsigned ConstantSize,
62 inline unsigned char *startFunctionBody();
63 inline void endFunctionBody(unsigned char *FunctionEnd);
67 JITMemoryManager::JITMemoryManager() {
68 // Allocate a 16M block of memory...
69 MemBlock = sys::Memory::AllocateRWX((16 << 20));
70 MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
71 FunctionBase = MemBase + 512*1024; // Use 512k for stubs
73 // Allocate stubs backwards from the function base, allocate functions forward
74 // from the function base.
75 CurStubPtr = CurFunctionPtr = FunctionBase;
77 ConstantPool = new unsigned char [512*1024]; // Use 512k for constant pools
78 CurConstantPtr = ConstantPool + 512*1024;
81 JITMemoryManager::~JITMemoryManager() {
82 sys::Memory::ReleaseRWX(MemBlock);
83 delete[] ConstantPool;
86 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
87 CurStubPtr -= StubSize;
88 if (CurStubPtr < MemBase) {
89 std::cerr << "JIT ran out of memory for function stubs!\n";
95 unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
97 // Reserve space and align pointer.
98 CurConstantPtr -= ConstantSize;
100 (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
102 if (CurConstantPtr < ConstantPool) {
103 std::cerr << "JIT ran out of memory for constant pools!\n";
106 return CurConstantPtr;
109 unsigned char *JITMemoryManager::startFunctionBody() {
110 // Round up to an even multiple of 8 bytes, this should eventually be target
112 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
115 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
116 assert(FunctionEnd > CurFunctionPtr);
117 CurFunctionPtr = FunctionEnd;
120 //===----------------------------------------------------------------------===//
121 // JIT lazy compilation code.
124 class JITResolverState {
126 /// FunctionToStubMap - Keep track of the stub created for a particular
127 /// function so that we can reuse them if necessary.
128 std::map<Function*, void*> FunctionToStubMap;
130 /// StubToFunctionMap - Keep track of the function that each stub
132 std::map<void*, Function*> StubToFunctionMap;
135 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
136 assert(locked.holds(TheJIT->lock));
137 return FunctionToStubMap;
140 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
141 assert(locked.holds(TheJIT->lock));
142 return StubToFunctionMap;
146 /// JITResolver - Keep track of, and resolve, call sites for functions that
147 /// have not yet been compiled.
149 /// MCE - The MachineCodeEmitter to use to emit stubs with.
150 MachineCodeEmitter &MCE;
152 /// LazyResolverFn - The target lazy resolver function that we actually
153 /// rewrite instructions to use.
154 TargetJITInfo::LazyResolverFn LazyResolverFn;
156 JITResolverState state;
158 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
159 /// external functions.
160 std::map<void*, void*> ExternalFnToStubMap;
162 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {
164 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
167 /// getFunctionStub - This returns a pointer to a function stub, creating
168 /// one on demand as needed.
169 void *getFunctionStub(Function *F);
171 /// getExternalFunctionStub - Return a stub for the function at the
172 /// specified address, created lazily on demand.
173 void *getExternalFunctionStub(void *FnAddr);
175 /// AddCallbackAtLocation - If the target is capable of rewriting an
176 /// instruction without the use of a stub, record the location of the use so
177 /// we know which function is being used at the location.
178 void *AddCallbackAtLocation(Function *F, void *Location) {
179 MutexGuard locked(TheJIT->lock);
180 /// Get the target-specific JIT resolver function.
181 state.getStubToFunctionMap(locked)[Location] = F;
182 return (void*)LazyResolverFn;
185 /// JITCompilerFn - This function is called to resolve a stub to a compiled
186 /// address. If the LLVM Function corresponding to the stub has not yet
187 /// been compiled, this function compiles it first.
188 static void *JITCompilerFn(void *Stub);
192 /// getJITResolver - This function returns the one instance of the JIT resolver.
194 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
195 static JITResolver TheJITResolver(*MCE);
196 return TheJITResolver;
199 /// getFunctionStub - This returns a pointer to a function stub, creating
200 /// one on demand as needed.
201 void *JITResolver::getFunctionStub(Function *F) {
202 MutexGuard locked(TheJIT->lock);
204 // If we already have a stub for this function, recycle it.
205 void *&Stub = state.getFunctionToStubMap(locked)[F];
206 if (Stub) return Stub;
208 // Call the lazy resolver function unless we already KNOW it is an external
209 // function, in which case we just skip the lazy resolution step.
210 void *Actual = (void*)LazyResolverFn;
211 if (F->isExternal() && F->hasExternalLinkage())
212 Actual = TheJIT->getPointerToFunction(F);
214 // Otherwise, codegen a new stub. For now, the stub will call the lazy
215 // resolver function.
216 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
218 if (Actual != (void*)LazyResolverFn) {
219 // If we are getting the stub for an external function, we really want the
220 // address of the stub in the GlobalAddressMap for the JIT, not the address
221 // of the external function.
222 TheJIT->updateGlobalMapping(F, Stub);
225 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
226 << F->getName() << "'\n");
228 // Finally, keep track of the stub-to-Function mapping so that the
229 // JITCompilerFn knows which function to compile!
230 state.getStubToFunctionMap(locked)[Stub] = F;
234 /// getExternalFunctionStub - Return a stub for the function at the
235 /// specified address, created lazily on demand.
236 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
237 // If we already have a stub for this function, recycle it.
238 void *&Stub = ExternalFnToStubMap[FnAddr];
239 if (Stub) return Stub;
241 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
242 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
243 << "] for external function at '" << FnAddr << "'\n");
248 /// JITCompilerFn - This function is called when a lazy compilation stub has
249 /// been entered. It looks up which function this stub corresponds to, compiles
250 /// it if necessary, then returns the resultant function pointer.
251 void *JITResolver::JITCompilerFn(void *Stub) {
252 JITResolver &JR = getJITResolver();
254 MutexGuard locked(TheJIT->lock);
256 // The address given to us for the stub may not be exactly right, it might be
257 // a little bit after the stub. As such, use upper_bound to find it.
258 std::map<void*, Function*>::iterator I =
259 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
260 assert(I != JR.state.getStubToFunctionMap(locked).begin() && "This is not a known stub!");
261 Function *F = (--I)->second;
263 // We might like to remove the stub from the StubToFunction map.
264 // We can't do that! Multiple threads could be stuck, waiting to acquire the
265 // lock above. As soon as the 1st function finishes compiling the function,
266 // the next one will be released, and needs to be able to find the function it needs
268 //JR.state.getStubToFunctionMap(locked).erase(I);
270 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
271 << "' In stub ptr = " << Stub << " actual ptr = "
272 << I->first << "\n");
274 void *Result = TheJIT->getPointerToFunction(F);
276 // We don't need to reuse this stub in the future, as F is now compiled.
277 JR.state.getFunctionToStubMap(locked).erase(F);
279 // FIXME: We could rewrite all references to this stub if we knew them.
284 // getPointerToFunctionOrStub - If the specified function has been
285 // code-gen'd, return a pointer to the function. If not, compile it, or use
286 // a stub to implement lazy compilation if available.
288 void *JIT::getPointerToFunctionOrStub(Function *F) {
289 // If we have already code generated the function, just return the address.
290 if (void *Addr = getPointerToGlobalIfAvailable(F))
293 // Get a stub if the target supports it
294 return getJITResolver(MCE).getFunctionStub(F);
299 //===----------------------------------------------------------------------===//
303 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
304 /// used to output functions to memory for execution.
305 class JITEmitter : public MachineCodeEmitter {
306 JITMemoryManager MemMgr;
308 // CurBlock - The start of the current block of memory. CurByte - The
309 // current byte being emitted to.
310 unsigned char *CurBlock, *CurByte;
312 // When outputting a function stub in the context of some other function, we
313 // save CurBlock and CurByte here.
314 unsigned char *SavedCurBlock, *SavedCurByte;
316 // ConstantPoolAddresses - Contains the location for each entry in the
318 std::vector<void*> ConstantPoolAddresses;
320 /// Relocations - These are the relocations that the function needs, as
322 std::vector<MachineRelocation> Relocations;
324 JITEmitter(JIT &jit) { TheJIT = &jit; }
326 virtual void startFunction(MachineFunction &F);
327 virtual void finishFunction(MachineFunction &F);
328 virtual void emitConstantPool(MachineConstantPool *MCP);
329 virtual void startFunctionStub(unsigned StubSize);
330 virtual void* finishFunctionStub(const Function *F);
331 virtual void emitByte(unsigned char B);
332 virtual void emitWord(unsigned W);
333 virtual void emitWordAt(unsigned W, unsigned *Ptr);
335 virtual void addRelocation(const MachineRelocation &MR) {
336 Relocations.push_back(MR);
339 virtual uint64_t getCurrentPCValue();
340 virtual uint64_t getCurrentPCOffset();
341 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
344 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
348 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
349 return new JITEmitter(jit);
352 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
353 bool DoesntNeedStub) {
354 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
355 /// FIXME: If we straightened things out, this could actually emit the
356 /// global immediately instead of queuing it for codegen later!
357 return TheJIT->getOrEmitGlobalVariable(GV);
360 // If we have already compiled the function, return a pointer to its body.
361 Function *F = cast<Function>(V);
362 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
363 if (ResultPtr) return ResultPtr;
365 if (F->hasExternalLinkage() && F->isExternal()) {
366 // If this is an external function pointer, we can force the JIT to
367 // 'compile' it, which really just adds it to the map.
369 return TheJIT->getPointerToFunction(F);
371 return getJITResolver(this).getFunctionStub(F);
374 // Okay, the function has not been compiled yet, if the target callback
375 // mechanism is capable of rewriting the instruction directly, prefer to do
376 // that instead of emitting a stub.
378 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
380 // Otherwise, we have to emit a lazy resolving stub.
381 return getJITResolver(this).getFunctionStub(F);
384 void JITEmitter::startFunction(MachineFunction &F) {
385 CurByte = CurBlock = MemMgr.startFunctionBody();
386 TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
389 void JITEmitter::finishFunction(MachineFunction &F) {
390 MemMgr.endFunctionBody(CurByte);
391 ConstantPoolAddresses.clear();
392 NumBytes += CurByte-CurBlock;
394 if (!Relocations.empty()) {
395 NumRelos += Relocations.size();
397 // Resolve the relocations to concrete pointers.
398 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
399 MachineRelocation &MR = Relocations[i];
402 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
404 // If the target REALLY wants a stub for this function, emit it now.
405 if (!MR.doesntNeedFunctionStub())
406 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
408 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
409 CurBlock+MR.getMachineCodeOffset(),
410 MR.doesntNeedFunctionStub());
411 MR.setResultPointer(ResultPtr);
414 TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
418 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
419 << "] Function: " << F.getFunction()->getName()
420 << ": " << CurByte-CurBlock << " bytes of text, "
421 << Relocations.size() << " relocations\n");
425 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
426 const std::vector<Constant*> &Constants = MCP->getConstants();
427 if (Constants.empty()) return;
429 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
430 const Type *Ty = Constants[i]->getType();
431 unsigned Size = (unsigned)TheJIT->getTargetData().getTypeSize(Ty);
432 unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
434 void *Addr = MemMgr.allocateConstant(Size, Alignment);
435 TheJIT->InitializeMemory(Constants[i], Addr);
436 ConstantPoolAddresses.push_back(Addr);
440 void JITEmitter::startFunctionStub(unsigned StubSize) {
441 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
442 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
445 void *JITEmitter::finishFunctionStub(const Function *F) {
446 NumBytes += CurByte-CurBlock;
447 std::swap(CurBlock, SavedCurBlock);
448 CurByte = SavedCurByte;
449 return SavedCurBlock;
452 void JITEmitter::emitByte(unsigned char B) {
453 *CurByte++ = B; // Write the byte to memory
456 void JITEmitter::emitWord(unsigned W) {
457 // This won't work if the endianness of the host and target don't agree! (For
458 // a JIT this can't happen though. :)
459 *(unsigned*)CurByte = W;
460 CurByte += sizeof(unsigned);
463 void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
467 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
468 // in the constant pool that was last emitted with the 'emitConstantPool'
471 uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
472 assert(ConstantNum < ConstantPoolAddresses.size() &&
473 "Invalid ConstantPoolIndex!");
474 return (intptr_t)ConstantPoolAddresses[ConstantNum];
477 // getCurrentPCValue - This returns the address that the next emitted byte
478 // will be output to.
480 uint64_t JITEmitter::getCurrentPCValue() {
481 return (intptr_t)CurByte;
484 uint64_t JITEmitter::getCurrentPCOffset() {
485 return (intptr_t)CurByte-(intptr_t)CurBlock;
488 // getPointerToNamedFunction - This function is used as a global wrapper to
489 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
490 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
491 // need to resolve function(s) that are being mis-codegenerated, so we need to
492 // resolve their addresses at runtime, and this is the way to do it.
494 void *getPointerToNamedFunction(const char *Name) {
495 Module &M = TheJIT->getModule();
496 if (Function *F = M.getNamedFunction(Name))
497 return TheJIT->getPointerToFunction(F);
498 return TheJIT->getPointerToNamedFunction(Name);