blob: 0d47a97e2fa3a3f38ef6815591093e688fae1946 [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"
Chris Lattner5be478f2004-11-20 03:46:14 +000023#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000024#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000025#include "llvm/Target/TargetJITInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/Support/Debug.h"
27#include "llvm/ADT/Statistic.h"
Reid Spencer52b0ba62004-09-11 04:31:03 +000028#include "llvm/System/Memory.h"
Chris Lattnerc19aade2003-12-08 08:06:28 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattnerbd199fb2002-12-24 00:01:05 +000031namespace {
Chris Lattnere7386562003-10-20 05:45:49 +000032 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
Chris Lattnere884dc22005-07-20 16:29:20 +000033 Statistic<> NumRelos("jit", "Number of relocations applied");
Chris Lattner4d326fa2003-12-20 01:46:27 +000034 JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000035}
Chris Lattnerbd199fb2002-12-24 00:01:05 +000036
Chris Lattner54266522004-11-20 23:57:07 +000037
38//===----------------------------------------------------------------------===//
39// JITMemoryManager code.
40//
41namespace {
Chris Lattner688506d2003-08-14 18:35:27 +000042 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
43 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
44 /// sections, one for function stubs, one for the functions themselves. We
45 /// have to do this because we may need to emit a function stub while in the
46 /// middle of emitting a function, and we don't know how large the function we
47 /// are emitting is. This never bothers to release the memory, because when
48 /// we are ready to destroy the JIT, the program exits.
49 class JITMemoryManager {
Reid Spencer33189e72004-09-13 22:38:11 +000050 sys::MemoryBlock MemBlock; // Virtual memory block allocated RWX
Chris Lattner688506d2003-08-14 18:35:27 +000051 unsigned char *MemBase; // Base of block of memory, start of stub mem
52 unsigned char *FunctionBase; // Start of the function body area
Chris Lattner281a6012005-01-10 18:23:22 +000053 unsigned char *ConstantPool; // Memory allocated for constant pools
54 unsigned char *CurStubPtr, *CurFunctionPtr, *CurConstantPtr;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000055 unsigned char *GOTBase; //Target Specific reserved memory
Chris Lattner688506d2003-08-14 18:35:27 +000056 public:
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000057 JITMemoryManager(bool useGOT);
Reid Spencer4af3da62004-12-13 16:04:04 +000058 ~JITMemoryManager();
Misha Brukmanf976c852005-04-21 22:55:34 +000059
Chris Lattner688506d2003-08-14 18:35:27 +000060 inline unsigned char *allocateStub(unsigned StubSize);
Chris Lattner281a6012005-01-10 18:23:22 +000061 inline unsigned char *allocateConstant(unsigned ConstantSize,
62 unsigned Alignment);
Andrew Lenharth6a974612005-07-28 12:44:13 +000063 inline unsigned char* allocateGlobal(unsigned Size,
64 unsigned Alignment);
Chris Lattner688506d2003-08-14 18:35:27 +000065 inline unsigned char *startFunctionBody();
Chris Lattner281a6012005-01-10 18:23:22 +000066 inline void endFunctionBody(unsigned char *FunctionEnd);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000067 inline unsigned char* getGOTBase() const;
68
69 inline bool isManagingGOT() const;
Chris Lattner688506d2003-08-14 18:35:27 +000070 };
71}
72
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000073JITMemoryManager::JITMemoryManager(bool useGOT) {
Chris Lattner688506d2003-08-14 18:35:27 +000074 // Allocate a 16M block of memory...
Reid Spencer33189e72004-09-13 22:38:11 +000075 MemBlock = sys::Memory::AllocateRWX((16 << 20));
Reid Spencer52b0ba62004-09-11 04:31:03 +000076 MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000077 ConstantPool = MemBase;
78 GOTBase = ConstantPool + 512*1024; //512 for constants
79 //8k number of entries in the GOT
80 FunctionBase = GOTBase + 8192 * sizeof(void*) + 512*1024; // Use 512k for stubs
81
82 //make it easier to tell if we are managing the GOT
83 if (!useGOT)
84 GOTBase = NULL;
Chris Lattner688506d2003-08-14 18:35:27 +000085
86 // Allocate stubs backwards from the function base, allocate functions forward
87 // from the function base.
88 CurStubPtr = CurFunctionPtr = FunctionBase;
Chris Lattner281a6012005-01-10 18:23:22 +000089
Chris Lattner281a6012005-01-10 18:23:22 +000090 CurConstantPtr = ConstantPool + 512*1024;
Chris Lattner688506d2003-08-14 18:35:27 +000091}
92
Reid Spencer4af3da62004-12-13 16:04:04 +000093JITMemoryManager::~JITMemoryManager() {
94 sys::Memory::ReleaseRWX(MemBlock);
95}
96
Chris Lattner688506d2003-08-14 18:35:27 +000097unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
98 CurStubPtr -= StubSize;
99 if (CurStubPtr < MemBase) {
100 std::cerr << "JIT ran out of memory for function stubs!\n";
101 abort();
102 }
103 return CurStubPtr;
104}
105
Chris Lattner281a6012005-01-10 18:23:22 +0000106unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
107 unsigned Alignment) {
108 // Reserve space and align pointer.
109 CurConstantPtr -= ConstantSize;
110 CurConstantPtr =
111 (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
112
113 if (CurConstantPtr < ConstantPool) {
114 std::cerr << "JIT ran out of memory for constant pools!\n";
115 abort();
116 }
117 return CurConstantPtr;
118}
119
Andrew Lenharth6a974612005-07-28 12:44:13 +0000120unsigned char *JITMemoryManager::allocateGlobal(unsigned Size,
121 unsigned Alignment) {
122 // For now, intersperse them with Constants
123 // Reserve space and align pointer.
124 CurConstantPtr -= Size;
125 CurConstantPtr =
126 (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
127
128 if (CurConstantPtr < ConstantPool) {
129 std::cerr << "JIT ran out of memory for Globals!\n";
130 abort();
131 }
132 return CurConstantPtr;
133}
134
Chris Lattner688506d2003-08-14 18:35:27 +0000135unsigned char *JITMemoryManager::startFunctionBody() {
Chris Lattner5be478f2004-11-20 03:46:14 +0000136 // Round up to an even multiple of 8 bytes, this should eventually be target
Chris Lattner688506d2003-08-14 18:35:27 +0000137 // specific.
Chris Lattner5be478f2004-11-20 03:46:14 +0000138 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
Chris Lattner688506d2003-08-14 18:35:27 +0000139}
140
141void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
142 assert(FunctionEnd > CurFunctionPtr);
143 CurFunctionPtr = FunctionEnd;
144}
145
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000146unsigned char* JITMemoryManager::getGOTBase() const {
147 return GOTBase;
148}
149
150bool JITMemoryManager::isManagingGOT() const {
151 return GOTBase != NULL;
152}
153
Chris Lattner54266522004-11-20 23:57:07 +0000154//===----------------------------------------------------------------------===//
155// JIT lazy compilation code.
156//
157namespace {
Reid Spenceree448632005-07-12 15:51:55 +0000158 class JITResolverState {
159 private:
160 /// FunctionToStubMap - Keep track of the stub created for a particular
161 /// function so that we can reuse them if necessary.
162 std::map<Function*, void*> FunctionToStubMap;
163
164 /// StubToFunctionMap - Keep track of the function that each stub
165 /// corresponds to.
166 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +0000167
Reid Spenceree448632005-07-12 15:51:55 +0000168 public:
169 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
170 assert(locked.holds(TheJIT->lock));
171 return FunctionToStubMap;
172 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000173
Reid Spenceree448632005-07-12 15:51:55 +0000174 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
175 assert(locked.holds(TheJIT->lock));
176 return StubToFunctionMap;
177 }
178 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000179
Chris Lattner54266522004-11-20 23:57:07 +0000180 /// JITResolver - Keep track of, and resolve, call sites for functions that
181 /// have not yet been compiled.
182 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +0000183 /// MCE - The MachineCodeEmitter to use to emit stubs with.
Chris Lattner54266522004-11-20 23:57:07 +0000184 MachineCodeEmitter &MCE;
185
Chris Lattner5e225582004-11-21 03:37:42 +0000186 /// LazyResolverFn - The target lazy resolver function that we actually
187 /// rewrite instructions to use.
188 TargetJITInfo::LazyResolverFn LazyResolverFn;
189
Reid Spenceree448632005-07-12 15:51:55 +0000190 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000191
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000192 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
193 /// external functions.
194 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000195
196 //map addresses to indexes in the GOT
197 std::map<void*, unsigned> revGOTMap;
198 unsigned nextGOTIndex;
199
Chris Lattner54266522004-11-20 23:57:07 +0000200 public:
Andrew Lenharth6a974612005-07-28 12:44:13 +0000201 JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
Chris Lattner5e225582004-11-21 03:37:42 +0000202 LazyResolverFn =
203 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
204 }
Chris Lattner54266522004-11-20 23:57:07 +0000205
206 /// getFunctionStub - This returns a pointer to a function stub, creating
207 /// one on demand as needed.
208 void *getFunctionStub(Function *F);
209
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000210 /// getExternalFunctionStub - Return a stub for the function at the
211 /// specified address, created lazily on demand.
212 void *getExternalFunctionStub(void *FnAddr);
213
Chris Lattner5e225582004-11-21 03:37:42 +0000214 /// AddCallbackAtLocation - If the target is capable of rewriting an
215 /// instruction without the use of a stub, record the location of the use so
216 /// we know which function is being used at the location.
217 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000218 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000219 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000220 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner5e225582004-11-21 03:37:42 +0000221 return (void*)LazyResolverFn;
222 }
223
Andrew Lenharth6a974612005-07-28 12:44:13 +0000224 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
225 /// and address. This function only manages slots, it does not manage the
226 /// contents of the slots or the memory associated with the GOT.
227 unsigned getGOTIndexForAddr(void* addr);
228
Chris Lattner54266522004-11-20 23:57:07 +0000229 /// JITCompilerFn - This function is called to resolve a stub to a compiled
230 /// address. If the LLVM Function corresponding to the stub has not yet
231 /// been compiled, this function compiles it first.
232 static void *JITCompilerFn(void *Stub);
233 };
234}
235
236/// getJITResolver - This function returns the one instance of the JIT resolver.
237///
238static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
239 static JITResolver TheJITResolver(*MCE);
240 return TheJITResolver;
241}
242
243/// getFunctionStub - This returns a pointer to a function stub, creating
244/// one on demand as needed.
245void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000246 MutexGuard locked(TheJIT->lock);
247
Chris Lattner54266522004-11-20 23:57:07 +0000248 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000249 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000250 if (Stub) return Stub;
251
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000252 // Call the lazy resolver function unless we already KNOW it is an external
253 // function, in which case we just skip the lazy resolution step.
254 void *Actual = (void*)LazyResolverFn;
Chris Lattner69435702005-02-20 18:43:35 +0000255 if (F->isExternal() && F->hasExternalLinkage())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000256 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000257
Chris Lattner54266522004-11-20 23:57:07 +0000258 // Otherwise, codegen a new stub. For now, the stub will call the lazy
259 // resolver function.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000260 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
261
Chris Lattner69435702005-02-20 18:43:35 +0000262 if (Actual != (void*)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000263 // If we are getting the stub for an external function, we really want the
264 // address of the stub in the GlobalAddressMap for the JIT, not the address
265 // of the external function.
266 TheJIT->updateGlobalMapping(F, Stub);
267 }
Chris Lattner54266522004-11-20 23:57:07 +0000268
Chris Lattnercb479412004-11-21 03:44:32 +0000269 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
Chris Lattner6f717202004-11-22 21:48:33 +0000270 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000271
Chris Lattner54266522004-11-20 23:57:07 +0000272 // Finally, keep track of the stub-to-Function mapping so that the
273 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000274 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000275 return Stub;
276}
277
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000278/// getExternalFunctionStub - Return a stub for the function at the
279/// specified address, created lazily on demand.
280void *JITResolver::getExternalFunctionStub(void *FnAddr) {
281 // If we already have a stub for this function, recycle it.
282 void *&Stub = ExternalFnToStubMap[FnAddr];
283 if (Stub) return Stub;
284
285 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
286 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
287 << "] for external function at '" << FnAddr << "'\n");
288 return Stub;
289}
290
Andrew Lenharth6a974612005-07-28 12:44:13 +0000291unsigned JITResolver::getGOTIndexForAddr(void* addr) {
292 unsigned idx = revGOTMap[addr];
293 if (!idx) {
294 idx = ++nextGOTIndex;
295 revGOTMap[addr] = idx;
296 DEBUG(std::cerr << "Adding GOT entry " << idx
297 << " for addr " << addr << "\n");
298 // ((void**)MemMgr.getGOTBase())[idx] = addr;
299 }
300 return idx;
301}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000302
Chris Lattner54266522004-11-20 23:57:07 +0000303/// JITCompilerFn - This function is called when a lazy compilation stub has
304/// been entered. It looks up which function this stub corresponds to, compiles
305/// it if necessary, then returns the resultant function pointer.
306void *JITResolver::JITCompilerFn(void *Stub) {
307 JITResolver &JR = getJITResolver();
Misha Brukmanf976c852005-04-21 22:55:34 +0000308
Reid Spenceree448632005-07-12 15:51:55 +0000309 MutexGuard locked(TheJIT->lock);
310
Chris Lattner54266522004-11-20 23:57:07 +0000311 // The address given to us for the stub may not be exactly right, it might be
312 // a little bit after the stub. As such, use upper_bound to find it.
313 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000314 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
315 assert(I != JR.state.getStubToFunctionMap(locked).begin() && "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000316 Function *F = (--I)->second;
317
Reid Spenceree448632005-07-12 15:51:55 +0000318 // We might like to remove the stub from the StubToFunction map.
319 // We can't do that! Multiple threads could be stuck, waiting to acquire the
320 // lock above. As soon as the 1st function finishes compiling the function,
321 // the next one will be released, and needs to be able to find the function it needs
322 // to call.
323 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000324
Chris Lattnercb479412004-11-21 03:44:32 +0000325 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
Chris Lattner54266522004-11-20 23:57:07 +0000326 << "' In stub ptr = " << Stub << " actual ptr = "
327 << I->first << "\n");
328
329 void *Result = TheJIT->getPointerToFunction(F);
330
331 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000332 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000333
334 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000335
336 // What we will do is set the compiled function address to map to the
337 // same GOT entry as the stub so that later clients may update the GOT
338 // if they see it still using the stub address.
339 // Note: this is done so the Resolver doesn't have to manage GOT memory
340 // Do this without allocating map space if the target isn't using a GOT
341 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
342 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
343
Chris Lattner54266522004-11-20 23:57:07 +0000344 return Result;
345}
Chris Lattner688506d2003-08-14 18:35:27 +0000346
347
Chris Lattnere518b712004-12-05 07:19:16 +0000348// getPointerToFunctionOrStub - If the specified function has been
349// code-gen'd, return a pointer to the function. If not, compile it, or use
350// a stub to implement lazy compilation if available.
351//
352void *JIT::getPointerToFunctionOrStub(Function *F) {
353 // If we have already code generated the function, just return the address.
354 if (void *Addr = getPointerToGlobalIfAvailable(F))
355 return Addr;
356
357 // Get a stub if the target supports it
358 return getJITResolver(MCE).getFunctionStub(F);
359}
360
361
362
Chris Lattner54266522004-11-20 23:57:07 +0000363//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000364// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000365//
Chris Lattner688506d2003-08-14 18:35:27 +0000366namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000367 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
368 /// used to output functions to memory for execution.
369 class JITEmitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000370 JITMemoryManager MemMgr;
371
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000372 // CurBlock - The start of the current block of memory. CurByte - The
373 // current byte being emitted to.
Chris Lattner6125fdd2003-05-09 03:30:07 +0000374 unsigned char *CurBlock, *CurByte;
375
376 // When outputting a function stub in the context of some other function, we
377 // save CurBlock and CurByte here.
378 unsigned char *SavedCurBlock, *SavedCurByte;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000379
380 // ConstantPoolAddresses - Contains the location for each entry in the
381 // constant pool.
Chris Lattner1cc08382003-01-13 01:00:12 +0000382 std::vector<void*> ConstantPoolAddresses;
Chris Lattner5be478f2004-11-20 03:46:14 +0000383
384 /// Relocations - These are the relocations that the function needs, as
385 /// emitted.
386 std::vector<MachineRelocation> Relocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000387
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000388 public:
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000389 JITEmitter(JIT &jit)
Andrew Lenharth6a974612005-07-28 12:44:13 +0000390 :MemMgr(jit.getJITInfo().needsGOT())
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000391 {
Jeff Cohen00b168892005-07-27 06:12:32 +0000392 TheJIT = &jit;
393 DEBUG(std::cerr <<
394 (MemMgr.isManagingGOT() ? "JIT is managing GOT\n"
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000395 : "JIT is not managing GOT\n"));
396 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000397
398 virtual void startFunction(MachineFunction &F);
399 virtual void finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000400 virtual void emitConstantPool(MachineConstantPool *MCP);
Chris Lattner54266522004-11-20 23:57:07 +0000401 virtual void startFunctionStub(unsigned StubSize);
402 virtual void* finishFunctionStub(const Function *F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000403 virtual void emitByte(unsigned char B);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000404 virtual void emitWord(unsigned W);
Brian Gaekeaea1b582004-04-23 17:11:14 +0000405 virtual void emitWordAt(unsigned W, unsigned *Ptr);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000406
Chris Lattner5be478f2004-11-20 03:46:14 +0000407 virtual void addRelocation(const MachineRelocation &MR) {
408 Relocations.push_back(MR);
409 }
410
411 virtual uint64_t getCurrentPCValue();
412 virtual uint64_t getCurrentPCOffset();
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000413 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000414 virtual unsigned char* allocateGlobal(unsigned size, unsigned alignment);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000415
Chris Lattner54266522004-11-20 23:57:07 +0000416 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000417 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000418 };
419}
420
Chris Lattner4d326fa2003-12-20 01:46:27 +0000421MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
Chris Lattner166f2262004-11-22 22:00:25 +0000422 return new JITEmitter(jit);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000423}
424
Chris Lattner166f2262004-11-22 22:00:25 +0000425void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
426 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000427 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
428 /// FIXME: If we straightened things out, this could actually emit the
429 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000430 return TheJIT->getOrEmitGlobalVariable(GV);
431 }
432
433 // If we have already compiled the function, return a pointer to its body.
434 Function *F = cast<Function>(V);
435 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
436 if (ResultPtr) return ResultPtr;
437
Chris Lattner532343b2004-11-30 17:41:49 +0000438 if (F->hasExternalLinkage() && F->isExternal()) {
Chris Lattner54266522004-11-20 23:57:07 +0000439 // If this is an external function pointer, we can force the JIT to
440 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000441 if (DoesntNeedStub)
442 return TheJIT->getPointerToFunction(F);
443
444 return getJITResolver(this).getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000445 }
446
Chris Lattner5e225582004-11-21 03:37:42 +0000447 // Okay, the function has not been compiled yet, if the target callback
448 // mechanism is capable of rewriting the instruction directly, prefer to do
449 // that instead of emitting a stub.
450 if (DoesntNeedStub)
451 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
452
Chris Lattner54266522004-11-20 23:57:07 +0000453 // Otherwise, we have to emit a lazy resolving stub.
454 return getJITResolver(this).getFunctionStub(F);
455}
456
Chris Lattner166f2262004-11-22 22:00:25 +0000457void JITEmitter::startFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000458 CurByte = CurBlock = MemMgr.startFunctionBody();
Chris Lattner4d326fa2003-12-20 01:46:27 +0000459 TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000460}
461
Chris Lattner166f2262004-11-22 22:00:25 +0000462void JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000463 MemMgr.endFunctionBody(CurByte);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000464 NumBytes += CurByte-CurBlock;
465
Chris Lattner5be478f2004-11-20 03:46:14 +0000466 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000467 NumRelos += Relocations.size();
468
Chris Lattner5be478f2004-11-20 03:46:14 +0000469 // Resolve the relocations to concrete pointers.
470 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
471 MachineRelocation &MR = Relocations[i];
472 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000473 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000474 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000475
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000476 // If the target REALLY wants a stub for this function, emit it now.
477 if (!MR.doesntNeedFunctionStub())
478 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
Jeff Cohen00b168892005-07-27 06:12:32 +0000479 } else if (MR.isGlobalValue())
Chris Lattner5e225582004-11-21 03:37:42 +0000480 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
481 CurBlock+MR.getMachineCodeOffset(),
482 MR.doesntNeedFunctionStub());
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000483 else //ConstantPoolIndex
Jeff Cohen00b168892005-07-27 06:12:32 +0000484 ResultPtr =
Chris Lattnerd6bbac52005-07-25 23:42:58 +0000485 (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Jeff Cohen00b168892005-07-27 06:12:32 +0000486
Chris Lattner5be478f2004-11-20 03:46:14 +0000487 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000488
Andrew Lenharth6a974612005-07-28 12:44:13 +0000489 // if we are managing the GOT and the relocation wants an index,
490 // give it one
491 if (MemMgr.isManagingGOT() && !MR.isConstantPoolIndex() &&
492 MR.isGOTRelative()) {
493 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
494 MR.setGOTIndex(idx);
495 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
496 DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
497 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
498 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
499 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000500 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000501 }
502
503 TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000504 Relocations.size(), MemMgr.getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000505 }
506
Andrew Lenharth6a974612005-07-28 12:44:13 +0000507 //Update the GOT entry for F to point to the new code.
508 if(MemMgr.isManagingGOT()) {
509 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)CurBlock);
510 if (((void**)MemMgr.getGOTBase())[idx] != (void*)CurBlock) {
511 DEBUG(std::cerr << "GOT was out of date for " << (void*)CurBlock
512 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
513 ((void**)MemMgr.getGOTBase())[idx] = (void*)CurBlock;
514 }
515 }
516
Chris Lattnercb479412004-11-21 03:44:32 +0000517 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
Misha Brukman1d440852003-06-06 06:52:35 +0000518 << "] Function: " << F.getFunction()->getName()
Chris Lattner5be478f2004-11-20 03:46:14 +0000519 << ": " << CurByte-CurBlock << " bytes of text, "
520 << Relocations.size() << " relocations\n");
521 Relocations.clear();
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000522 ConstantPoolAddresses.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000523}
524
Chris Lattner166f2262004-11-22 22:00:25 +0000525void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattner1cc08382003-01-13 01:00:12 +0000526 const std::vector<Constant*> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000527 if (Constants.empty()) return;
528
Chris Lattner1cc08382003-01-13 01:00:12 +0000529 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000530 const Type *Ty = Constants[i]->getType();
Chris Lattnera8101c12005-01-08 20:07:03 +0000531 unsigned Size = (unsigned)TheJIT->getTargetData().getTypeSize(Ty);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000532 unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000533
Chris Lattner281a6012005-01-10 18:23:22 +0000534 void *Addr = MemMgr.allocateConstant(Size, Alignment);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000535 TheJIT->InitializeMemory(Constants[i], Addr);
Misha Brukman91de3522003-11-30 00:50:53 +0000536 ConstantPoolAddresses.push_back(Addr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000537 }
538}
539
Chris Lattner166f2262004-11-22 22:00:25 +0000540void JITEmitter::startFunctionStub(unsigned StubSize) {
Chris Lattner6125fdd2003-05-09 03:30:07 +0000541 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
Chris Lattner688506d2003-08-14 18:35:27 +0000542 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000543}
544
Chris Lattner166f2262004-11-22 22:00:25 +0000545void *JITEmitter::finishFunctionStub(const Function *F) {
Chris Lattner6125fdd2003-05-09 03:30:07 +0000546 NumBytes += CurByte-CurBlock;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000547 std::swap(CurBlock, SavedCurBlock);
548 CurByte = SavedCurByte;
549 return SavedCurBlock;
550}
551
Chris Lattner166f2262004-11-22 22:00:25 +0000552void JITEmitter::emitByte(unsigned char B) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000553 *CurByte++ = B; // Write the byte to memory
554}
555
Chris Lattner166f2262004-11-22 22:00:25 +0000556void JITEmitter::emitWord(unsigned W) {
Chris Lattner688506d2003-08-14 18:35:27 +0000557 // This won't work if the endianness of the host and target don't agree! (For
558 // a JIT this can't happen though. :)
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000559 *(unsigned*)CurByte = W;
560 CurByte += sizeof(unsigned);
561}
562
Chris Lattner166f2262004-11-22 22:00:25 +0000563void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
Brian Gaekeaea1b582004-04-23 17:11:14 +0000564 *Ptr = W;
565}
566
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000567// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
568// in the constant pool that was last emitted with the 'emitConstantPool'
569// method.
570//
Chris Lattner166f2262004-11-22 22:00:25 +0000571uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000572 assert(ConstantNum < ConstantPoolAddresses.size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000573 "Invalid ConstantPoolIndex!");
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000574 return (intptr_t)ConstantPoolAddresses[ConstantNum];
575}
576
Andrew Lenharth6a974612005-07-28 12:44:13 +0000577unsigned char* JITEmitter::allocateGlobal(unsigned size, unsigned alignment)
578{
579 return MemMgr.allocateGlobal(size, alignment);
580}
581
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000582// getCurrentPCValue - This returns the address that the next emitted byte
583// will be output to.
584//
Chris Lattner166f2262004-11-22 22:00:25 +0000585uint64_t JITEmitter::getCurrentPCValue() {
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000586 return (intptr_t)CurByte;
587}
588
Chris Lattner166f2262004-11-22 22:00:25 +0000589uint64_t JITEmitter::getCurrentPCOffset() {
Chris Lattner5be478f2004-11-20 03:46:14 +0000590 return (intptr_t)CurByte-(intptr_t)CurBlock;
591}
592
Misha Brukmand69c1e62003-07-28 19:09:06 +0000593// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000594// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000595// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
596// need to resolve function(s) that are being mis-codegenerated, so we need to
597// resolve their addresses at runtime, and this is the way to do it.
598extern "C" {
599 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000600 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000601 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000602 return TheJIT->getPointerToFunction(F);
603 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000604 }
605}