blob: 4f13ea4d49a0a929d9d547cc1ba633b0c2963995 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000017#include "JITDwarfEmitter.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000018#include "llvm/Constant.h"
19#include "llvm/Module.h"
Chris Lattner5b3a4552005-03-17 15:38:16 +000020#include "llvm/Type.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000021#include "llvm/CodeGen/MachineCodeEmitter.h"
22#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000023#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman37efe672006-04-22 18:53:45 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000026#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000028#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000029#include "llvm/Target/TargetJITInfo.h"
Jim Laskeyacd80ac2006-12-14 19:17:33 +000030#include "llvm/Target/TargetMachine.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000031#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000033#include "llvm/Support/MutexGuard.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000034#include "llvm/System/Disassembler.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000035#include "llvm/Target/TargetInstrInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000037#include <algorithm>
Chris Lattnerc19aade2003-12-08 08:06:28 +000038using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000039
Chris Lattner36343732006-12-19 22:43:32 +000040STATISTIC(NumBytes, "Number of bytes of machine code compiled");
41STATISTIC(NumRelos, "Number of relocations applied");
42static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000043
Andrew Lenhartha00269b2005-07-29 23:40:16 +000044
Chris Lattner54266522004-11-20 23:57:07 +000045//===----------------------------------------------------------------------===//
46// JIT lazy compilation code.
47//
48namespace {
Reid Spenceree448632005-07-12 15:51:55 +000049 class JITResolverState {
50 private:
51 /// FunctionToStubMap - Keep track of the stub created for a particular
52 /// function so that we can reuse them if necessary.
53 std::map<Function*, void*> FunctionToStubMap;
54
55 /// StubToFunctionMap - Keep track of the function that each stub
56 /// corresponds to.
57 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000058
Evan Chengbe8c03f2008-01-04 10:46:51 +000059 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
60 /// particular GlobalVariable so that we can reuse them if necessary.
61 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
62
Reid Spenceree448632005-07-12 15:51:55 +000063 public:
64 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
65 assert(locked.holds(TheJIT->lock));
66 return FunctionToStubMap;
67 }
Jeff Cohen00b168892005-07-27 06:12:32 +000068
Reid Spenceree448632005-07-12 15:51:55 +000069 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
70 assert(locked.holds(TheJIT->lock));
71 return StubToFunctionMap;
72 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000073
74 std::map<GlobalValue*, void*>&
75 getGlobalToLazyPtrMap(const MutexGuard& locked) {
76 assert(locked.holds(TheJIT->lock));
77 return GlobalToLazyPtrMap;
78 }
Reid Spenceree448632005-07-12 15:51:55 +000079 };
Jeff Cohen00b168892005-07-27 06:12:32 +000080
Chris Lattner54266522004-11-20 23:57:07 +000081 /// JITResolver - Keep track of, and resolve, call sites for functions that
82 /// have not yet been compiled.
83 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +000084 /// LazyResolverFn - The target lazy resolver function that we actually
85 /// rewrite instructions to use.
86 TargetJITInfo::LazyResolverFn LazyResolverFn;
87
Reid Spenceree448632005-07-12 15:51:55 +000088 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +000089
Chris Lattnerd91ff7c2005-04-18 01:44:27 +000090 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
91 /// external functions.
92 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +000093
94 //map addresses to indexes in the GOT
95 std::map<void*, unsigned> revGOTMap;
96 unsigned nextGOTIndex;
97
Chris Lattnere7484012007-02-24 02:57:03 +000098 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +000099 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000100 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000101 TheJIT = &jit;
102
103 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
104 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
105 TheJITResolver = this;
106 }
107
108 ~JITResolver() {
109 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000110 }
Chris Lattner54266522004-11-20 23:57:07 +0000111
112 /// getFunctionStub - This returns a pointer to a function stub, creating
113 /// one on demand as needed.
114 void *getFunctionStub(Function *F);
115
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000116 /// getExternalFunctionStub - Return a stub for the function at the
117 /// specified address, created lazily on demand.
118 void *getExternalFunctionStub(void *FnAddr);
119
Evan Chengbe8c03f2008-01-04 10:46:51 +0000120 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
121 /// GV address.
122 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
123
Chris Lattner5e225582004-11-21 03:37:42 +0000124 /// AddCallbackAtLocation - If the target is capable of rewriting an
125 /// instruction without the use of a stub, record the location of the use so
126 /// we know which function is being used at the location.
127 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000128 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000129 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000130 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000131 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000132 }
133
Andrew Lenharth6a974612005-07-28 12:44:13 +0000134 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000135 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000136 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000137 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000138
Chris Lattner54266522004-11-20 23:57:07 +0000139 /// JITCompilerFn - This function is called to resolve a stub to a compiled
140 /// address. If the LLVM Function corresponding to the stub has not yet
141 /// been compiled, this function compiles it first.
142 static void *JITCompilerFn(void *Stub);
143 };
144}
145
Chris Lattnere7484012007-02-24 02:57:03 +0000146JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000147
Evan Cheng55b50532006-07-27 06:33:55 +0000148#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
149 defined(__APPLE__)
150extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
151#endif
152
153/// synchronizeICache - On some targets, the JIT emitted code must be
154/// explicitly refetched to ensure correct execution.
155static void synchronizeICache(const void *Addr, size_t len) {
156#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
157 defined(__APPLE__)
Jim Laskey2e9f3682006-07-27 13:40:34 +0000158 sys_icache_invalidate(Addr, len);
Evan Cheng55b50532006-07-27 06:33:55 +0000159#endif
160}
161
Chris Lattner54266522004-11-20 23:57:07 +0000162/// getFunctionStub - This returns a pointer to a function stub, creating
163/// one on demand as needed.
164void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000165 MutexGuard locked(TheJIT->lock);
166
Chris Lattner54266522004-11-20 23:57:07 +0000167 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000168 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000169 if (Stub) return Stub;
170
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000171 // Call the lazy resolver function unless we already KNOW it is an external
172 // function, in which case we just skip the lazy resolution step.
Chris Lattner870286a2006-06-01 17:29:22 +0000173 void *Actual = (void*)(intptr_t)LazyResolverFn;
Gabor Greifa99be512007-07-05 17:07:56 +0000174 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000175 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000176
Chris Lattner54266522004-11-20 23:57:07 +0000177 // Otherwise, codegen a new stub. For now, the stub will call the lazy
178 // resolver function.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000179 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000180 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000181
Chris Lattner870286a2006-06-01 17:29:22 +0000182 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000183 // If we are getting the stub for an external function, we really want the
184 // address of the stub in the GlobalAddressMap for the JIT, not the address
185 // of the external function.
186 TheJIT->updateGlobalMapping(F, Stub);
187 }
Chris Lattner54266522004-11-20 23:57:07 +0000188
Bill Wendling832171c2006-12-07 20:04:42 +0000189 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
190 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000191
Chris Lattner54266522004-11-20 23:57:07 +0000192 // Finally, keep track of the stub-to-Function mapping so that the
193 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000194 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000195 return Stub;
196}
197
Evan Chengbe8c03f2008-01-04 10:46:51 +0000198/// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
199/// GV address.
200void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
201 MutexGuard locked(TheJIT->lock);
202
203 // If we already have a stub for this global variable, recycle it.
204 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
205 if (LazyPtr) return LazyPtr;
206
207 // Otherwise, codegen a new lazy pointer.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000208 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GV, GVAddress,
Evan Chengbe8c03f2008-01-04 10:46:51 +0000209 *TheJIT->getCodeEmitter());
210
211 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
212 << GV->getName() << "'\n";
213
214 return LazyPtr;
215}
216
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000217/// getExternalFunctionStub - Return a stub for the function at the
218/// specified address, created lazily on demand.
219void *JITResolver::getExternalFunctionStub(void *FnAddr) {
220 // If we already have a stub for this function, recycle it.
221 void *&Stub = ExternalFnToStubMap[FnAddr];
222 if (Stub) return Stub;
223
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000224 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000225 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000226
Bill Wendling832171c2006-12-07 20:04:42 +0000227 DOUT << "JIT: Stub emitted at [" << Stub
228 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000229 return Stub;
230}
231
Andrew Lenharth6a974612005-07-28 12:44:13 +0000232unsigned JITResolver::getGOTIndexForAddr(void* addr) {
233 unsigned idx = revGOTMap[addr];
234 if (!idx) {
235 idx = ++nextGOTIndex;
236 revGOTMap[addr] = idx;
Evan Cheng97b8c402008-04-12 00:22:01 +0000237 DOUT << "Adding GOT entry " << idx << " for addr " << addr << "\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000238 }
239 return idx;
240}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000241
Chris Lattner54266522004-11-20 23:57:07 +0000242/// JITCompilerFn - This function is called when a lazy compilation stub has
243/// been entered. It looks up which function this stub corresponds to, compiles
244/// it if necessary, then returns the resultant function pointer.
245void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000246 JITResolver &JR = *TheJITResolver;
Misha Brukmanf976c852005-04-21 22:55:34 +0000247
Reid Spenceree448632005-07-12 15:51:55 +0000248 MutexGuard locked(TheJIT->lock);
249
Chris Lattner54266522004-11-20 23:57:07 +0000250 // The address given to us for the stub may not be exactly right, it might be
251 // a little bit after the stub. As such, use upper_bound to find it.
252 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000253 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
Chris Lattner21998772006-01-07 06:20:51 +0000254 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
255 "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000256 Function *F = (--I)->second;
257
Evan Cheng9da60f92007-06-30 00:10:37 +0000258 // If we have already code generated the function, just return the address.
259 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000260
Evan Cheng9da60f92007-06-30 00:10:37 +0000261 if (!Result) {
262 // Otherwise we don't have it, do lazy compilation now.
263
264 // If lazy compilation is disabled, emit a useful error message and abort.
265 if (TheJIT->isLazyCompilationDisabled()) {
266 cerr << "LLVM JIT requested to do lazy compilation of function '"
267 << F->getName() << "' when lazy compiles are disabled!\n";
268 abort();
269 }
270
271 // We might like to remove the stub from the StubToFunction map.
272 // We can't do that! Multiple threads could be stuck, waiting to acquire the
273 // lock above. As soon as the 1st function finishes compiling the function,
274 // the next one will be released, and needs to be able to find the function
275 // it needs to call.
276 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000277
Evan Cheng9da60f92007-06-30 00:10:37 +0000278 DOUT << "JIT: Lazily resolving function '" << F->getName()
279 << "' In stub ptr = " << Stub << " actual ptr = "
280 << I->first << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000281
Evan Cheng9da60f92007-06-30 00:10:37 +0000282 Result = TheJIT->getPointerToFunction(F);
283 }
Chris Lattner54266522004-11-20 23:57:07 +0000284
285 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000286 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000287
288 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000289
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000290 // What we will do is set the compiled function address to map to the
291 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000292 // if they see it still using the stub address.
293 // Note: this is done so the Resolver doesn't have to manage GOT memory
294 // Do this without allocating map space if the target isn't using a GOT
295 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
296 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
297
Chris Lattner54266522004-11-20 23:57:07 +0000298 return Result;
299}
Chris Lattner688506d2003-08-14 18:35:27 +0000300
Chris Lattner8ac66c12008-04-04 05:51:42 +0000301//===----------------------------------------------------------------------===//
302// Function Index Support
303
304// On MacOS we generate an index of currently JIT'd functions so that
305// performance tools can determine a symbol name and accurate code range for a
306// PC value. Because performance tools are generally asynchronous, the code
307// below is written with the hope that it could be interrupted at any time and
308// have useful answers. However, we don't go crazy with atomic operations, we
309// just do a "reasonable effort".
310#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000311#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000312#endif
313
314/// JitSymbolEntry - Each function that is JIT compiled results in one of these
315/// being added to an array of symbols. This indicates the name of the function
316/// as well as the address range it occupies. This allows the client to map
317/// from a PC value to the name of the function.
318struct JitSymbolEntry {
319 const char *FnName; // FnName - a strdup'd string.
320 void *FnStart;
321 intptr_t FnSize;
322};
323
324
325struct JitSymbolTable {
326 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
327 /// pointer is not used right now, but might be used in the future. Consider
328 /// it reserved for future use.
329 JitSymbolTable *NextPtr;
330
331 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
332 /// 'NumSymbols' symbols are valid.
333 JitSymbolEntry *Symbols;
334
335 /// NumSymbols - This indicates the number entries in the Symbols array that
336 /// are valid.
337 unsigned NumSymbols;
338
339 /// NumAllocated - This indicates the amount of space we have in the Symbols
340 /// array. This is a private field that should not be read by external tools.
341 unsigned NumAllocated;
342};
343
344#if ENABLE_JIT_SYMBOL_TABLE
345JitSymbolTable *__jitSymbolTable;
346#endif
347
348static void AddFunctionToSymbolTable(const char *FnName,
349 void *FnStart, intptr_t FnSize) {
350 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
351 JitSymbolTable **SymTabPtrPtr = 0;
352#if !ENABLE_JIT_SYMBOL_TABLE
353 return;
354#else
355 SymTabPtrPtr = &__jitSymbolTable;
356#endif
357
358 // If this is the first entry in the symbol table, add the JitSymbolTable
359 // index.
360 if (*SymTabPtrPtr == 0) {
361 JitSymbolTable *New = new JitSymbolTable();
362 New->NextPtr = 0;
363 New->Symbols = 0;
364 New->NumSymbols = 0;
365 New->NumAllocated = 0;
366 *SymTabPtrPtr = New;
367 }
368
369 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
370
371 // If we have space in the table, reallocate the table.
372 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
373 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000374 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000375 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
376 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
377
378 // Copy the old entries over.
379 memcpy(NewSymbols, OldSymbols,
Chris Lattner3b374482008-04-13 07:04:56 +0000380 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000381
382 // Swap the new symbols in, delete the old ones.
383 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000384 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000385 delete [] OldSymbols;
386 }
387
388 // Otherwise, we have enough space, just tack it onto the end of the array.
389 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
390 Entry.FnName = strdup(FnName);
391 Entry.FnStart = FnStart;
392 Entry.FnSize = FnSize;
393 ++SymTabPtr->NumSymbols;
394}
395
396static void RemoveFunctionFromSymbolTable(void *FnStart) {
397 assert(FnStart && "Invalid function pointer");
398 JitSymbolTable **SymTabPtrPtr = 0;
399#if !ENABLE_JIT_SYMBOL_TABLE
400 return;
401#else
402 SymTabPtrPtr = &__jitSymbolTable;
403#endif
404
405 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
406 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
407
408 // Scan the table to find its index. The table is not sorted, so do a linear
409 // scan.
410 unsigned Index;
411 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
412 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
413
414 // Once we have an index, we know to nuke this entry, overwrite it with the
415 // entry at the end of the array, making the last entry redundant.
416 const char *OldName = Symbols[Index].FnName;
417 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
418 free((void*)OldName);
419
420 // Drop the number of symbols in the table.
421 --SymTabPtr->NumSymbols;
422
423 // Finally, if we deleted the final symbol, deallocate the table itself.
424 if (SymTabPtr->NumSymbols == 0)
425 return;
426
427 *SymTabPtrPtr = 0;
428 delete [] Symbols;
429 delete SymTabPtr;
430}
Chris Lattner688506d2003-08-14 18:35:27 +0000431
Chris Lattner54266522004-11-20 23:57:07 +0000432//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000433// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000434//
Chris Lattner688506d2003-08-14 18:35:27 +0000435namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000436 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
437 /// used to output functions to memory for execution.
438 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000439 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000440
Chris Lattner6125fdd2003-05-09 03:30:07 +0000441 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000442 // save BufferBegin/BufferEnd/CurBufferPtr here.
443 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000444
Chris Lattner5be478f2004-11-20 03:46:14 +0000445 /// Relocations - These are the relocations that the function needs, as
446 /// emitted.
447 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000448
449 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
450 /// It is filled in by the StartMachineBasicBlock callback and queried by
451 /// the getMachineBasicBlockAddress callback.
452 std::vector<intptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000453
Chris Lattner239862c2006-02-09 04:49:59 +0000454 /// ConstantPool - The constant pool for the current function.
455 ///
456 MachineConstantPool *ConstantPool;
457
458 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
459 ///
460 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000461
Nate Begeman019f8512006-09-10 23:03:44 +0000462 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000463 ///
464 MachineJumpTableInfo *JumpTable;
465
466 /// JumpTableBase - A pointer to the first entry in the jump table.
467 ///
468 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000469
Chris Lattnere7484012007-02-24 02:57:03 +0000470 /// Resolver - This contains info about the currently resolved functions.
471 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000472
473 /// DE - The dwarf emitter for the jit.
474 JITDwarfEmitter *DE;
475
476 /// LabelLocations - This vector is a mapping from Label ID's to their
477 /// address.
478 std::vector<intptr_t> LabelLocations;
479
480 /// MMI - Machine module info for exception informations
481 MachineModuleInfo* MMI;
482
Chris Lattnere7484012007-02-24 02:57:03 +0000483 public:
Chris Lattner9f2f1422007-12-06 01:08:09 +0000484 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
485 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000486 if (jit.getJITInfo().needsGOT()) {
487 MemMgr->AllocateGOT();
488 DOUT << "JIT is managing a GOT\n";
489 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000490
491 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000492 }
493 ~JITEmitter() {
494 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000495 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000496 }
Chris Lattnere7484012007-02-24 02:57:03 +0000497
498 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000499
500 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000501 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000502
503 void emitConstantPool(MachineConstantPool *MCP);
504 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000505 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000506
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000507 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
508 unsigned Alignment = 1);
509 virtual void* finishFunctionStub(const GlobalValue *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000510
Chris Lattner5be478f2004-11-20 03:46:14 +0000511 virtual void addRelocation(const MachineRelocation &MR) {
512 Relocations.push_back(MR);
513 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000514
515 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
516 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
517 MBBLocations.resize((MBB->getNumber()+1)*2);
518 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
519 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000520
Chris Lattnerb4432f32006-05-03 17:10:41 +0000521 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
522 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000523
Chris Lattnerb4432f32006-05-03 17:10:41 +0000524 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
525 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
526 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
527 return MBBLocations[MBB->getNumber()];
528 }
529
Chris Lattnere993cc22006-05-11 23:08:08 +0000530 /// deallocateMemForFunction - Deallocate all memory for the specified
531 /// function body.
532 void deallocateMemForFunction(Function *F) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000533 MemMgr->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000534 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000535
536 virtual void emitLabel(uint64_t LabelID) {
537 if (LabelLocations.size() <= LabelID)
538 LabelLocations.resize((LabelID+1)*2);
539 LabelLocations[LabelID] = getCurrentPCValue();
540 }
541
542 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
543 assert(LabelLocations.size() > (unsigned)LabelID &&
544 LabelLocations[LabelID] && "Label not emitted!");
545 return LabelLocations[LabelID];
546 }
547
548 virtual void setModuleInfo(MachineModuleInfo* Info) {
549 MMI = Info;
550 if (ExceptionHandling) DE->setModuleInfo(Info);
551 }
552
Chris Lattner54266522004-11-20 23:57:07 +0000553 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000554 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000555 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
556 bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000557 };
558}
559
Chris Lattner166f2262004-11-22 22:00:25 +0000560void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
561 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000562 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
563 /// FIXME: If we straightened things out, this could actually emit the
564 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000565 return TheJIT->getOrEmitGlobalVariable(GV);
566 }
567
568 // If we have already compiled the function, return a pointer to its body.
569 Function *F = cast<Function>(V);
570 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
571 if (ResultPtr) return ResultPtr;
572
Gabor Greifa99be512007-07-05 17:07:56 +0000573 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattner54266522004-11-20 23:57:07 +0000574 // If this is an external function pointer, we can force the JIT to
575 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000576 if (DoesntNeedStub)
577 return TheJIT->getPointerToFunction(F);
578
Chris Lattnere7484012007-02-24 02:57:03 +0000579 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000580 }
581
Chris Lattner5e225582004-11-21 03:37:42 +0000582 // Okay, the function has not been compiled yet, if the target callback
583 // mechanism is capable of rewriting the instruction directly, prefer to do
584 // that instead of emitting a stub.
585 if (DoesntNeedStub)
Chris Lattnere7484012007-02-24 02:57:03 +0000586 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000587
Chris Lattner54266522004-11-20 23:57:07 +0000588 // Otherwise, we have to emit a lazy resolving stub.
Chris Lattnere7484012007-02-24 02:57:03 +0000589 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000590}
591
Evan Chengbe8c03f2008-01-04 10:46:51 +0000592void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
593 bool DoesntNeedStub) {
594 // Make sure GV is emitted first.
595 // FIXME: For now, if the GV is an external function we force the JIT to
596 // compile it so the lazy pointer will contain the fully resolved address.
597 void *GVAddress = getPointerToGlobal(V, Reference, true);
598 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
599}
600
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000601static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
602 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
603 if (Constants.empty()) return 0;
604
605 MachineConstantPoolEntry CPE = Constants.back();
606 unsigned Size = CPE.Offset;
607 const Type *Ty = CPE.isMachineConstantPoolEntry()
608 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
609 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
610 return Size;
611}
612
613static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
614 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
615 if (JT.empty()) return 0;
616
617 unsigned NumEntries = 0;
618 for (unsigned i = 0, e = JT.size(); i != e; ++i)
619 NumEntries += JT[i].MBBs.size();
620
621 unsigned EntrySize = MJTI->getEntrySize();
622
623 return NumEntries * EntrySize;
624}
625
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000626static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000627 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000628 // Since we do not know where the buffer will be allocated, be pessimistic.
629 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000630}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000631
Chris Lattner166f2262004-11-22 22:00:25 +0000632void JITEmitter::startFunction(MachineFunction &F) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000633 uintptr_t ActualSize = 0;
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000634 if (MemMgr->NeedsExactSize()) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000635 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
636 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
637 MachineConstantPool *MCP = F.getConstantPool();
638
639 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000640 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000641
642 // Add the alignment of the constant pool
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000643 ActualSize = RoundUpToAlign(ActualSize,
644 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000645
646 // Add the constant pool size
647 ActualSize += GetConstantPoolSizeInBytes(MCP);
648
649 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000650 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000651
652 // Add the jump table size
653 ActualSize += GetJumpTableSizeInBytes(MJTI);
654
655 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000656 ActualSize = RoundUpToAlign(ActualSize,
657 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000658
659 // Add the function size
660 ActualSize += TII->GetFunctionSizeInBytes(F);
661 }
662
Chris Lattner8907b4b2007-12-05 23:39:57 +0000663 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
664 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000665 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000666
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000667 // Ensure the constant pool/jump table info is at least 4-byte aligned.
668 emitAlignment(16);
669
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000670 emitConstantPool(F.getConstantPool());
671 initJumpTableInfo(F.getJumpTableInfo());
672
673 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000674 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000675 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000676
Chris Lattnerb4432f32006-05-03 17:10:41 +0000677 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000678}
679
Chris Lattner43b429b2006-05-02 18:27:26 +0000680bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000681 if (CurBufferPtr == BufferEnd) {
682 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +0000683 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +0000684 abort();
685 }
686
Jim Laskeyb92767a2006-12-14 22:53:42 +0000687 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +0000688
Chris Lattnera8279532006-06-16 18:09:26 +0000689 // FnStart is the start of the text, not the start of the constant pool and
690 // other per-function data.
691 unsigned char *FnStart =
692 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
693 unsigned char *FnEnd = CurBufferPtr;
694
Chris Lattner8907b4b2007-12-05 23:39:57 +0000695 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Chris Lattnera8279532006-06-16 18:09:26 +0000696 NumBytes += FnEnd-FnStart;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000697
Chris Lattner5be478f2004-11-20 03:46:14 +0000698 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000699 NumRelos += Relocations.size();
700
Chris Lattner5be478f2004-11-20 03:46:14 +0000701 // Resolve the relocations to concrete pointers.
702 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
703 MachineRelocation &MR = Relocations[i];
704 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000705 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000706 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000707
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000708 // If the target REALLY wants a stub for this function, emit it now.
Evan Cheng02aabbf2008-01-03 02:56:28 +0000709 if (!MR.doesntNeedStub())
Chris Lattnere7484012007-02-24 02:57:03 +0000710 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000711 } else if (MR.isGlobalValue()) {
Chris Lattner5e225582004-11-21 03:37:42 +0000712 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
Chris Lattner43b429b2006-05-02 18:27:26 +0000713 BufferBegin+MR.getMachineCodeOffset(),
Evan Cheng02aabbf2008-01-03 02:56:28 +0000714 MR.doesntNeedStub());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000715 } else if (MR.isGlobalValueLazyPtr()) {
716 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
717 BufferBegin+MR.getMachineCodeOffset(),
718 MR.doesntNeedStub());
Evan Chengf141cc42006-07-27 18:21:10 +0000719 } else if (MR.isBasicBlock()) {
720 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000721 } else if (MR.isConstantPoolIndex()) {
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000722 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Evan Cheng52b510b2006-06-23 01:02:37 +0000723 } else {
724 assert(MR.isJumpTableIndex());
725 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000726 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000727
Chris Lattner5be478f2004-11-20 03:46:14 +0000728 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000729
Andrew Lenharth6a974612005-07-28 12:44:13 +0000730 // if we are managing the GOT and the relocation wants an index,
731 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +0000732 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000733 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000734 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000735 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Bill Wendling832171c2006-12-07 20:04:42 +0000736 DOUT << "GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +0000737 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +0000738 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +0000739 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000740 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000741 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000742 }
743
Chris Lattner43b429b2006-05-02 18:27:26 +0000744 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +0000745 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000746 }
747
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000748 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000749 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000750 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000751 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Bill Wendling832171c2006-12-07 20:04:42 +0000752 DOUT << "GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +0000753 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
754 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000755 }
756 }
757
Evan Cheng55fc2802006-07-25 20:40:54 +0000758 // Invalidate the icache if necessary.
Evan Cheng55b50532006-07-27 06:33:55 +0000759 synchronizeICache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000760
761 // Add it to the JIT symbol table if the host wants it.
762 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
763 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +0000764
Bill Wendling832171c2006-12-07 20:04:42 +0000765 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
766 << "] Function: " << F.getFunction()->getName()
767 << ": " << (FnEnd-FnStart) << " bytes of text, "
768 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +0000769 Relocations.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +0000770
Chris Lattnerc5633c22007-01-20 20:51:43 +0000771#ifndef NDEBUG
Anton Korobeynikovc6551ff2007-03-06 05:32:48 +0000772 if (sys::hasDisassembler())
773 DOUT << "Disassembled code:\n"
774 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Chris Lattnerc5633c22007-01-20 20:51:43 +0000775#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000776 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000777 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000778 SavedBufferBegin = BufferBegin;
779 SavedBufferEnd = BufferEnd;
780 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000781
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000782 if (MemMgr->NeedsExactSize()) {
783 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000784 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000785
786 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
787 ActualSize);
788 BufferEnd = BufferBegin+ActualSize;
789 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +0000790 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
791 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000792 BufferBegin = SavedBufferBegin;
793 BufferEnd = SavedBufferEnd;
794 CurBufferPtr = SavedCurBufferPtr;
795
796 TheJIT->RegisterTable(FrameRegister);
797 }
798 MMI->EndFunction();
799
Chris Lattner43b429b2006-05-02 18:27:26 +0000800 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000801}
802
Chris Lattner166f2262004-11-22 22:00:25 +0000803void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000804 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000805 if (Constants.empty()) return;
806
Evan Chengcd5731d2006-09-12 20:59:59 +0000807 MachineConstantPoolEntry CPE = Constants.back();
808 unsigned Size = CPE.Offset;
809 const Type *Ty = CPE.isMachineConstantPoolEntry()
Chris Lattner8a650092006-09-13 16:21:10 +0000810 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +0000811 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000812
Evan Cheng97b8c402008-04-12 00:22:01 +0000813 unsigned Align = 1 << MCP->getConstantPoolAlignment();
814 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +0000815 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000816
817 if (ConstantPoolBase == 0) return; // Buffer overflow.
818
Evan Cheng97b8c402008-04-12 00:22:01 +0000819 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
820 << "] (size: " << Size << ", alignment: " << Align << ")\n";
821
Chris Lattner239862c2006-02-09 04:49:59 +0000822 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +0000823 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +0000824 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Evan Chengcd5731d2006-09-12 20:59:59 +0000825 if (Constants[i].isMachineConstantPoolEntry()) {
826 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +0000827 cerr << "Initialize memory with machine specific constant pool entry"
828 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +0000829 abort();
830 }
831 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng97b8c402008-04-12 00:22:01 +0000832 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Chris Lattner1cc08382003-01-13 01:00:12 +0000833 }
834}
835
Nate Begeman37efe672006-04-22 18:53:45 +0000836void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
837 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
838 if (JT.empty()) return;
839
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000840 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +0000841 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000842 NumEntries += JT[i].MBBs.size();
843
844 unsigned EntrySize = MJTI->getEntrySize();
845
Nate Begeman37efe672006-04-22 18:53:45 +0000846 // Just allocate space for all the jump tables now. We will fix up the actual
847 // MBB entries in the tables after we emit the code for each block, since then
848 // we will know the final locations of the MBBs in memory.
849 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000850 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +0000851}
852
Jim Laskeyb92767a2006-12-14 22:53:42 +0000853void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Nate Begeman37efe672006-04-22 18:53:45 +0000854 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000855 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +0000856
Jim Laskeyb92767a2006-12-14 22:53:42 +0000857 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000858 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
859 // For each jump table, place the offset from the beginning of the table
860 // to the target address.
861 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +0000862
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000863 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
864 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
865 // Store the offset of the basic block for this jump table slot in the
866 // memory we allocated for the jump table in 'initJumpTableInfo'
867 intptr_t Base = (intptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000868 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
869 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
870 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
871 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000872 }
873 } else {
874 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
875
876 // For each jump table, map each target in the jump table to the address of
877 // an emitted MachineBasicBlock.
878 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
879
880 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
881 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
882 // Store the address of the basic block for this jump table slot in the
883 // memory we allocated for the jump table in 'initJumpTableInfo'
884 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
885 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
886 }
Nate Begeman37efe672006-04-22 18:53:45 +0000887 }
888}
889
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000890void JITEmitter::startFunctionStub(const GlobalValue* F, unsigned StubSize,
891 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000892 SavedBufferBegin = BufferBegin;
893 SavedBufferEnd = BufferEnd;
894 SavedCurBufferPtr = CurBufferPtr;
895
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000896 BufferBegin = CurBufferPtr = MemMgr->allocateStub(F, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +0000897 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000898}
899
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000900void *JITEmitter::finishFunctionStub(const GlobalValue* F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000901 NumBytes += getCurrentPCOffset();
902 std::swap(SavedBufferBegin, BufferBegin);
903 BufferEnd = SavedBufferEnd;
904 CurBufferPtr = SavedCurBufferPtr;
905 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000906}
907
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000908// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
909// in the constant pool that was last emitted with the 'emitConstantPool'
910// method.
911//
Chris Lattnerb4432f32006-05-03 17:10:41 +0000912intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +0000913 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000914 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +0000915 return (intptr_t)ConstantPoolBase +
916 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000917}
918
Nate Begeman37efe672006-04-22 18:53:45 +0000919// getJumpTableEntryAddress - Return the address of the JumpTable with index
920// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
921//
Chris Lattnerb4432f32006-05-03 17:10:41 +0000922intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +0000923 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
924 assert(Index < JT.size() && "Invalid jump table index!");
925
926 unsigned Offset = 0;
927 unsigned EntrySize = JumpTable->getEntrySize();
928
929 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000930 Offset += JT[i].MBBs.size();
931
932 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +0000933
Nate Begemanc34b2272006-04-25 17:46:32 +0000934 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +0000935}
936
Chris Lattnere993cc22006-05-11 23:08:08 +0000937//===----------------------------------------------------------------------===//
938// Public interface to this file
939//===----------------------------------------------------------------------===//
940
Chris Lattner9f2f1422007-12-06 01:08:09 +0000941MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
942 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +0000943}
944
Misha Brukmand69c1e62003-07-28 19:09:06 +0000945// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000946// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000947// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
948// need to resolve function(s) that are being mis-codegenerated, so we need to
949// resolve their addresses at runtime, and this is the way to do it.
950extern "C" {
951 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000952 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000953 return TheJIT->getPointerToFunction(F);
954 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000955 }
956}
Chris Lattnere993cc22006-05-11 23:08:08 +0000957
958// getPointerToFunctionOrStub - If the specified function has been
959// code-gen'd, return a pointer to the function. If not, compile it, or use
960// a stub to implement lazy compilation if available.
961//
962void *JIT::getPointerToFunctionOrStub(Function *F) {
963 // If we have already code generated the function, just return the address.
964 if (void *Addr = getPointerToGlobalIfAvailable(F))
965 return Addr;
966
Chris Lattnere7484012007-02-24 02:57:03 +0000967 // Get a stub if the target supports it.
968 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
969 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
970 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000971}
972
973/// freeMachineCodeForFunction - release machine code memory for given Function.
974///
975void JIT::freeMachineCodeForFunction(Function *F) {
Chris Lattner8ac66c12008-04-04 05:51:42 +0000976
Chris Lattnere993cc22006-05-11 23:08:08 +0000977 // Delete translation for this from the ExecutionEngine, so it will get
978 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +0000979 void *OldPtr = updateGlobalMapping(F, 0);
980
981 if (OldPtr)
982 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +0000983
984 // Free the actual memory for the function body and related stuff.
985 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
Chris Lattnere7484012007-02-24 02:57:03 +0000986 static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000987}
988