1 //===-- Emitter.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 Jello to write
11 // machine code to memory and remember where relocatable values lie.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
16 #ifndef _POSIX_MAPPED_FILES
17 #define _POSIX_MAPPED_FILES
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Module.h"
25 #include "Support/Debug.h"
26 #include "Support/Statistic.h"
27 #include "Config/unistd.h"
28 #include "Config/sys/mman.h"
31 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
34 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
35 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
36 /// sections, one for function stubs, one for the functions themselves. We
37 /// have to do this because we may need to emit a function stub while in the
38 /// middle of emitting a function, and we don't know how large the function we
39 /// are emitting is. This never bothers to release the memory, because when
40 /// we are ready to destroy the JIT, the program exits.
41 class JITMemoryManager {
42 unsigned char *MemBase; // Base of block of memory, start of stub mem
43 unsigned char *FunctionBase; // Start of the function body area
44 unsigned char *CurStubPtr, *CurFunctionPtr;
48 inline unsigned char *allocateStub(unsigned StubSize);
49 inline unsigned char *startFunctionBody();
50 inline void endFunctionBody(unsigned char *FunctionEnd);
54 // getMemory - Return a pointer to the specified number of bytes, which is
55 // mapped as executable readable and writable.
56 static void *getMemory(unsigned NumBytes) {
57 if (NumBytes == 0) return 0;
58 static const long pageSize = sysconf(_SC_PAGESIZE);
59 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
61 #if defined(i386) || defined(__i386__) || defined(__x86__)
62 /* Linux and *BSD tend to have these flags named differently. */
63 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
64 # define MAP_ANONYMOUS MAP_ANON
65 #endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
66 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
69 std::cerr << "This architecture is not supported by the JIT!\n";
73 #if defined(__linux__)
79 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
81 mmapFlags |= MAP_NORESERVE;
84 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
86 if (pa == MAP_FAILED) {
93 JITMemoryManager::JITMemoryManager() {
94 // Allocate a 16M block of memory...
95 MemBase = (unsigned char*)getMemory(16 << 20);
96 FunctionBase = MemBase + 512*1024; // Use 512k for stubs
98 // Allocate stubs backwards from the function base, allocate functions forward
99 // from the function base.
100 CurStubPtr = CurFunctionPtr = FunctionBase;
103 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
104 CurStubPtr -= StubSize;
105 if (CurStubPtr < MemBase) {
106 std::cerr << "JIT ran out of memory for function stubs!\n";
112 unsigned char *JITMemoryManager::startFunctionBody() {
113 // Round up to an even multiple of 4 bytes, this should eventually be target
115 return (unsigned char*)(((intptr_t)CurFunctionPtr + 3) & ~3);
118 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
119 assert(FunctionEnd > CurFunctionPtr);
120 CurFunctionPtr = FunctionEnd;
126 /// Emitter - The JIT implementation of the MachineCodeEmitter, which is used
127 /// to output functions to memory for execution.
128 class Emitter : public MachineCodeEmitter {
129 JITMemoryManager MemMgr;
131 // CurBlock - The start of the current block of memory. CurByte - The
132 // current byte being emitted to.
133 unsigned char *CurBlock, *CurByte;
135 // When outputting a function stub in the context of some other function, we
136 // save CurBlock and CurByte here.
137 unsigned char *SavedCurBlock, *SavedCurByte;
139 // ConstantPoolAddresses - Contains the location for each entry in the
141 std::vector<void*> ConstantPoolAddresses;
143 Emitter(VM &vm) { TheVM = &vm; }
145 virtual void startFunction(MachineFunction &F);
146 virtual void finishFunction(MachineFunction &F);
147 virtual void emitConstantPool(MachineConstantPool *MCP);
148 virtual void startFunctionStub(const Function &F, unsigned StubSize);
149 virtual void* finishFunctionStub(const Function &F);
150 virtual void emitByte(unsigned char B);
151 virtual void emitWord(unsigned W);
153 virtual uint64_t getGlobalValueAddress(GlobalValue *V);
154 virtual uint64_t getGlobalValueAddress(const std::string &Name);
155 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
156 virtual uint64_t getCurrentPCValue();
158 // forceCompilationOf - Force the compilation of the specified function, and
159 // return its address, because we REALLY need the address now.
161 // FIXME: This is JIT specific!
163 virtual uint64_t forceCompilationOf(Function *F);
167 MachineCodeEmitter *VM::createEmitter(VM &V) {
168 return new Emitter(V);
171 void Emitter::startFunction(MachineFunction &F) {
172 CurByte = CurBlock = MemMgr.startFunctionBody();
173 TheVM->addGlobalMapping(F.getFunction(), CurBlock);
176 void Emitter::finishFunction(MachineFunction &F) {
177 MemMgr.endFunctionBody(CurByte);
178 ConstantPoolAddresses.clear();
179 NumBytes += CurByte-CurBlock;
181 DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock
182 << "] Function: " << F.getFunction()->getName()
183 << ": " << CurByte-CurBlock << " bytes of text\n");
186 void Emitter::emitConstantPool(MachineConstantPool *MCP) {
187 const std::vector<Constant*> &Constants = MCP->getConstants();
188 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
189 // For now we just allocate some memory on the heap, this can be
190 // dramatically improved.
191 const Type *Ty = ((Value*)Constants[i])->getType();
192 void *Addr = malloc(TheVM->getTargetData().getTypeSize(Ty));
193 TheVM->InitializeMemory(Constants[i], Addr);
194 ConstantPoolAddresses.push_back(Addr);
198 void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
199 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
200 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
203 void *Emitter::finishFunctionStub(const Function &F) {
204 NumBytes += CurByte-CurBlock;
205 DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
206 << (unsigned)(intptr_t)CurBlock
207 << std::dec << "] Function stub for: " << F.getName()
208 << ": " << CurByte-CurBlock << " bytes of text\n");
209 std::swap(CurBlock, SavedCurBlock);
210 CurByte = SavedCurByte;
211 return SavedCurBlock;
214 void Emitter::emitByte(unsigned char B) {
215 *CurByte++ = B; // Write the byte to memory
218 void Emitter::emitWord(unsigned W) {
219 // This won't work if the endianness of the host and target don't agree! (For
220 // a JIT this can't happen though. :)
221 *(unsigned*)CurByte = W;
222 CurByte += sizeof(unsigned);
225 uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
226 // Try looking up the function to see if it is already compiled, if not return
228 return (intptr_t)TheVM->getPointerToGlobalIfAvailable(V);
230 uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
231 return (intptr_t)TheVM->getPointerToNamedFunction(Name);
234 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
235 // in the constant pool that was last emitted with the 'emitConstantPool'
238 uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
239 assert(ConstantNum < ConstantPoolAddresses.size() &&
240 "Invalid ConstantPoolIndex!");
241 return (intptr_t)ConstantPoolAddresses[ConstantNum];
244 // getCurrentPCValue - This returns the address that the next emitted byte
245 // will be output to.
247 uint64_t Emitter::getCurrentPCValue() {
248 return (intptr_t)CurByte;
251 uint64_t Emitter::forceCompilationOf(Function *F) {
252 return (intptr_t)TheVM->getPointerToFunction(F);
255 // getPointerToNamedFunction - This function is used as a global wrapper to
256 // VM::getPointerToNamedFunction for the purpose of resolving symbols when
257 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
258 // need to resolve function(s) that are being mis-codegenerated, so we need to
259 // resolve their addresses at runtime, and this is the way to do it.
261 void *getPointerToNamedFunction(const char *Name) {
262 Module &M = TheVM->getModule();
263 if (Function *F = M.getNamedFunction(Name))
264 return TheVM->getPointerToFunction(F);
265 return TheVM->getPointerToNamedFunction(Name);