blob: 2bead72272d04bec755fd1a16e7a3281a77e5597 [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 Lattner4d326fa2003-12-20 01:46:27 +000019#include "JIT.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");
Chris Lattner4d326fa2003-12-20 01:46:27 +000034 JIT *TheJIT = 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
Chris Lattner6c0398e2004-02-08 19:33:07 +000075 int fd = -1;
Brian Gaeke364f86d2003-10-11 03:51:18 +000076#if defined(__linux__)
Chris Lattner6c0398e2004-02-08 19:33:07 +000077 fd = 0;
Brian Gaeke364f86d2003-10-11 03:51:18 +000078#endif
Chris Lattner688506d2003-08-14 18:35:27 +000079
80 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
81#ifdef MAP_NORESERVE
82 mmapFlags |= MAP_NORESERVE;
83#endif
84
85 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
Chris Lattner011efae2003-10-06 19:07:41 +000086 mmapFlags, fd, 0);
Chris Lattner688506d2003-08-14 18:35:27 +000087 if (pa == MAP_FAILED) {
88 perror("mmap");
89 abort();
90 }
91 return pa;
92}
93
94JITMemoryManager::JITMemoryManager() {
95 // Allocate a 16M block of memory...
96 MemBase = (unsigned char*)getMemory(16 << 20);
97 FunctionBase = MemBase + 512*1024; // Use 512k for stubs
98
99 // Allocate stubs backwards from the function base, allocate functions forward
100 // from the function base.
101 CurStubPtr = CurFunctionPtr = FunctionBase;
102}
103
104unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
105 CurStubPtr -= StubSize;
106 if (CurStubPtr < MemBase) {
107 std::cerr << "JIT ran out of memory for function stubs!\n";
108 abort();
109 }
110 return CurStubPtr;
111}
112
113unsigned char *JITMemoryManager::startFunctionBody() {
114 // Round up to an even multiple of 4 bytes, this should eventually be target
115 // specific.
116 return (unsigned char*)(((intptr_t)CurFunctionPtr + 3) & ~3);
117}
118
119void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
120 assert(FunctionEnd > CurFunctionPtr);
121 CurFunctionPtr = FunctionEnd;
122}
123
124
125
126namespace {
Brian Gaeke6020ddd2003-10-16 23:33:38 +0000127 /// Emitter - The JIT implementation of the MachineCodeEmitter, which is used
Chris Lattner688506d2003-08-14 18:35:27 +0000128 /// to output functions to memory for execution.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000129 class Emitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000130 JITMemoryManager MemMgr;
131
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000132 // CurBlock - The start of the current block of memory. CurByte - The
133 // current byte being emitted to.
Chris Lattner6125fdd2003-05-09 03:30:07 +0000134 unsigned char *CurBlock, *CurByte;
135
136 // When outputting a function stub in the context of some other function, we
137 // save CurBlock and CurByte here.
138 unsigned char *SavedCurBlock, *SavedCurByte;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000139
140 // ConstantPoolAddresses - Contains the location for each entry in the
141 // constant pool.
Chris Lattner1cc08382003-01-13 01:00:12 +0000142 std::vector<void*> ConstantPoolAddresses;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000143 public:
Chris Lattner4d326fa2003-12-20 01:46:27 +0000144 Emitter(JIT &jit) { TheJIT = &jit; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000145
146 virtual void startFunction(MachineFunction &F);
147 virtual void finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000148 virtual void emitConstantPool(MachineConstantPool *MCP);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000149 virtual void startFunctionStub(const Function &F, unsigned StubSize);
150 virtual void* finishFunctionStub(const Function &F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000151 virtual void emitByte(unsigned char B);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000152 virtual void emitWord(unsigned W);
153
154 virtual uint64_t getGlobalValueAddress(GlobalValue *V);
155 virtual uint64_t getGlobalValueAddress(const std::string &Name);
156 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
157 virtual uint64_t getCurrentPCValue();
158
159 // forceCompilationOf - Force the compilation of the specified function, and
160 // return its address, because we REALLY need the address now.
161 //
162 // FIXME: This is JIT specific!
163 //
164 virtual uint64_t forceCompilationOf(Function *F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000165 };
166}
167
Chris Lattner4d326fa2003-12-20 01:46:27 +0000168MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
169 return new Emitter(jit);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000170}
171
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000172void Emitter::startFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000173 CurByte = CurBlock = MemMgr.startFunctionBody();
Chris Lattner4d326fa2003-12-20 01:46:27 +0000174 TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000175}
176
177void Emitter::finishFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000178 MemMgr.endFunctionBody(CurByte);
Chris Lattner1cc08382003-01-13 01:00:12 +0000179 ConstantPoolAddresses.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000180 NumBytes += CurByte-CurBlock;
181
Brian Gaeke02c26b62003-06-30 18:06:20 +0000182 DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock
Misha Brukman1d440852003-06-06 06:52:35 +0000183 << "] Function: " << F.getFunction()->getName()
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000184 << ": " << CurByte-CurBlock << " bytes of text\n");
185}
186
Chris Lattner1cc08382003-01-13 01:00:12 +0000187void Emitter::emitConstantPool(MachineConstantPool *MCP) {
188 const std::vector<Constant*> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000189 if (Constants.empty()) return;
190
191 std::vector<unsigned> ConstantOffset;
192 ConstantOffset.reserve(Constants.size());
193
194 // Calculate how much space we will need for all the constants, and the offset
195 // each one will live in.
196 unsigned TotalSize = 0;
Chris Lattner1cc08382003-01-13 01:00:12 +0000197 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000198 const Type *Ty = Constants[i]->getType();
Chris Lattner4d326fa2003-12-20 01:46:27 +0000199 unsigned Size = TheJIT->getTargetData().getTypeSize(Ty);
200 unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000201 // Make sure to take into account the alignment requirements of the type.
202 TotalSize = (TotalSize + Alignment-1) & ~(Alignment-1);
203
204 // Remember the offset this element lives at.
205 ConstantOffset.push_back(TotalSize);
206 TotalSize += Size; // Reserve space for the constant.
207 }
208
209 // Now that we know how much memory to allocate, do so.
210 char *Pool = new char[TotalSize];
211
212 // Actually output all of the constants, and remember their addresses.
213 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
214 void *Addr = Pool + ConstantOffset[i];
Chris Lattner4d326fa2003-12-20 01:46:27 +0000215 TheJIT->InitializeMemory(Constants[i], Addr);
Misha Brukman91de3522003-11-30 00:50:53 +0000216 ConstantPoolAddresses.push_back(Addr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000217 }
218}
219
Chris Lattner6125fdd2003-05-09 03:30:07 +0000220void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
221 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
Chris Lattner688506d2003-08-14 18:35:27 +0000222 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000223}
224
225void *Emitter::finishFunctionStub(const Function &F) {
226 NumBytes += CurByte-CurBlock;
227 DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
228 << (unsigned)(intptr_t)CurBlock
229 << std::dec << "] Function stub for: " << F.getName()
230 << ": " << CurByte-CurBlock << " bytes of text\n");
231 std::swap(CurBlock, SavedCurBlock);
232 CurByte = SavedCurByte;
233 return SavedCurBlock;
234}
235
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000236void Emitter::emitByte(unsigned char B) {
237 *CurByte++ = B; // Write the byte to memory
238}
239
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000240void Emitter::emitWord(unsigned W) {
Chris Lattner688506d2003-08-14 18:35:27 +0000241 // This won't work if the endianness of the host and target don't agree! (For
242 // a JIT this can't happen though. :)
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000243 *(unsigned*)CurByte = W;
244 CurByte += sizeof(unsigned);
245}
246
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000247uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
248 // Try looking up the function to see if it is already compiled, if not return
249 // 0.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000250 if (isa<Function>(V))
251 return (intptr_t)TheJIT->getPointerToGlobalIfAvailable(V);
252 else {
253 return (intptr_t)TheJIT->getOrEmitGlobalVariable(cast<GlobalVariable>(V));
254 }
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000255}
256uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000257 return (intptr_t)TheJIT->getPointerToNamedFunction(Name);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000258}
259
260// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
261// in the constant pool that was last emitted with the 'emitConstantPool'
262// method.
263//
264uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
265 assert(ConstantNum < ConstantPoolAddresses.size() &&
266 "Invalid ConstantPoolIndex!");
267 return (intptr_t)ConstantPoolAddresses[ConstantNum];
268}
269
270// getCurrentPCValue - This returns the address that the next emitted byte
271// will be output to.
272//
273uint64_t Emitter::getCurrentPCValue() {
274 return (intptr_t)CurByte;
275}
276
277uint64_t Emitter::forceCompilationOf(Function *F) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000278 return (intptr_t)TheJIT->getPointerToFunction(F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000279}
280
Misha Brukmand69c1e62003-07-28 19:09:06 +0000281// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000282// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000283// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
284// need to resolve function(s) that are being mis-codegenerated, so we need to
285// resolve their addresses at runtime, and this is the way to do it.
286extern "C" {
287 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000288 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000289 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000290 return TheJIT->getPointerToFunction(F);
291 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000292 }
293}