blob: 47b45a0daf53d7b336abba266fad2e6a8bdbe3b6 [file] [log] [blame]
Chris Lattner166f2262004-11-22 22:00:25 +00001//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009//
Chris Lattner5be478f2004-11-20 03:46:14 +000010// 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.
Chris Lattnerbd199fb2002-12-24 00:01:05 +000012//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Chris Lattner4d326fa2003-12-20 01:46:27 +000016#include "JIT.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000017#include "llvm/Constant.h"
18#include "llvm/Module.h"
Chris Lattner5b3a4552005-03-17 15:38:16 +000019#include "llvm/Type.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000020#include "llvm/CodeGen/MachineCodeEmitter.h"
21#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000022#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman37efe672006-04-22 18:53:45 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000024#include "llvm/CodeGen/MachineRelocation.h"
Nate Begeman37efe672006-04-22 18:53:45 +000025#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000026#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000027#include "llvm/Target/TargetJITInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/Support/Debug.h"
29#include "llvm/ADT/Statistic.h"
Reid Spencer52b0ba62004-09-11 04:31:03 +000030#include "llvm/System/Memory.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000031#include <algorithm>
Chris Lattnerca261802006-01-22 23:41:42 +000032#include <iostream>
33#include <list>
Chris Lattnerc19aade2003-12-08 08:06:28 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Chris Lattnerbd199fb2002-12-24 00:01:05 +000036namespace {
Chris Lattnere7386562003-10-20 05:45:49 +000037 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
Chris Lattnere884dc22005-07-20 16:29:20 +000038 Statistic<> NumRelos("jit", "Number of relocations applied");
Chris Lattner4d326fa2003-12-20 01:46:27 +000039 JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000040}
Chris Lattnerbd199fb2002-12-24 00:01:05 +000041
Chris Lattner54266522004-11-20 23:57:07 +000042
43//===----------------------------------------------------------------------===//
44// JITMemoryManager code.
45//
46namespace {
Chris Lattner688506d2003-08-14 18:35:27 +000047 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
48 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
49 /// sections, one for function stubs, one for the functions themselves. We
50 /// have to do this because we may need to emit a function stub while in the
51 /// middle of emitting a function, and we don't know how large the function we
52 /// are emitting is. This never bothers to release the memory, because when
53 /// we are ready to destroy the JIT, the program exits.
54 class JITMemoryManager {
Andrew Lenhartha00269b2005-07-29 23:40:16 +000055 std::list<sys::MemoryBlock> Blocks; // List of blocks allocated by the JIT
Chris Lattner688506d2003-08-14 18:35:27 +000056 unsigned char *FunctionBase; // Start of the function body area
Andrew Lenhartha00269b2005-07-29 23:40:16 +000057 unsigned char *ConstantBase; // Memory allocated for constant pools
Chris Lattnerf5d438c2006-05-02 21:57:51 +000058 unsigned char *CurStubPtr, *CurFunctionPtr, *CurConstantPtr;
Chris Lattnera726c7f2006-05-02 21:44:14 +000059 unsigned char *GOTBase; // Target Specific reserved memory
Andrew Lenhartha00269b2005-07-29 23:40:16 +000060
61 // centralize memory block allocation
62 sys::MemoryBlock getNewMemoryBlock(unsigned size);
Chris Lattner688506d2003-08-14 18:35:27 +000063 public:
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000064 JITMemoryManager(bool useGOT);
Reid Spencer4af3da62004-12-13 16:04:04 +000065 ~JITMemoryManager();
Misha Brukmanf976c852005-04-21 22:55:34 +000066
Chris Lattner688506d2003-08-14 18:35:27 +000067 inline unsigned char *allocateStub(unsigned StubSize);
Chris Lattner281a6012005-01-10 18:23:22 +000068 inline unsigned char *allocateConstant(unsigned ConstantSize,
69 unsigned Alignment);
Chris Lattner688506d2003-08-14 18:35:27 +000070 inline unsigned char *startFunctionBody();
Chris Lattner281a6012005-01-10 18:23:22 +000071 inline void endFunctionBody(unsigned char *FunctionEnd);
Chris Lattnera726c7f2006-05-02 21:44:14 +000072
73 unsigned char *getGOTBase() const {
74 return GOTBase;
75 }
76 bool isManagingGOT() const {
77 return GOTBase != NULL;
78 }
Chris Lattner688506d2003-08-14 18:35:27 +000079 };
80}
81
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000082JITMemoryManager::JITMemoryManager(bool useGOT) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +000083 // Allocate a 16M block of memory for functions
84 sys::MemoryBlock FunBlock = getNewMemoryBlock(16 << 20);
85 // Allocate a 1M block of memory for Constants
86 sys::MemoryBlock ConstBlock = getNewMemoryBlock(1 << 20);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000087
Andrew Lenhartha00269b2005-07-29 23:40:16 +000088 Blocks.push_front(FunBlock);
89 Blocks.push_front(ConstBlock);
Chris Lattner688506d2003-08-14 18:35:27 +000090
Andrew Lenhartha00269b2005-07-29 23:40:16 +000091 FunctionBase = reinterpret_cast<unsigned char*>(FunBlock.base());
92 ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
Chris Lattner281a6012005-01-10 18:23:22 +000093
Andrew Lenhartha00269b2005-07-29 23:40:16 +000094 // Allocate stubs backwards from the base, allocate functions forward
95 // from the base.
96 CurStubPtr = CurFunctionPtr = FunctionBase + 512*1024;// Use 512k for stubs
97
98 CurConstantPtr = ConstantBase + ConstBlock.size();
Andrew Lenharth2b3b89c2005-08-01 17:35:40 +000099
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000100 // Allocate the GOT.
Andrew Lenharth2b3b89c2005-08-01 17:35:40 +0000101 GOTBase = NULL;
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000102 if (useGOT) GOTBase = (unsigned char*)malloc(sizeof(void*) * 8192);
Chris Lattner688506d2003-08-14 18:35:27 +0000103}
104
Reid Spencer4af3da62004-12-13 16:04:04 +0000105JITMemoryManager::~JITMemoryManager() {
Chris Lattner21998772006-01-07 06:20:51 +0000106 for (std::list<sys::MemoryBlock>::iterator ib = Blocks.begin(),
107 ie = Blocks.end(); ib != ie; ++ib)
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000108 sys::Memory::ReleaseRWX(*ib);
109 Blocks.clear();
Reid Spencer4af3da62004-12-13 16:04:04 +0000110}
111
Chris Lattner688506d2003-08-14 18:35:27 +0000112unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
113 CurStubPtr -= StubSize;
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000114 if (CurStubPtr < FunctionBase) {
Chris Lattnera726c7f2006-05-02 21:44:14 +0000115 // FIXME: allocate a new block
Chris Lattner688506d2003-08-14 18:35:27 +0000116 std::cerr << "JIT ran out of memory for function stubs!\n";
117 abort();
118 }
119 return CurStubPtr;
120}
121
Chris Lattner281a6012005-01-10 18:23:22 +0000122unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
123 unsigned Alignment) {
124 // Reserve space and align pointer.
125 CurConstantPtr -= ConstantSize;
126 CurConstantPtr =
127 (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
128
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000129 if (CurConstantPtr < ConstantBase) {
130 //Either allocate another MB or 2xConstantSize
131 sys::MemoryBlock ConstBlock = getNewMemoryBlock(2 * ConstantSize);
132 ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
133 CurConstantPtr = ConstantBase + ConstBlock.size();
134 return allocateConstant(ConstantSize, Alignment);
Chris Lattner281a6012005-01-10 18:23:22 +0000135 }
136 return CurConstantPtr;
137}
138
Chris Lattner688506d2003-08-14 18:35:27 +0000139unsigned char *JITMemoryManager::startFunctionBody() {
Chris Lattner5be478f2004-11-20 03:46:14 +0000140 // Round up to an even multiple of 8 bytes, this should eventually be target
Chris Lattner688506d2003-08-14 18:35:27 +0000141 // specific.
Chris Lattner5be478f2004-11-20 03:46:14 +0000142 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
Chris Lattner688506d2003-08-14 18:35:27 +0000143}
144
145void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
146 assert(FunctionEnd > CurFunctionPtr);
147 CurFunctionPtr = FunctionEnd;
148}
149
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000150sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
151 const sys::MemoryBlock* BOld = 0;
152 if (Blocks.size())
153 BOld = &Blocks.front();
154 //never allocate less than 1 MB
155 sys::MemoryBlock B;
156 try {
157 B = sys::Memory::AllocateRWX(std::max(((unsigned)1 << 20), size), BOld);
158 } catch (std::string& err) {
159 std::cerr << "Allocation failed when allocating new memory in the JIT\n";
160 std::cerr << err << "\n";
161 abort();
162 }
163 Blocks.push_front(B);
164 return B;
165}
166
Chris Lattner54266522004-11-20 23:57:07 +0000167//===----------------------------------------------------------------------===//
168// JIT lazy compilation code.
169//
170namespace {
Reid Spenceree448632005-07-12 15:51:55 +0000171 class JITResolverState {
172 private:
173 /// FunctionToStubMap - Keep track of the stub created for a particular
174 /// function so that we can reuse them if necessary.
175 std::map<Function*, void*> FunctionToStubMap;
176
177 /// StubToFunctionMap - Keep track of the function that each stub
178 /// corresponds to.
179 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +0000180
Reid Spenceree448632005-07-12 15:51:55 +0000181 public:
182 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
183 assert(locked.holds(TheJIT->lock));
184 return FunctionToStubMap;
185 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000186
Reid Spenceree448632005-07-12 15:51:55 +0000187 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
188 assert(locked.holds(TheJIT->lock));
189 return StubToFunctionMap;
190 }
191 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000192
Chris Lattner54266522004-11-20 23:57:07 +0000193 /// JITResolver - Keep track of, and resolve, call sites for functions that
194 /// have not yet been compiled.
195 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +0000196 /// MCE - The MachineCodeEmitter to use to emit stubs with.
Chris Lattner54266522004-11-20 23:57:07 +0000197 MachineCodeEmitter &MCE;
198
Chris Lattner5e225582004-11-21 03:37:42 +0000199 /// LazyResolverFn - The target lazy resolver function that we actually
200 /// rewrite instructions to use.
201 TargetJITInfo::LazyResolverFn LazyResolverFn;
202
Reid Spenceree448632005-07-12 15:51:55 +0000203 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000204
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000205 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
206 /// external functions.
207 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000208
209 //map addresses to indexes in the GOT
210 std::map<void*, unsigned> revGOTMap;
211 unsigned nextGOTIndex;
212
Chris Lattner54266522004-11-20 23:57:07 +0000213 public:
Andrew Lenharth6a974612005-07-28 12:44:13 +0000214 JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
Chris Lattner5e225582004-11-21 03:37:42 +0000215 LazyResolverFn =
216 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
217 }
Chris Lattner54266522004-11-20 23:57:07 +0000218
219 /// getFunctionStub - This returns a pointer to a function stub, creating
220 /// one on demand as needed.
221 void *getFunctionStub(Function *F);
222
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000223 /// getExternalFunctionStub - Return a stub for the function at the
224 /// specified address, created lazily on demand.
225 void *getExternalFunctionStub(void *FnAddr);
226
Chris Lattner5e225582004-11-21 03:37:42 +0000227 /// AddCallbackAtLocation - If the target is capable of rewriting an
228 /// instruction without the use of a stub, record the location of the use so
229 /// we know which function is being used at the location.
230 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000231 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000232 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000233 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner5e225582004-11-21 03:37:42 +0000234 return (void*)LazyResolverFn;
235 }
236
Andrew Lenharth6a974612005-07-28 12:44:13 +0000237 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
238 /// and address. This function only manages slots, it does not manage the
239 /// contents of the slots or the memory associated with the GOT.
240 unsigned getGOTIndexForAddr(void* addr);
241
Chris Lattner54266522004-11-20 23:57:07 +0000242 /// JITCompilerFn - This function is called to resolve a stub to a compiled
243 /// address. If the LLVM Function corresponding to the stub has not yet
244 /// been compiled, this function compiles it first.
245 static void *JITCompilerFn(void *Stub);
246 };
247}
248
249/// getJITResolver - This function returns the one instance of the JIT resolver.
250///
251static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
252 static JITResolver TheJITResolver(*MCE);
253 return TheJITResolver;
254}
255
256/// getFunctionStub - This returns a pointer to a function stub, creating
257/// one on demand as needed.
258void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000259 MutexGuard locked(TheJIT->lock);
260
Chris Lattner54266522004-11-20 23:57:07 +0000261 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000262 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000263 if (Stub) return Stub;
264
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000265 // Call the lazy resolver function unless we already KNOW it is an external
266 // function, in which case we just skip the lazy resolution step.
267 void *Actual = (void*)LazyResolverFn;
Chris Lattner69435702005-02-20 18:43:35 +0000268 if (F->isExternal() && F->hasExternalLinkage())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000269 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000270
Chris Lattner54266522004-11-20 23:57:07 +0000271 // Otherwise, codegen a new stub. For now, the stub will call the lazy
272 // resolver function.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000273 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
274
Chris Lattner69435702005-02-20 18:43:35 +0000275 if (Actual != (void*)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000276 // If we are getting the stub for an external function, we really want the
277 // address of the stub in the GlobalAddressMap for the JIT, not the address
278 // of the external function.
279 TheJIT->updateGlobalMapping(F, Stub);
280 }
Chris Lattner54266522004-11-20 23:57:07 +0000281
Chris Lattnercb479412004-11-21 03:44:32 +0000282 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
Chris Lattner6f717202004-11-22 21:48:33 +0000283 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000284
Chris Lattner54266522004-11-20 23:57:07 +0000285 // Finally, keep track of the stub-to-Function mapping so that the
286 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000287 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000288 return Stub;
289}
290
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000291/// getExternalFunctionStub - Return a stub for the function at the
292/// specified address, created lazily on demand.
293void *JITResolver::getExternalFunctionStub(void *FnAddr) {
294 // If we already have a stub for this function, recycle it.
295 void *&Stub = ExternalFnToStubMap[FnAddr];
296 if (Stub) return Stub;
297
298 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
299 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
300 << "] for external function at '" << FnAddr << "'\n");
301 return Stub;
302}
303
Andrew Lenharth6a974612005-07-28 12:44:13 +0000304unsigned JITResolver::getGOTIndexForAddr(void* addr) {
305 unsigned idx = revGOTMap[addr];
306 if (!idx) {
307 idx = ++nextGOTIndex;
308 revGOTMap[addr] = idx;
309 DEBUG(std::cerr << "Adding GOT entry " << idx
310 << " for addr " << addr << "\n");
311 // ((void**)MemMgr.getGOTBase())[idx] = addr;
312 }
313 return idx;
314}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000315
Chris Lattner54266522004-11-20 23:57:07 +0000316/// JITCompilerFn - This function is called when a lazy compilation stub has
317/// been entered. It looks up which function this stub corresponds to, compiles
318/// it if necessary, then returns the resultant function pointer.
319void *JITResolver::JITCompilerFn(void *Stub) {
320 JITResolver &JR = getJITResolver();
Misha Brukmanf976c852005-04-21 22:55:34 +0000321
Reid Spenceree448632005-07-12 15:51:55 +0000322 MutexGuard locked(TheJIT->lock);
323
Chris Lattner54266522004-11-20 23:57:07 +0000324 // The address given to us for the stub may not be exactly right, it might be
325 // a little bit after the stub. As such, use upper_bound to find it.
326 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000327 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
Chris Lattner21998772006-01-07 06:20:51 +0000328 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
329 "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000330 Function *F = (--I)->second;
331
Reid Spenceree448632005-07-12 15:51:55 +0000332 // We might like to remove the stub from the StubToFunction map.
333 // We can't do that! Multiple threads could be stuck, waiting to acquire the
334 // lock above. As soon as the 1st function finishes compiling the function,
Chris Lattner21998772006-01-07 06:20:51 +0000335 // the next one will be released, and needs to be able to find the function it
336 // needs to call.
Reid Spenceree448632005-07-12 15:51:55 +0000337 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000338
Chris Lattnercb479412004-11-21 03:44:32 +0000339 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
Chris Lattner54266522004-11-20 23:57:07 +0000340 << "' In stub ptr = " << Stub << " actual ptr = "
341 << I->first << "\n");
342
343 void *Result = TheJIT->getPointerToFunction(F);
344
345 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000346 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000347
348 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000349
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000350 // What we will do is set the compiled function address to map to the
351 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000352 // if they see it still using the stub address.
353 // Note: this is done so the Resolver doesn't have to manage GOT memory
354 // Do this without allocating map space if the target isn't using a GOT
355 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
356 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
357
Chris Lattner54266522004-11-20 23:57:07 +0000358 return Result;
359}
Chris Lattner688506d2003-08-14 18:35:27 +0000360
361
Chris Lattnere518b712004-12-05 07:19:16 +0000362// getPointerToFunctionOrStub - If the specified function has been
363// code-gen'd, return a pointer to the function. If not, compile it, or use
364// a stub to implement lazy compilation if available.
365//
366void *JIT::getPointerToFunctionOrStub(Function *F) {
367 // If we have already code generated the function, just return the address.
368 if (void *Addr = getPointerToGlobalIfAvailable(F))
369 return Addr;
370
371 // Get a stub if the target supports it
372 return getJITResolver(MCE).getFunctionStub(F);
373}
374
375
376
Chris Lattner54266522004-11-20 23:57:07 +0000377//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000378// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000379//
Chris Lattner688506d2003-08-14 18:35:27 +0000380namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000381 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
382 /// used to output functions to memory for execution.
383 class JITEmitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000384 JITMemoryManager MemMgr;
385
Chris Lattner6125fdd2003-05-09 03:30:07 +0000386 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000387 // save BufferBegin/BufferEnd/CurBufferPtr here.
388 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000389
Chris Lattner5be478f2004-11-20 03:46:14 +0000390 /// Relocations - These are the relocations that the function needs, as
391 /// emitted.
392 std::vector<MachineRelocation> Relocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000393
Chris Lattner239862c2006-02-09 04:49:59 +0000394 /// ConstantPool - The constant pool for the current function.
395 ///
396 MachineConstantPool *ConstantPool;
397
398 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
399 ///
400 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000401
402 /// ConstantPool - The constant pool for the current function.
403 ///
404 MachineJumpTableInfo *JumpTable;
405
406 /// JumpTableBase - A pointer to the first entry in the jump table.
407 ///
408 void *JumpTableBase;
409public:
Chris Lattner239862c2006-02-09 04:49:59 +0000410 JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
Jeff Cohen00b168892005-07-27 06:12:32 +0000411 TheJIT = &jit;
Chris Lattnera726c7f2006-05-02 21:44:14 +0000412 DEBUG(if (MemMgr.isManagingGOT()) std::cerr << "JIT is managing a GOT\n");
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000413 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000414
415 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000416 virtual bool finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000417 virtual void emitConstantPool(MachineConstantPool *MCP);
Nate Begeman37efe672006-04-22 18:53:45 +0000418 virtual void initJumpTableInfo(MachineJumpTableInfo *MJTI);
419 virtual void emitJumpTableInfo(MachineJumpTableInfo *MJTI,
420 std::map<MachineBasicBlock*,uint64_t> &MBBM);
Chris Lattner54266522004-11-20 23:57:07 +0000421 virtual void startFunctionStub(unsigned StubSize);
422 virtual void* finishFunctionStub(const Function *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000423
Chris Lattner5be478f2004-11-20 03:46:14 +0000424 virtual void addRelocation(const MachineRelocation &MR) {
425 Relocations.push_back(MR);
426 }
427
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000428 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
Nate Begeman37efe672006-04-22 18:53:45 +0000429 virtual uint64_t getJumpTableEntryAddress(unsigned Entry);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000430
Chris Lattner54266522004-11-20 23:57:07 +0000431 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000432 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000433 };
434}
435
Chris Lattner4d326fa2003-12-20 01:46:27 +0000436MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
Chris Lattner166f2262004-11-22 22:00:25 +0000437 return new JITEmitter(jit);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000438}
439
Chris Lattner166f2262004-11-22 22:00:25 +0000440void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
441 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000442 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
443 /// FIXME: If we straightened things out, this could actually emit the
444 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000445 return TheJIT->getOrEmitGlobalVariable(GV);
446 }
447
448 // If we have already compiled the function, return a pointer to its body.
449 Function *F = cast<Function>(V);
450 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
451 if (ResultPtr) return ResultPtr;
452
Chris Lattner532343b2004-11-30 17:41:49 +0000453 if (F->hasExternalLinkage() && F->isExternal()) {
Chris Lattner54266522004-11-20 23:57:07 +0000454 // If this is an external function pointer, we can force the JIT to
455 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000456 if (DoesntNeedStub)
457 return TheJIT->getPointerToFunction(F);
458
459 return getJITResolver(this).getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000460 }
461
Chris Lattner5e225582004-11-21 03:37:42 +0000462 // Okay, the function has not been compiled yet, if the target callback
463 // mechanism is capable of rewriting the instruction directly, prefer to do
464 // that instead of emitting a stub.
465 if (DoesntNeedStub)
466 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
467
Chris Lattner54266522004-11-20 23:57:07 +0000468 // Otherwise, we have to emit a lazy resolving stub.
469 return getJITResolver(this).getFunctionStub(F);
470}
471
Chris Lattner166f2262004-11-22 22:00:25 +0000472void JITEmitter::startFunction(MachineFunction &F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000473 BufferBegin = CurBufferPtr = MemMgr.startFunctionBody();
474 TheJIT->updateGlobalMapping(F.getFunction(), BufferBegin);
475
476 /// FIXME: implement out of space handling correctly!
477 BufferEnd = (unsigned char*)(intptr_t)~0ULL;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000478}
479
Chris Lattner43b429b2006-05-02 18:27:26 +0000480bool JITEmitter::finishFunction(MachineFunction &F) {
481 MemMgr.endFunctionBody(CurBufferPtr);
482 NumBytes += getCurrentPCOffset();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000483
Chris Lattner5be478f2004-11-20 03:46:14 +0000484 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000485 NumRelos += Relocations.size();
486
Chris Lattner5be478f2004-11-20 03:46:14 +0000487 // Resolve the relocations to concrete pointers.
488 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
489 MachineRelocation &MR = Relocations[i];
490 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000491 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000492 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000493
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000494 // If the target REALLY wants a stub for this function, emit it now.
495 if (!MR.doesntNeedFunctionStub())
496 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
Jeff Cohen00b168892005-07-27 06:12:32 +0000497 } else if (MR.isGlobalValue())
Chris Lattner5e225582004-11-21 03:37:42 +0000498 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
Chris Lattner43b429b2006-05-02 18:27:26 +0000499 BufferBegin+MR.getMachineCodeOffset(),
Chris Lattner5e225582004-11-21 03:37:42 +0000500 MR.doesntNeedFunctionStub());
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000501 else //ConstantPoolIndex
Jeff Cohen00b168892005-07-27 06:12:32 +0000502 ResultPtr =
Chris Lattnerd6bbac52005-07-25 23:42:58 +0000503 (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Jeff Cohen00b168892005-07-27 06:12:32 +0000504
Chris Lattner5be478f2004-11-20 03:46:14 +0000505 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000506
Andrew Lenharth6a974612005-07-28 12:44:13 +0000507 // if we are managing the GOT and the relocation wants an index,
508 // give it one
509 if (MemMgr.isManagingGOT() && !MR.isConstantPoolIndex() &&
510 MR.isGOTRelative()) {
511 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
512 MR.setGOTIndex(idx);
513 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
514 DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
Chris Lattner21998772006-01-07 06:20:51 +0000515 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
516 << "\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000517 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
518 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000519 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000520 }
521
Chris Lattner43b429b2006-05-02 18:27:26 +0000522 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000523 Relocations.size(), MemMgr.getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000524 }
525
Andrew Lenharth6a974612005-07-28 12:44:13 +0000526 //Update the GOT entry for F to point to the new code.
527 if(MemMgr.isManagingGOT()) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000528 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)BufferBegin);
529 if (((void**)MemMgr.getGOTBase())[idx] != (void*)BufferBegin) {
530 DEBUG(std::cerr << "GOT was out of date for " << (void*)BufferBegin
Andrew Lenharth6a974612005-07-28 12:44:13 +0000531 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
Chris Lattner43b429b2006-05-02 18:27:26 +0000532 ((void**)MemMgr.getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000533 }
534 }
535
Chris Lattner43b429b2006-05-02 18:27:26 +0000536 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)BufferBegin
Misha Brukman1d440852003-06-06 06:52:35 +0000537 << "] Function: " << F.getFunction()->getName()
Chris Lattner43b429b2006-05-02 18:27:26 +0000538 << ": " << getCurrentPCOffset() << " bytes of text, "
Chris Lattner5be478f2004-11-20 03:46:14 +0000539 << Relocations.size() << " relocations\n");
540 Relocations.clear();
Chris Lattner43b429b2006-05-02 18:27:26 +0000541 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000542}
543
Chris Lattner166f2262004-11-22 22:00:25 +0000544void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000545 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000546 if (Constants.empty()) return;
547
Chris Lattner3029f922006-02-09 04:46:04 +0000548 unsigned Size = Constants.back().Offset;
549 Size += TheJIT->getTargetData().getTypeSize(Constants.back().Val->getType());
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000550
Chris Lattner239862c2006-02-09 04:49:59 +0000551 ConstantPoolBase = MemMgr.allocateConstant(Size,
Chris Lattner3029f922006-02-09 04:46:04 +0000552 1 << MCP->getConstantPoolAlignment());
Chris Lattner239862c2006-02-09 04:49:59 +0000553 ConstantPool = MCP;
554
555 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +0000556 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +0000557 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Chris Lattner3029f922006-02-09 04:46:04 +0000558 TheJIT->InitializeMemory(Constants[i].Val, CAddr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000559 }
560}
561
Nate Begeman37efe672006-04-22 18:53:45 +0000562void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
563 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
564 if (JT.empty()) return;
565
566 unsigned Size = 0;
567 unsigned EntrySize = MJTI->getEntrySize();
568 for (unsigned i = 0, e = JT.size(); i != e; ++i)
569 Size += JT[i].MBBs.size() * EntrySize;
570
571 // Just allocate space for all the jump tables now. We will fix up the actual
572 // MBB entries in the tables after we emit the code for each block, since then
573 // we will know the final locations of the MBBs in memory.
574 JumpTable = MJTI;
575 JumpTableBase = MemMgr.allocateConstant(Size, MJTI->getAlignment());
576}
577
578void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI,
579 std::map<MachineBasicBlock*,uint64_t> &MBBM){
580 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
581 if (JT.empty()) return;
582
583 unsigned Offset = 0;
584 unsigned EntrySize = MJTI->getEntrySize();
585
586 // For each jump table, map each target in the jump table to the address of
587 // an emitted MachineBasicBlock.
588 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
589 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
590 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
591 uint64_t addr = MBBM[MBBs[mi]];
592 GenericValue addrgv;
593 const Type *Ty;
594 if (EntrySize == 4) {
595 addrgv.UIntVal = addr;
596 Ty = Type::UIntTy;
597 } else if (EntrySize == 8) {
598 addrgv.ULongVal = addr;
599 Ty = Type::ULongTy;
600 } else {
601 assert(0 && "Unhandled jump table entry size!");
602 abort();
603 }
604 // Store the address of the basic block for this jump table slot in the
605 // memory we allocated for the jump table in 'initJumpTableInfo'
606 void *ptr = (void *)((char *)JumpTableBase + Offset);
607 TheJIT->StoreValueToMemory(addrgv, (GenericValue *)ptr, Ty);
608 Offset += EntrySize;
609 }
610 }
611}
612
Chris Lattner166f2262004-11-22 22:00:25 +0000613void JITEmitter::startFunctionStub(unsigned StubSize) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000614 SavedBufferBegin = BufferBegin;
615 SavedBufferEnd = BufferEnd;
616 SavedCurBufferPtr = CurBufferPtr;
617
618 BufferBegin = CurBufferPtr = MemMgr.allocateStub(StubSize);
619 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000620}
621
Chris Lattner166f2262004-11-22 22:00:25 +0000622void *JITEmitter::finishFunctionStub(const Function *F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000623 NumBytes += getCurrentPCOffset();
624 std::swap(SavedBufferBegin, BufferBegin);
625 BufferEnd = SavedBufferEnd;
626 CurBufferPtr = SavedCurBufferPtr;
627 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000628}
629
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000630// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
631// in the constant pool that was last emitted with the 'emitConstantPool'
632// method.
633//
Chris Lattner166f2262004-11-22 22:00:25 +0000634uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
Chris Lattner239862c2006-02-09 04:49:59 +0000635 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000636 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +0000637 return (intptr_t)ConstantPoolBase +
638 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000639}
640
Nate Begeman37efe672006-04-22 18:53:45 +0000641// getJumpTableEntryAddress - Return the address of the JumpTable with index
642// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
643//
644uint64_t JITEmitter::getJumpTableEntryAddress(unsigned Index) {
645 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
646 assert(Index < JT.size() && "Invalid jump table index!");
647
648 unsigned Offset = 0;
649 unsigned EntrySize = JumpTable->getEntrySize();
650
651 for (unsigned i = 0; i < Index; ++i)
652 Offset += JT[i].MBBs.size() * EntrySize;
653
Nate Begemanc34b2272006-04-25 17:46:32 +0000654 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +0000655}
656
Misha Brukmand69c1e62003-07-28 19:09:06 +0000657// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000658// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000659// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
660// need to resolve function(s) that are being mis-codegenerated, so we need to
661// resolve their addresses at runtime, and this is the way to do it.
662extern "C" {
663 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000664 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000665 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000666 return TheJIT->getPointerToFunction(F);
667 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000668 }
669}