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/CodeGen/MachineCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineRelocation.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetJITInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/System/Memory.h"
31 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
36 //===----------------------------------------------------------------------===//
37 // JITMemoryManager code.
40 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
41 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
42 /// sections, one for function stubs, one for the functions themselves. We
43 /// have to do this because we may need to emit a function stub while in the
44 /// middle of emitting a function, and we don't know how large the function we
45 /// are emitting is. This never bothers to release the memory, because when
46 /// we are ready to destroy the JIT, the program exits.
47 class JITMemoryManager {
48 sys::MemoryBlock MemBlock; // Virtual memory block allocated RWX
49 unsigned char *MemBase; // Base of block of memory, start of stub mem
50 unsigned char *FunctionBase; // Start of the function body area
51 unsigned char *CurStubPtr, *CurFunctionPtr;
55 inline unsigned char *allocateStub(unsigned StubSize);
56 inline unsigned char *startFunctionBody();
57 inline void endFunctionBody(unsigned char *FunctionEnd);
61 JITMemoryManager::JITMemoryManager() {
62 // Allocate a 16M block of memory...
63 MemBlock = sys::Memory::AllocateRWX((16 << 20));
64 MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
65 FunctionBase = MemBase + 512*1024; // Use 512k for stubs
67 // Allocate stubs backwards from the function base, allocate functions forward
68 // from the function base.
69 CurStubPtr = CurFunctionPtr = FunctionBase;
72 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
73 CurStubPtr -= StubSize;
74 if (CurStubPtr < MemBase) {
75 std::cerr << "JIT ran out of memory for function stubs!\n";
81 unsigned char *JITMemoryManager::startFunctionBody() {
82 // Round up to an even multiple of 8 bytes, this should eventually be target
84 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
87 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
88 assert(FunctionEnd > CurFunctionPtr);
89 CurFunctionPtr = FunctionEnd;
92 //===----------------------------------------------------------------------===//
93 // JIT lazy compilation code.
96 /// JITResolver - Keep track of, and resolve, call sites for functions that
97 /// have not yet been compiled.
99 /// MCE - The MachineCodeEmitter to use to emit stubs with.
100 MachineCodeEmitter &MCE;
102 /// LazyResolverFn - The target lazy resolver function that we actually
103 /// rewrite instructions to use.
104 TargetJITInfo::LazyResolverFn LazyResolverFn;
106 // FunctionToStubMap - Keep track of the stub created for a particular
107 // function so that we can reuse them if necessary.
108 std::map<Function*, void*> FunctionToStubMap;
110 // StubToFunctionMap - Keep track of the function that each stub corresponds
112 std::map<void*, Function*> StubToFunctionMap;
115 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {
117 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
120 /// getFunctionStub - This returns a pointer to a function stub, creating
121 /// one on demand as needed.
122 void *getFunctionStub(Function *F);
124 /// AddCallbackAtLocation - If the target is capable of rewriting an
125 /// instruction without the use of a stub, record the location of the use so
126 /// we know which function is being used at the location.
127 void *AddCallbackAtLocation(Function *F, void *Location) {
128 /// Get the target-specific JIT resolver function.
129 StubToFunctionMap[Location] = F;
130 return (void*)LazyResolverFn;
133 /// JITCompilerFn - This function is called to resolve a stub to a compiled
134 /// address. If the LLVM Function corresponding to the stub has not yet
135 /// been compiled, this function compiles it first.
136 static void *JITCompilerFn(void *Stub);
140 /// getJITResolver - This function returns the one instance of the JIT resolver.
142 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
143 static JITResolver TheJITResolver(*MCE);
144 return TheJITResolver;
147 /// getFunctionStub - This returns a pointer to a function stub, creating
148 /// one on demand as needed.
149 void *JITResolver::getFunctionStub(Function *F) {
150 // If we already have a stub for this function, recycle it.
151 void *&Stub = FunctionToStubMap[F];
152 if (Stub) return Stub;
154 // Call the lazy resolver function unless we already KNOW it is an external
155 // function, in which case we just skip the lazy resolution step.
156 void *Actual = (void*)LazyResolverFn;
157 if (F->hasExternalLinkage())
158 Actual = TheJIT->getPointerToFunction(F);
160 // Otherwise, codegen a new stub. For now, the stub will call the lazy
161 // resolver function.
162 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
164 if (F->hasExternalLinkage()) {
165 // If we are getting the stub for an external function, we really want the
166 // address of the stub in the GlobalAddressMap for the JIT, not the address
167 // of the external function.
168 TheJIT->updateGlobalMapping(F, Stub);
171 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
172 << F->getName() << "'\n");
174 // Finally, keep track of the stub-to-Function mapping so that the
175 // JITCompilerFn knows which function to compile!
176 StubToFunctionMap[Stub] = F;
180 /// JITCompilerFn - This function is called when a lazy compilation stub has
181 /// been entered. It looks up which function this stub corresponds to, compiles
182 /// it if necessary, then returns the resultant function pointer.
183 void *JITResolver::JITCompilerFn(void *Stub) {
184 JITResolver &JR = getJITResolver();
186 // The address given to us for the stub may not be exactly right, it might be
187 // a little bit after the stub. As such, use upper_bound to find it.
188 std::map<void*, Function*>::iterator I =
189 JR.StubToFunctionMap.upper_bound(Stub);
190 assert(I != JR.StubToFunctionMap.begin() && "This is not a known stub!");
191 Function *F = (--I)->second;
193 // The target function will rewrite the stub so that the compilation callback
194 // function is no longer called from this stub.
195 JR.StubToFunctionMap.erase(I);
197 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
198 << "' In stub ptr = " << Stub << " actual ptr = "
199 << I->first << "\n");
201 void *Result = TheJIT->getPointerToFunction(F);
203 // We don't need to reuse this stub in the future, as F is now compiled.
204 JR.FunctionToStubMap.erase(F);
206 // FIXME: We could rewrite all references to this stub if we knew them.
211 //===----------------------------------------------------------------------===//
215 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
216 /// used to output functions to memory for execution.
217 class JITEmitter : public MachineCodeEmitter {
218 JITMemoryManager MemMgr;
220 // CurBlock - The start of the current block of memory. CurByte - The
221 // current byte being emitted to.
222 unsigned char *CurBlock, *CurByte;
224 // When outputting a function stub in the context of some other function, we
225 // save CurBlock and CurByte here.
226 unsigned char *SavedCurBlock, *SavedCurByte;
228 // ConstantPoolAddresses - Contains the location for each entry in the
230 std::vector<void*> ConstantPoolAddresses;
232 /// Relocations - These are the relocations that the function needs, as
234 std::vector<MachineRelocation> Relocations;
236 JITEmitter(JIT &jit) { TheJIT = &jit; }
238 virtual void startFunction(MachineFunction &F);
239 virtual void finishFunction(MachineFunction &F);
240 virtual void emitConstantPool(MachineConstantPool *MCP);
241 virtual void startFunctionStub(unsigned StubSize);
242 virtual void* finishFunctionStub(const Function *F);
243 virtual void emitByte(unsigned char B);
244 virtual void emitWord(unsigned W);
245 virtual void emitWordAt(unsigned W, unsigned *Ptr);
247 virtual void addRelocation(const MachineRelocation &MR) {
248 Relocations.push_back(MR);
251 virtual uint64_t getCurrentPCValue();
252 virtual uint64_t getCurrentPCOffset();
253 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
256 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
260 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
261 return new JITEmitter(jit);
264 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
265 bool DoesntNeedStub) {
266 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
267 /// FIXME: If we straightened things out, this could actually emit the
268 /// global immediately instead of queuing it for codegen later!
269 GlobalVariable *GV = cast<GlobalVariable>(V);
270 return TheJIT->getOrEmitGlobalVariable(GV);
273 // If we have already compiled the function, return a pointer to its body.
274 Function *F = cast<Function>(V);
275 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
276 if (ResultPtr) return ResultPtr;
278 if (F->hasExternalLinkage() && F->isExternal()) {
279 // If this is an external function pointer, we can force the JIT to
280 // 'compile' it, which really just adds it to the map.
282 return TheJIT->getPointerToFunction(F);
284 return getJITResolver(this).getFunctionStub(F);
287 // Okay, the function has not been compiled yet, if the target callback
288 // mechanism is capable of rewriting the instruction directly, prefer to do
289 // that instead of emitting a stub.
291 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
293 // Otherwise, we have to emit a lazy resolving stub.
294 return getJITResolver(this).getFunctionStub(F);
297 void JITEmitter::startFunction(MachineFunction &F) {
298 CurByte = CurBlock = MemMgr.startFunctionBody();
299 TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
302 void JITEmitter::finishFunction(MachineFunction &F) {
303 MemMgr.endFunctionBody(CurByte);
304 ConstantPoolAddresses.clear();
305 NumBytes += CurByte-CurBlock;
307 if (!Relocations.empty()) {
308 // Resolve the relocations to concrete pointers.
309 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
310 MachineRelocation &MR = Relocations[i];
313 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
315 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
316 CurBlock+MR.getMachineCodeOffset(),
317 MR.doesntNeedFunctionStub());
318 MR.setResultPointer(ResultPtr);
321 TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
325 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
326 << "] Function: " << F.getFunction()->getName()
327 << ": " << CurByte-CurBlock << " bytes of text, "
328 << Relocations.size() << " relocations\n");
332 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
333 const std::vector<Constant*> &Constants = MCP->getConstants();
334 if (Constants.empty()) return;
336 std::vector<unsigned> ConstantOffset;
337 ConstantOffset.reserve(Constants.size());
339 // Calculate how much space we will need for all the constants, and the offset
340 // each one will live in.
341 unsigned TotalSize = 0;
342 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
343 const Type *Ty = Constants[i]->getType();
344 unsigned Size = TheJIT->getTargetData().getTypeSize(Ty);
345 unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
346 // Make sure to take into account the alignment requirements of the type.
347 TotalSize = (TotalSize + Alignment-1) & ~(Alignment-1);
349 // Remember the offset this element lives at.
350 ConstantOffset.push_back(TotalSize);
351 TotalSize += Size; // Reserve space for the constant.
354 // Now that we know how much memory to allocate, do so.
355 char *Pool = new char[TotalSize];
357 // Actually output all of the constants, and remember their addresses.
358 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
359 void *Addr = Pool + ConstantOffset[i];
360 TheJIT->InitializeMemory(Constants[i], Addr);
361 ConstantPoolAddresses.push_back(Addr);
365 void JITEmitter::startFunctionStub(unsigned StubSize) {
366 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
367 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
370 void *JITEmitter::finishFunctionStub(const Function *F) {
371 NumBytes += CurByte-CurBlock;
372 std::swap(CurBlock, SavedCurBlock);
373 CurByte = SavedCurByte;
374 return SavedCurBlock;
377 void JITEmitter::emitByte(unsigned char B) {
378 *CurByte++ = B; // Write the byte to memory
381 void JITEmitter::emitWord(unsigned W) {
382 // This won't work if the endianness of the host and target don't agree! (For
383 // a JIT this can't happen though. :)
384 *(unsigned*)CurByte = W;
385 CurByte += sizeof(unsigned);
388 void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
392 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
393 // in the constant pool that was last emitted with the 'emitConstantPool'
396 uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
397 assert(ConstantNum < ConstantPoolAddresses.size() &&
398 "Invalid ConstantPoolIndex!");
399 return (intptr_t)ConstantPoolAddresses[ConstantNum];
402 // getCurrentPCValue - This returns the address that the next emitted byte
403 // will be output to.
405 uint64_t JITEmitter::getCurrentPCValue() {
406 return (intptr_t)CurByte;
409 uint64_t JITEmitter::getCurrentPCOffset() {
410 return (intptr_t)CurByte-(intptr_t)CurBlock;
413 // getPointerToNamedFunction - This function is used as a global wrapper to
414 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
415 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
416 // need to resolve function(s) that are being mis-codegenerated, so we need to
417 // resolve their addresses at runtime, and this is the way to do it.
419 void *getPointerToNamedFunction(const char *Name) {
420 Module &M = TheJIT->getModule();
421 if (Function *F = M.getNamedFunction(Name))
422 return TheJIT->getPointerToFunction(F);
423 return TheJIT->getPointerToNamedFunction(Name);