blob: 704fa803f81b11edc1b4eb920bbadb4379983ced [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"
Chris Lattnere7fd5532006-05-08 22:00:52 +000029#include "llvm/Support/MutexGuard.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/ADT/Statistic.h"
Reid Spencer52b0ba62004-09-11 04:31:03 +000031#include "llvm/System/Memory.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000032#include <algorithm>
Chris Lattnerca261802006-01-22 23:41:42 +000033#include <iostream>
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 {
Chris Lattnere6fdcbf2006-05-03 00:54:49 +000055 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
Chris Lattner688506d2003-08-14 18:35:27 +000056 unsigned char *FunctionBase; // Start of the function body area
Chris Lattnerf75f9be2006-05-02 23:22:24 +000057 unsigned char *CurStubPtr, *CurFunctionPtr;
Chris Lattnera726c7f2006-05-02 21:44:14 +000058 unsigned char *GOTBase; // Target Specific reserved memory
Andrew Lenhartha00269b2005-07-29 23:40:16 +000059
60 // centralize memory block allocation
61 sys::MemoryBlock getNewMemoryBlock(unsigned size);
Chris Lattner688506d2003-08-14 18:35:27 +000062 public:
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000063 JITMemoryManager(bool useGOT);
Reid Spencer4af3da62004-12-13 16:04:04 +000064 ~JITMemoryManager();
Misha Brukmanf976c852005-04-21 22:55:34 +000065
Chris Lattner688506d2003-08-14 18:35:27 +000066 inline unsigned char *allocateStub(unsigned StubSize);
67 inline unsigned char *startFunctionBody();
Chris Lattner281a6012005-01-10 18:23:22 +000068 inline void endFunctionBody(unsigned char *FunctionEnd);
Chris Lattnera726c7f2006-05-02 21:44:14 +000069
70 unsigned char *getGOTBase() const {
71 return GOTBase;
72 }
73 bool isManagingGOT() const {
74 return GOTBase != NULL;
75 }
Chris Lattner688506d2003-08-14 18:35:27 +000076 };
77}
78
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000079JITMemoryManager::JITMemoryManager(bool useGOT) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +000080 // Allocate a 16M block of memory for functions
81 sys::MemoryBlock FunBlock = getNewMemoryBlock(16 << 20);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000082
Andrew Lenhartha00269b2005-07-29 23:40:16 +000083 FunctionBase = reinterpret_cast<unsigned char*>(FunBlock.base());
Chris Lattner281a6012005-01-10 18:23:22 +000084
Andrew Lenhartha00269b2005-07-29 23:40:16 +000085 // Allocate stubs backwards from the base, allocate functions forward
86 // from the base.
87 CurStubPtr = CurFunctionPtr = FunctionBase + 512*1024;// Use 512k for stubs
88
Chris Lattnerf5d438c2006-05-02 21:57:51 +000089 // Allocate the GOT.
Andrew Lenharth2b3b89c2005-08-01 17:35:40 +000090 GOTBase = NULL;
Chris Lattnerf5d438c2006-05-02 21:57:51 +000091 if (useGOT) GOTBase = (unsigned char*)malloc(sizeof(void*) * 8192);
Chris Lattner688506d2003-08-14 18:35:27 +000092}
93
Reid Spencer4af3da62004-12-13 16:04:04 +000094JITMemoryManager::~JITMemoryManager() {
Chris Lattnere6fdcbf2006-05-03 00:54:49 +000095 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
96 sys::Memory::ReleaseRWX(Blocks[i]);
Andrew Lenhartha00269b2005-07-29 23:40:16 +000097 Blocks.clear();
Reid Spencer4af3da62004-12-13 16:04:04 +000098}
99
Chris Lattner688506d2003-08-14 18:35:27 +0000100unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
101 CurStubPtr -= StubSize;
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000102 if (CurStubPtr < FunctionBase) {
Chris Lattnera726c7f2006-05-02 21:44:14 +0000103 // FIXME: allocate a new block
Chris Lattner688506d2003-08-14 18:35:27 +0000104 std::cerr << "JIT ran out of memory for function stubs!\n";
105 abort();
106 }
107 return CurStubPtr;
108}
109
110unsigned char *JITMemoryManager::startFunctionBody() {
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000111 return CurFunctionPtr;
Chris Lattner688506d2003-08-14 18:35:27 +0000112}
113
114void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
115 assert(FunctionEnd > CurFunctionPtr);
116 CurFunctionPtr = FunctionEnd;
117}
118
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000119sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000120 try {
Chris Lattnere6fdcbf2006-05-03 00:54:49 +0000121 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
122 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld);
123 Blocks.push_back(B);
124 return B;
125 } catch (std::string &err) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000126 std::cerr << "Allocation failed when allocating new memory in the JIT\n";
127 std::cerr << err << "\n";
128 abort();
129 }
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000130}
131
Chris Lattner54266522004-11-20 23:57:07 +0000132//===----------------------------------------------------------------------===//
133// JIT lazy compilation code.
134//
135namespace {
Reid Spenceree448632005-07-12 15:51:55 +0000136 class JITResolverState {
137 private:
138 /// FunctionToStubMap - Keep track of the stub created for a particular
139 /// function so that we can reuse them if necessary.
140 std::map<Function*, void*> FunctionToStubMap;
141
142 /// StubToFunctionMap - Keep track of the function that each stub
143 /// corresponds to.
144 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +0000145
Reid Spenceree448632005-07-12 15:51:55 +0000146 public:
147 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
148 assert(locked.holds(TheJIT->lock));
149 return FunctionToStubMap;
150 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000151
Reid Spenceree448632005-07-12 15:51:55 +0000152 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
153 assert(locked.holds(TheJIT->lock));
154 return StubToFunctionMap;
155 }
156 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000157
Chris Lattner54266522004-11-20 23:57:07 +0000158 /// JITResolver - Keep track of, and resolve, call sites for functions that
159 /// have not yet been compiled.
160 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +0000161 /// MCE - The MachineCodeEmitter to use to emit stubs with.
Chris Lattner54266522004-11-20 23:57:07 +0000162 MachineCodeEmitter &MCE;
163
Chris Lattner5e225582004-11-21 03:37:42 +0000164 /// LazyResolverFn - The target lazy resolver function that we actually
165 /// rewrite instructions to use.
166 TargetJITInfo::LazyResolverFn LazyResolverFn;
167
Reid Spenceree448632005-07-12 15:51:55 +0000168 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000169
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000170 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
171 /// external functions.
172 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000173
174 //map addresses to indexes in the GOT
175 std::map<void*, unsigned> revGOTMap;
176 unsigned nextGOTIndex;
177
Chris Lattner54266522004-11-20 23:57:07 +0000178 public:
Andrew Lenharth6a974612005-07-28 12:44:13 +0000179 JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
Chris Lattner5e225582004-11-21 03:37:42 +0000180 LazyResolverFn =
181 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
182 }
Chris Lattner54266522004-11-20 23:57:07 +0000183
184 /// getFunctionStub - This returns a pointer to a function stub, creating
185 /// one on demand as needed.
186 void *getFunctionStub(Function *F);
187
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000188 /// getExternalFunctionStub - Return a stub for the function at the
189 /// specified address, created lazily on demand.
190 void *getExternalFunctionStub(void *FnAddr);
191
Chris Lattner5e225582004-11-21 03:37:42 +0000192 /// AddCallbackAtLocation - If the target is capable of rewriting an
193 /// instruction without the use of a stub, record the location of the use so
194 /// we know which function is being used at the location.
195 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000196 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000197 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000198 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner5e225582004-11-21 03:37:42 +0000199 return (void*)LazyResolverFn;
200 }
201
Andrew Lenharth6a974612005-07-28 12:44:13 +0000202 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
203 /// and address. This function only manages slots, it does not manage the
204 /// contents of the slots or the memory associated with the GOT.
205 unsigned getGOTIndexForAddr(void* addr);
206
Chris Lattner54266522004-11-20 23:57:07 +0000207 /// JITCompilerFn - This function is called to resolve a stub to a compiled
208 /// address. If the LLVM Function corresponding to the stub has not yet
209 /// been compiled, this function compiles it first.
210 static void *JITCompilerFn(void *Stub);
211 };
212}
213
214/// getJITResolver - This function returns the one instance of the JIT resolver.
215///
216static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
217 static JITResolver TheJITResolver(*MCE);
218 return TheJITResolver;
219}
220
221/// getFunctionStub - This returns a pointer to a function stub, creating
222/// one on demand as needed.
223void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000224 MutexGuard locked(TheJIT->lock);
225
Chris Lattner54266522004-11-20 23:57:07 +0000226 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000227 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000228 if (Stub) return Stub;
229
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000230 // Call the lazy resolver function unless we already KNOW it is an external
231 // function, in which case we just skip the lazy resolution step.
232 void *Actual = (void*)LazyResolverFn;
Chris Lattner69435702005-02-20 18:43:35 +0000233 if (F->isExternal() && F->hasExternalLinkage())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000234 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000235
Chris Lattner54266522004-11-20 23:57:07 +0000236 // Otherwise, codegen a new stub. For now, the stub will call the lazy
237 // resolver function.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000238 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
239
Chris Lattner69435702005-02-20 18:43:35 +0000240 if (Actual != (void*)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000241 // If we are getting the stub for an external function, we really want the
242 // address of the stub in the GlobalAddressMap for the JIT, not the address
243 // of the external function.
244 TheJIT->updateGlobalMapping(F, Stub);
245 }
Chris Lattner54266522004-11-20 23:57:07 +0000246
Chris Lattnercb479412004-11-21 03:44:32 +0000247 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
Chris Lattner6f717202004-11-22 21:48:33 +0000248 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000249
Chris Lattner54266522004-11-20 23:57:07 +0000250 // Finally, keep track of the stub-to-Function mapping so that the
251 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000252 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000253 return Stub;
254}
255
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000256/// getExternalFunctionStub - Return a stub for the function at the
257/// specified address, created lazily on demand.
258void *JITResolver::getExternalFunctionStub(void *FnAddr) {
259 // If we already have a stub for this function, recycle it.
260 void *&Stub = ExternalFnToStubMap[FnAddr];
261 if (Stub) return Stub;
262
263 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
264 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
265 << "] for external function at '" << FnAddr << "'\n");
266 return Stub;
267}
268
Andrew Lenharth6a974612005-07-28 12:44:13 +0000269unsigned JITResolver::getGOTIndexForAddr(void* addr) {
270 unsigned idx = revGOTMap[addr];
271 if (!idx) {
272 idx = ++nextGOTIndex;
273 revGOTMap[addr] = idx;
274 DEBUG(std::cerr << "Adding GOT entry " << idx
275 << " for addr " << addr << "\n");
276 // ((void**)MemMgr.getGOTBase())[idx] = addr;
277 }
278 return idx;
279}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000280
Chris Lattner54266522004-11-20 23:57:07 +0000281/// JITCompilerFn - This function is called when a lazy compilation stub has
282/// been entered. It looks up which function this stub corresponds to, compiles
283/// it if necessary, then returns the resultant function pointer.
284void *JITResolver::JITCompilerFn(void *Stub) {
285 JITResolver &JR = getJITResolver();
Misha Brukmanf976c852005-04-21 22:55:34 +0000286
Reid Spenceree448632005-07-12 15:51:55 +0000287 MutexGuard locked(TheJIT->lock);
288
Chris Lattner54266522004-11-20 23:57:07 +0000289 // The address given to us for the stub may not be exactly right, it might be
290 // a little bit after the stub. As such, use upper_bound to find it.
291 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000292 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
Chris Lattner21998772006-01-07 06:20:51 +0000293 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
294 "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000295 Function *F = (--I)->second;
296
Reid Spenceree448632005-07-12 15:51:55 +0000297 // We might like to remove the stub from the StubToFunction map.
298 // We can't do that! Multiple threads could be stuck, waiting to acquire the
299 // lock above. As soon as the 1st function finishes compiling the function,
Chris Lattner21998772006-01-07 06:20:51 +0000300 // the next one will be released, and needs to be able to find the function it
301 // needs to call.
Reid Spenceree448632005-07-12 15:51:55 +0000302 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000303
Chris Lattnercb479412004-11-21 03:44:32 +0000304 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
Chris Lattner54266522004-11-20 23:57:07 +0000305 << "' In stub ptr = " << Stub << " actual ptr = "
306 << I->first << "\n");
307
308 void *Result = TheJIT->getPointerToFunction(F);
309
310 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000311 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000312
313 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000314
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000315 // What we will do is set the compiled function address to map to the
316 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000317 // if they see it still using the stub address.
318 // Note: this is done so the Resolver doesn't have to manage GOT memory
319 // Do this without allocating map space if the target isn't using a GOT
320 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
321 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
322
Chris Lattner54266522004-11-20 23:57:07 +0000323 return Result;
324}
Chris Lattner688506d2003-08-14 18:35:27 +0000325
326
Chris Lattnere518b712004-12-05 07:19:16 +0000327// getPointerToFunctionOrStub - If the specified function has been
328// code-gen'd, return a pointer to the function. If not, compile it, or use
329// a stub to implement lazy compilation if available.
330//
331void *JIT::getPointerToFunctionOrStub(Function *F) {
332 // If we have already code generated the function, just return the address.
333 if (void *Addr = getPointerToGlobalIfAvailable(F))
334 return Addr;
335
336 // Get a stub if the target supports it
337 return getJITResolver(MCE).getFunctionStub(F);
338}
339
Chris Lattnere7fd5532006-05-08 22:00:52 +0000340/// freeMachineCodeForFunction - release machine code memory for given Function.
341///
342void JIT::freeMachineCodeForFunction(Function *F) {
343 // Delete translation for this from the ExecutionEngine, so it will get
344 // retranslated next time it is used.
345 updateGlobalMapping(F, 0);
346
347}
Chris Lattnere518b712004-12-05 07:19:16 +0000348
Chris Lattner54266522004-11-20 23:57:07 +0000349//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000350// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000351//
Chris Lattner688506d2003-08-14 18:35:27 +0000352namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000353 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
354 /// used to output functions to memory for execution.
355 class JITEmitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000356 JITMemoryManager MemMgr;
357
Chris Lattner6125fdd2003-05-09 03:30:07 +0000358 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000359 // save BufferBegin/BufferEnd/CurBufferPtr here.
360 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000361
Chris Lattner5be478f2004-11-20 03:46:14 +0000362 /// Relocations - These are the relocations that the function needs, as
363 /// emitted.
364 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000365
366 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
367 /// It is filled in by the StartMachineBasicBlock callback and queried by
368 /// the getMachineBasicBlockAddress callback.
369 std::vector<intptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000370
Chris Lattner239862c2006-02-09 04:49:59 +0000371 /// ConstantPool - The constant pool for the current function.
372 ///
373 MachineConstantPool *ConstantPool;
374
375 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
376 ///
377 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000378
379 /// ConstantPool - The constant pool for the current function.
380 ///
381 MachineJumpTableInfo *JumpTable;
382
383 /// JumpTableBase - A pointer to the first entry in the jump table.
384 ///
385 void *JumpTableBase;
386public:
Chris Lattner239862c2006-02-09 04:49:59 +0000387 JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
Jeff Cohen00b168892005-07-27 06:12:32 +0000388 TheJIT = &jit;
Chris Lattnera726c7f2006-05-02 21:44:14 +0000389 DEBUG(if (MemMgr.isManagingGOT()) std::cerr << "JIT is managing a GOT\n");
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000390 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000391
392 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000393 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000394
395 void emitConstantPool(MachineConstantPool *MCP);
396 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerb4432f32006-05-03 17:10:41 +0000397 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000398
Chris Lattner54266522004-11-20 23:57:07 +0000399 virtual void startFunctionStub(unsigned StubSize);
400 virtual void* finishFunctionStub(const Function *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000401
Chris Lattner5be478f2004-11-20 03:46:14 +0000402 virtual void addRelocation(const MachineRelocation &MR) {
403 Relocations.push_back(MR);
404 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000405
406 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
407 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
408 MBBLocations.resize((MBB->getNumber()+1)*2);
409 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
410 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000411
Chris Lattnerb4432f32006-05-03 17:10:41 +0000412 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
413 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
414
415 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
416 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
417 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
418 return MBBLocations[MBB->getNumber()];
419 }
420
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000421
Chris Lattner54266522004-11-20 23:57:07 +0000422 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000423 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000424 };
425}
426
Chris Lattner4d326fa2003-12-20 01:46:27 +0000427MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
Chris Lattner166f2262004-11-22 22:00:25 +0000428 return new JITEmitter(jit);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000429}
430
Chris Lattner166f2262004-11-22 22:00:25 +0000431void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
432 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000433 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
434 /// FIXME: If we straightened things out, this could actually emit the
435 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000436 return TheJIT->getOrEmitGlobalVariable(GV);
437 }
438
439 // If we have already compiled the function, return a pointer to its body.
440 Function *F = cast<Function>(V);
441 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
442 if (ResultPtr) return ResultPtr;
443
Chris Lattner532343b2004-11-30 17:41:49 +0000444 if (F->hasExternalLinkage() && F->isExternal()) {
Chris Lattner54266522004-11-20 23:57:07 +0000445 // If this is an external function pointer, we can force the JIT to
446 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000447 if (DoesntNeedStub)
448 return TheJIT->getPointerToFunction(F);
449
450 return getJITResolver(this).getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000451 }
452
Chris Lattner5e225582004-11-21 03:37:42 +0000453 // Okay, the function has not been compiled yet, if the target callback
454 // mechanism is capable of rewriting the instruction directly, prefer to do
455 // that instead of emitting a stub.
456 if (DoesntNeedStub)
457 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
458
Chris Lattner54266522004-11-20 23:57:07 +0000459 // Otherwise, we have to emit a lazy resolving stub.
460 return getJITResolver(this).getFunctionStub(F);
461}
462
Chris Lattner166f2262004-11-22 22:00:25 +0000463void JITEmitter::startFunction(MachineFunction &F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000464 BufferBegin = CurBufferPtr = MemMgr.startFunctionBody();
Chris Lattner43b429b2006-05-02 18:27:26 +0000465
466 /// FIXME: implement out of space handling correctly!
467 BufferEnd = (unsigned char*)(intptr_t)~0ULL;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000468
469 emitConstantPool(F.getConstantPool());
470 initJumpTableInfo(F.getJumpTableInfo());
471
472 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000473 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000474 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Chris Lattnerb4432f32006-05-03 17:10:41 +0000475
476 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000477}
478
Chris Lattner43b429b2006-05-02 18:27:26 +0000479bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000480 emitJumpTableInfo(F.getJumpTableInfo());
481
Chris Lattner43b429b2006-05-02 18:27:26 +0000482 MemMgr.endFunctionBody(CurBufferPtr);
483 NumBytes += getCurrentPCOffset();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000484
Chris Lattner5be478f2004-11-20 03:46:14 +0000485 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000486 NumRelos += Relocations.size();
487
Chris Lattner5be478f2004-11-20 03:46:14 +0000488 // Resolve the relocations to concrete pointers.
489 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
490 MachineRelocation &MR = Relocations[i];
491 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000492 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000493 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000494
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000495 // If the target REALLY wants a stub for this function, emit it now.
496 if (!MR.doesntNeedFunctionStub())
497 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000498 } else if (MR.isGlobalValue()) {
Chris Lattner5e225582004-11-21 03:37:42 +0000499 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
Chris Lattner43b429b2006-05-02 18:27:26 +0000500 BufferBegin+MR.getMachineCodeOffset(),
Chris Lattner5e225582004-11-21 03:37:42 +0000501 MR.doesntNeedFunctionStub());
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000502 } else {
503 assert(MR.isConstantPoolIndex());
504 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
505 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000506
Chris Lattner5be478f2004-11-20 03:46:14 +0000507 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000508
Andrew Lenharth6a974612005-07-28 12:44:13 +0000509 // if we are managing the GOT and the relocation wants an index,
510 // give it one
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000511 if (MemMgr.isManagingGOT() && MR.isGOTRelative()) {
Andrew Lenharth6a974612005-07-28 12:44:13 +0000512 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
513 MR.setGOTIndex(idx);
514 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
515 DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
Chris Lattner21998772006-01-07 06:20:51 +0000516 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
517 << "\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000518 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
519 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000520 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000521 }
522
Chris Lattner43b429b2006-05-02 18:27:26 +0000523 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000524 Relocations.size(), MemMgr.getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000525 }
526
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000527 // Update the GOT entry for F to point to the new code.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000528 if(MemMgr.isManagingGOT()) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000529 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)BufferBegin);
530 if (((void**)MemMgr.getGOTBase())[idx] != (void*)BufferBegin) {
531 DEBUG(std::cerr << "GOT was out of date for " << (void*)BufferBegin
Andrew Lenharth6a974612005-07-28 12:44:13 +0000532 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
Chris Lattner43b429b2006-05-02 18:27:26 +0000533 ((void**)MemMgr.getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000534 }
535 }
536
Chris Lattner43b429b2006-05-02 18:27:26 +0000537 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)BufferBegin
Misha Brukman1d440852003-06-06 06:52:35 +0000538 << "] Function: " << F.getFunction()->getName()
Chris Lattner43b429b2006-05-02 18:27:26 +0000539 << ": " << getCurrentPCOffset() << " bytes of text, "
Chris Lattner5be478f2004-11-20 03:46:14 +0000540 << Relocations.size() << " relocations\n");
541 Relocations.clear();
Chris Lattner43b429b2006-05-02 18:27:26 +0000542 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000543}
544
Chris Lattner166f2262004-11-22 22:00:25 +0000545void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000546 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000547 if (Constants.empty()) return;
548
Chris Lattner3029f922006-02-09 04:46:04 +0000549 unsigned Size = Constants.back().Offset;
Owen Andersona69571c2006-05-03 01:29:57 +0000550 Size += TheJIT->getTargetData()->getTypeSize(Constants.back().Val->getType());
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000551
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000552 ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
Chris Lattner239862c2006-02-09 04:49:59 +0000553 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000554
555 if (ConstantPoolBase == 0) return; // Buffer overflow.
556
Chris Lattner239862c2006-02-09 04:49:59 +0000557 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +0000558 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +0000559 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Chris Lattner3029f922006-02-09 04:46:04 +0000560 TheJIT->InitializeMemory(Constants[i].Val, CAddr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000561 }
562}
563
Nate Begeman37efe672006-04-22 18:53:45 +0000564void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
565 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
566 if (JT.empty()) return;
567
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000568 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +0000569 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000570 NumEntries += JT[i].MBBs.size();
571
572 unsigned EntrySize = MJTI->getEntrySize();
573
Nate Begeman37efe672006-04-22 18:53:45 +0000574 // Just allocate space for all the jump tables now. We will fix up the actual
575 // MBB entries in the tables after we emit the code for each block, since then
576 // we will know the final locations of the MBBs in memory.
577 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000578 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +0000579}
580
Chris Lattnerb4432f32006-05-03 17:10:41 +0000581void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Nate Begeman37efe672006-04-22 18:53:45 +0000582 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000583 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +0000584
585 unsigned Offset = 0;
Chris Lattner32ca55f2006-05-03 00:13:06 +0000586 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
Nate Begeman37efe672006-04-22 18:53:45 +0000587
588 // For each jump table, map each target in the jump table to the address of
589 // an emitted MachineBasicBlock.
Chris Lattner32ca55f2006-05-03 00:13:06 +0000590 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
591
Nate Begeman37efe672006-04-22 18:53:45 +0000592 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
593 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Chris Lattner32ca55f2006-05-03 00:13:06 +0000594 // Store the address of the basic block for this jump table slot in the
595 // memory we allocated for the jump table in 'initJumpTableInfo'
596 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
Chris Lattnerb4432f32006-05-03 17:10:41 +0000597 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
Nate Begeman37efe672006-04-22 18:53:45 +0000598 }
599}
600
Chris Lattner166f2262004-11-22 22:00:25 +0000601void JITEmitter::startFunctionStub(unsigned StubSize) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000602 SavedBufferBegin = BufferBegin;
603 SavedBufferEnd = BufferEnd;
604 SavedCurBufferPtr = CurBufferPtr;
605
606 BufferBegin = CurBufferPtr = MemMgr.allocateStub(StubSize);
607 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000608}
609
Chris Lattner166f2262004-11-22 22:00:25 +0000610void *JITEmitter::finishFunctionStub(const Function *F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000611 NumBytes += getCurrentPCOffset();
612 std::swap(SavedBufferBegin, BufferBegin);
613 BufferEnd = SavedBufferEnd;
614 CurBufferPtr = SavedCurBufferPtr;
615 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000616}
617
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000618// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
619// in the constant pool that was last emitted with the 'emitConstantPool'
620// method.
621//
Chris Lattnerb4432f32006-05-03 17:10:41 +0000622intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +0000623 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000624 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +0000625 return (intptr_t)ConstantPoolBase +
626 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000627}
628
Nate Begeman37efe672006-04-22 18:53:45 +0000629// getJumpTableEntryAddress - Return the address of the JumpTable with index
630// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
631//
Chris Lattnerb4432f32006-05-03 17:10:41 +0000632intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +0000633 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
634 assert(Index < JT.size() && "Invalid jump table index!");
635
636 unsigned Offset = 0;
637 unsigned EntrySize = JumpTable->getEntrySize();
638
639 for (unsigned i = 0; i < Index; ++i)
640 Offset += JT[i].MBBs.size() * EntrySize;
641
Nate Begemanc34b2272006-04-25 17:46:32 +0000642 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +0000643}
644
Misha Brukmand69c1e62003-07-28 19:09:06 +0000645// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000646// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000647// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
648// need to resolve function(s) that are being mis-codegenerated, so we need to
649// resolve their addresses at runtime, and this is the way to do it.
650extern "C" {
651 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000652 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000653 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000654 return TheJIT->getPointerToFunction(F);
655 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000656 }
657}