blob: 2495360aea1ec787c28030627ba0e864857e61df [file] [log] [blame]
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001//===-- Emitter.cpp - Write machine code to executable memory -------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009//
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.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Misha Brukman36d10ef2003-09-10 20:52:05 +000016#ifndef _POSIX_MAPPED_FILES
17#define _POSIX_MAPPED_FILES
18#endif
Chris Lattnerbd199fb2002-12-24 00:01:05 +000019#include "VM.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000020#include "llvm/Constant.h"
21#include "llvm/Module.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000022#include "llvm/CodeGen/MachineCodeEmitter.h"
23#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000024#include "llvm/CodeGen/MachineConstantPool.h"
25#include "llvm/Target/TargetData.h"
Chris Lattnerc648dab2003-08-01 22:13:59 +000026#include "Support/Debug.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000027#include "Support/Statistic.h"
Misha Brukman36d10ef2003-09-10 20:52:05 +000028#include "Config/unistd.h"
29#include "Config/sys/mman.h"
Chris Lattnerc19aade2003-12-08 08:06:28 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattnerbd199fb2002-12-24 00:01:05 +000032namespace {
Chris Lattnere7386562003-10-20 05:45:49 +000033 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
Misha Brukmand69c1e62003-07-28 19:09:06 +000034 VM *TheVM = 0;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000035
Chris Lattner688506d2003-08-14 18:35:27 +000036 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
37 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
38 /// sections, one for function stubs, one for the functions themselves. We
39 /// have to do this because we may need to emit a function stub while in the
40 /// middle of emitting a function, and we don't know how large the function we
41 /// are emitting is. This never bothers to release the memory, because when
42 /// we are ready to destroy the JIT, the program exits.
43 class JITMemoryManager {
44 unsigned char *MemBase; // Base of block of memory, start of stub mem
45 unsigned char *FunctionBase; // Start of the function body area
46 unsigned char *CurStubPtr, *CurFunctionPtr;
47 public:
48 JITMemoryManager();
49
50 inline unsigned char *allocateStub(unsigned StubSize);
51 inline unsigned char *startFunctionBody();
52 inline void endFunctionBody(unsigned char *FunctionEnd);
53 };
54}
55
Chris Lattner688506d2003-08-14 18:35:27 +000056// getMemory - Return a pointer to the specified number of bytes, which is
57// mapped as executable readable and writable.
58static void *getMemory(unsigned NumBytes) {
59 if (NumBytes == 0) return 0;
60 static const long pageSize = sysconf(_SC_PAGESIZE);
61 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
62
63#if defined(i386) || defined(__i386__) || defined(__x86__)
64 /* Linux and *BSD tend to have these flags named differently. */
65#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
66# define MAP_ANONYMOUS MAP_ANON
67#endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
Chris Lattner688506d2003-08-14 18:35:27 +000068#elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
Brian Gaeke364f86d2003-10-11 03:51:18 +000069/* nothing */
Chris Lattner688506d2003-08-14 18:35:27 +000070#else
71 std::cerr << "This architecture is not supported by the JIT!\n";
72 abort();
73#endif
Brian Gaeke364f86d2003-10-11 03:51:18 +000074
75#if defined(__linux__)
76#define fd 0
77#else
78#define fd -1
79#endif
Chris Lattner688506d2003-08-14 18:35:27 +000080
81 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
82#ifdef MAP_NORESERVE
83 mmapFlags |= MAP_NORESERVE;
84#endif
85
86 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
Chris Lattner011efae2003-10-06 19:07:41 +000087 mmapFlags, fd, 0);
Chris Lattner688506d2003-08-14 18:35:27 +000088 if (pa == MAP_FAILED) {
89 perror("mmap");
90 abort();
91 }
92 return pa;
93}
94
95JITMemoryManager::JITMemoryManager() {
96 // Allocate a 16M block of memory...
97 MemBase = (unsigned char*)getMemory(16 << 20);
98 FunctionBase = MemBase + 512*1024; // Use 512k for stubs
99
100 // Allocate stubs backwards from the function base, allocate functions forward
101 // from the function base.
102 CurStubPtr = CurFunctionPtr = FunctionBase;
103}
104
105unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
106 CurStubPtr -= StubSize;
107 if (CurStubPtr < MemBase) {
108 std::cerr << "JIT ran out of memory for function stubs!\n";
109 abort();
110 }
111 return CurStubPtr;
112}
113
114unsigned char *JITMemoryManager::startFunctionBody() {
115 // Round up to an even multiple of 4 bytes, this should eventually be target
116 // specific.
117 return (unsigned char*)(((intptr_t)CurFunctionPtr + 3) & ~3);
118}
119
120void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
121 assert(FunctionEnd > CurFunctionPtr);
122 CurFunctionPtr = FunctionEnd;
123}
124
125
126
127namespace {
Brian Gaeke6020ddd2003-10-16 23:33:38 +0000128 /// Emitter - The JIT implementation of the MachineCodeEmitter, which is used
Chris Lattner688506d2003-08-14 18:35:27 +0000129 /// to output functions to memory for execution.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000130 class Emitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000131 JITMemoryManager MemMgr;
132
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000133 // CurBlock - The start of the current block of memory. CurByte - The
134 // current byte being emitted to.
Chris Lattner6125fdd2003-05-09 03:30:07 +0000135 unsigned char *CurBlock, *CurByte;
136
137 // When outputting a function stub in the context of some other function, we
138 // save CurBlock and CurByte here.
139 unsigned char *SavedCurBlock, *SavedCurByte;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000140
141 // ConstantPoolAddresses - Contains the location for each entry in the
142 // constant pool.
Chris Lattner1cc08382003-01-13 01:00:12 +0000143 std::vector<void*> ConstantPoolAddresses;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000144 public:
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000145 Emitter(VM &vm) { TheVM = &vm; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000146
147 virtual void startFunction(MachineFunction &F);
148 virtual void finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000149 virtual void emitConstantPool(MachineConstantPool *MCP);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000150 virtual void startFunctionStub(const Function &F, unsigned StubSize);
151 virtual void* finishFunctionStub(const Function &F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000152 virtual void emitByte(unsigned char B);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000153 virtual void emitWord(unsigned W);
154
155 virtual uint64_t getGlobalValueAddress(GlobalValue *V);
156 virtual uint64_t getGlobalValueAddress(const std::string &Name);
157 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
158 virtual uint64_t getCurrentPCValue();
159
160 // forceCompilationOf - Force the compilation of the specified function, and
161 // return its address, because we REALLY need the address now.
162 //
163 // FIXME: This is JIT specific!
164 //
165 virtual uint64_t forceCompilationOf(Function *F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000166 };
167}
168
Misha Brukman906f5fa2003-06-02 03:23:16 +0000169MachineCodeEmitter *VM::createEmitter(VM &V) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000170 return new Emitter(V);
171}
172
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000173void Emitter::startFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000174 CurByte = CurBlock = MemMgr.startFunctionBody();
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000175 TheVM->addGlobalMapping(F.getFunction(), CurBlock);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000176}
177
178void Emitter::finishFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000179 MemMgr.endFunctionBody(CurByte);
Chris Lattner1cc08382003-01-13 01:00:12 +0000180 ConstantPoolAddresses.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000181 NumBytes += CurByte-CurBlock;
182
Brian Gaeke02c26b62003-06-30 18:06:20 +0000183 DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock
Misha Brukman1d440852003-06-06 06:52:35 +0000184 << "] Function: " << F.getFunction()->getName()
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000185 << ": " << CurByte-CurBlock << " bytes of text\n");
186}
187
Chris Lattner1cc08382003-01-13 01:00:12 +0000188void Emitter::emitConstantPool(MachineConstantPool *MCP) {
189 const std::vector<Constant*> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000190 if (Constants.empty()) return;
191
192 std::vector<unsigned> ConstantOffset;
193 ConstantOffset.reserve(Constants.size());
194
195 // Calculate how much space we will need for all the constants, and the offset
196 // each one will live in.
197 unsigned TotalSize = 0;
Chris Lattner1cc08382003-01-13 01:00:12 +0000198 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000199 const Type *Ty = Constants[i]->getType();
200 unsigned Size = TheVM->getTargetData().getTypeSize(Ty);
201 unsigned Alignment = TheVM->getTargetData().getTypeAlignment(Ty);
202 // Make sure to take into account the alignment requirements of the type.
203 TotalSize = (TotalSize + Alignment-1) & ~(Alignment-1);
204
205 // Remember the offset this element lives at.
206 ConstantOffset.push_back(TotalSize);
207 TotalSize += Size; // Reserve space for the constant.
208 }
209
210 // Now that we know how much memory to allocate, do so.
211 char *Pool = new char[TotalSize];
212
213 // Actually output all of the constants, and remember their addresses.
214 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
215 void *Addr = Pool + ConstantOffset[i];
Misha Brukman91de3522003-11-30 00:50:53 +0000216 TheVM->InitializeMemory(Constants[i], Addr);
217 ConstantPoolAddresses.push_back(Addr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000218 }
219}
220
Chris Lattner6125fdd2003-05-09 03:30:07 +0000221void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
222 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
Chris Lattner688506d2003-08-14 18:35:27 +0000223 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000224}
225
226void *Emitter::finishFunctionStub(const Function &F) {
227 NumBytes += CurByte-CurBlock;
228 DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
229 << (unsigned)(intptr_t)CurBlock
230 << std::dec << "] Function stub for: " << F.getName()
231 << ": " << CurByte-CurBlock << " bytes of text\n");
232 std::swap(CurBlock, SavedCurBlock);
233 CurByte = SavedCurByte;
234 return SavedCurBlock;
235}
236
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000237void Emitter::emitByte(unsigned char B) {
238 *CurByte++ = B; // Write the byte to memory
239}
240
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000241void Emitter::emitWord(unsigned W) {
Chris Lattner688506d2003-08-14 18:35:27 +0000242 // This won't work if the endianness of the host and target don't agree! (For
243 // a JIT this can't happen though. :)
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000244 *(unsigned*)CurByte = W;
245 CurByte += sizeof(unsigned);
246}
247
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000248uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
249 // Try looking up the function to see if it is already compiled, if not return
250 // 0.
251 return (intptr_t)TheVM->getPointerToGlobalIfAvailable(V);
252}
253uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
254 return (intptr_t)TheVM->getPointerToNamedFunction(Name);
255}
256
257// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
258// in the constant pool that was last emitted with the 'emitConstantPool'
259// method.
260//
261uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
262 assert(ConstantNum < ConstantPoolAddresses.size() &&
263 "Invalid ConstantPoolIndex!");
264 return (intptr_t)ConstantPoolAddresses[ConstantNum];
265}
266
267// getCurrentPCValue - This returns the address that the next emitted byte
268// will be output to.
269//
270uint64_t Emitter::getCurrentPCValue() {
271 return (intptr_t)CurByte;
272}
273
274uint64_t Emitter::forceCompilationOf(Function *F) {
275 return (intptr_t)TheVM->getPointerToFunction(F);
276}
277
Misha Brukmand69c1e62003-07-28 19:09:06 +0000278// getPointerToNamedFunction - This function is used as a global wrapper to
279// VM::getPointerToNamedFunction for the purpose of resolving symbols when
280// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
281// need to resolve function(s) that are being mis-codegenerated, so we need to
282// resolve their addresses at runtime, and this is the way to do it.
283extern "C" {
284 void *getPointerToNamedFunction(const char *Name) {
285 Module &M = TheVM->getModule();
286 if (Function *F = M.getNamedFunction(Name))
287 return TheVM->getPointerToFunction(F);
288 return TheVM->getPointerToNamedFunction(Name);
289 }
290}