blob: cbfaa09e36dfd08da344792f984bd0f41090b8eb [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"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000035#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000036#include "llvm/Target/TargetInstrInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000037#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000038#include <algorithm>
Chris Lattnerc19aade2003-12-08 08:06:28 +000039using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000040
Chris Lattner36343732006-12-19 22:43:32 +000041STATISTIC(NumBytes, "Number of bytes of machine code compiled");
42STATISTIC(NumRelos, "Number of relocations applied");
43static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000044
Andrew Lenhartha00269b2005-07-29 23:40:16 +000045
Chris Lattner54266522004-11-20 23:57:07 +000046//===----------------------------------------------------------------------===//
47// JIT lazy compilation code.
48//
49namespace {
Reid Spenceree448632005-07-12 15:51:55 +000050 class JITResolverState {
51 private:
52 /// FunctionToStubMap - Keep track of the stub created for a particular
53 /// function so that we can reuse them if necessary.
54 std::map<Function*, void*> FunctionToStubMap;
55
56 /// StubToFunctionMap - Keep track of the function that each stub
57 /// corresponds to.
58 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000059
Evan Chengbe8c03f2008-01-04 10:46:51 +000060 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
61 /// particular GlobalVariable so that we can reuse them if necessary.
62 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
63
Reid Spenceree448632005-07-12 15:51:55 +000064 public:
65 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
66 assert(locked.holds(TheJIT->lock));
67 return FunctionToStubMap;
68 }
Jeff Cohen00b168892005-07-27 06:12:32 +000069
Reid Spenceree448632005-07-12 15:51:55 +000070 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
71 assert(locked.holds(TheJIT->lock));
72 return StubToFunctionMap;
73 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000074
75 std::map<GlobalValue*, void*>&
76 getGlobalToLazyPtrMap(const MutexGuard& locked) {
77 assert(locked.holds(TheJIT->lock));
78 return GlobalToLazyPtrMap;
79 }
Reid Spenceree448632005-07-12 15:51:55 +000080 };
Jeff Cohen00b168892005-07-27 06:12:32 +000081
Chris Lattner54266522004-11-20 23:57:07 +000082 /// JITResolver - Keep track of, and resolve, call sites for functions that
83 /// have not yet been compiled.
84 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +000085 /// LazyResolverFn - The target lazy resolver function that we actually
86 /// rewrite instructions to use.
87 TargetJITInfo::LazyResolverFn LazyResolverFn;
88
Reid Spenceree448632005-07-12 15:51:55 +000089 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +000090
Chris Lattnerd91ff7c2005-04-18 01:44:27 +000091 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
92 /// external functions.
93 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +000094
95 //map addresses to indexes in the GOT
96 std::map<void*, unsigned> revGOTMap;
97 unsigned nextGOTIndex;
98
Chris Lattnere7484012007-02-24 02:57:03 +000099 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000100 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000101 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000102 TheJIT = &jit;
103
104 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
105 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
106 TheJITResolver = this;
107 }
108
109 ~JITResolver() {
110 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000111 }
Chris Lattner54266522004-11-20 23:57:07 +0000112
113 /// getFunctionStub - This returns a pointer to a function stub, creating
114 /// one on demand as needed.
115 void *getFunctionStub(Function *F);
116
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000117 /// getExternalFunctionStub - Return a stub for the function at the
118 /// specified address, created lazily on demand.
119 void *getExternalFunctionStub(void *FnAddr);
120
Evan Chengbe8c03f2008-01-04 10:46:51 +0000121 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
122 /// GV address.
123 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
124
Chris Lattner5e225582004-11-21 03:37:42 +0000125 /// AddCallbackAtLocation - If the target is capable of rewriting an
126 /// instruction without the use of a stub, record the location of the use so
127 /// we know which function is being used at the location.
128 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000129 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000130 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000131 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000132 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000133 }
134
Andrew Lenharth6a974612005-07-28 12:44:13 +0000135 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000136 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000137 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000138 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000139
Chris Lattner54266522004-11-20 23:57:07 +0000140 /// JITCompilerFn - This function is called to resolve a stub to a compiled
141 /// address. If the LLVM Function corresponding to the stub has not yet
142 /// been compiled, this function compiles it first.
143 static void *JITCompilerFn(void *Stub);
144 };
145}
146
Chris Lattnere7484012007-02-24 02:57:03 +0000147JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000148
149/// getFunctionStub - This returns a pointer to a function stub, creating
150/// one on demand as needed.
151void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000152 MutexGuard locked(TheJIT->lock);
153
Chris Lattner54266522004-11-20 23:57:07 +0000154 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000155 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000156 if (Stub) return Stub;
157
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000158 // Call the lazy resolver function unless we already KNOW it is an external
159 // function, in which case we just skip the lazy resolution step.
Chris Lattner870286a2006-06-01 17:29:22 +0000160 void *Actual = (void*)(intptr_t)LazyResolverFn;
Gabor Greifa99be512007-07-05 17:07:56 +0000161 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000162 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000163
Chris Lattner54266522004-11-20 23:57:07 +0000164 // Otherwise, codegen a new stub. For now, the stub will call the lazy
165 // resolver function.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000166 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000167 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000168
Chris Lattner870286a2006-06-01 17:29:22 +0000169 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000170 // If we are getting the stub for an external function, we really want the
171 // address of the stub in the GlobalAddressMap for the JIT, not the address
172 // of the external function.
173 TheJIT->updateGlobalMapping(F, Stub);
174 }
Chris Lattner54266522004-11-20 23:57:07 +0000175
Bill Wendling832171c2006-12-07 20:04:42 +0000176 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
177 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000178
Chris Lattner54266522004-11-20 23:57:07 +0000179 // Finally, keep track of the stub-to-Function mapping so that the
180 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000181 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000182 return Stub;
183}
184
Evan Chengbe8c03f2008-01-04 10:46:51 +0000185/// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
186/// GV address.
187void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
188 MutexGuard locked(TheJIT->lock);
189
190 // If we already have a stub for this global variable, recycle it.
191 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
192 if (LazyPtr) return LazyPtr;
193
194 // Otherwise, codegen a new lazy pointer.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000195 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GV, GVAddress,
Evan Chengbe8c03f2008-01-04 10:46:51 +0000196 *TheJIT->getCodeEmitter());
197
198 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
199 << GV->getName() << "'\n";
200
201 return LazyPtr;
202}
203
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000204/// getExternalFunctionStub - Return a stub for the function at the
205/// specified address, created lazily on demand.
206void *JITResolver::getExternalFunctionStub(void *FnAddr) {
207 // If we already have a stub for this function, recycle it.
208 void *&Stub = ExternalFnToStubMap[FnAddr];
209 if (Stub) return Stub;
210
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000211 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000212 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000213
Bill Wendling832171c2006-12-07 20:04:42 +0000214 DOUT << "JIT: Stub emitted at [" << Stub
215 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000216 return Stub;
217}
218
Andrew Lenharth6a974612005-07-28 12:44:13 +0000219unsigned JITResolver::getGOTIndexForAddr(void* addr) {
220 unsigned idx = revGOTMap[addr];
221 if (!idx) {
222 idx = ++nextGOTIndex;
223 revGOTMap[addr] = idx;
Evan Cheng97b8c402008-04-12 00:22:01 +0000224 DOUT << "Adding GOT entry " << idx << " for addr " << addr << "\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000225 }
226 return idx;
227}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000228
Chris Lattner54266522004-11-20 23:57:07 +0000229/// JITCompilerFn - This function is called when a lazy compilation stub has
230/// been entered. It looks up which function this stub corresponds to, compiles
231/// it if necessary, then returns the resultant function pointer.
232void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000233 JITResolver &JR = *TheJITResolver;
Misha Brukmanf976c852005-04-21 22:55:34 +0000234
Reid Spenceree448632005-07-12 15:51:55 +0000235 MutexGuard locked(TheJIT->lock);
236
Chris Lattner54266522004-11-20 23:57:07 +0000237 // The address given to us for the stub may not be exactly right, it might be
238 // a little bit after the stub. As such, use upper_bound to find it.
239 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000240 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
Chris Lattner21998772006-01-07 06:20:51 +0000241 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
242 "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000243 Function *F = (--I)->second;
244
Evan Cheng9da60f92007-06-30 00:10:37 +0000245 // If we have already code generated the function, just return the address.
246 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000247
Evan Cheng9da60f92007-06-30 00:10:37 +0000248 if (!Result) {
249 // Otherwise we don't have it, do lazy compilation now.
250
251 // If lazy compilation is disabled, emit a useful error message and abort.
252 if (TheJIT->isLazyCompilationDisabled()) {
253 cerr << "LLVM JIT requested to do lazy compilation of function '"
254 << F->getName() << "' when lazy compiles are disabled!\n";
255 abort();
256 }
257
258 // We might like to remove the stub from the StubToFunction map.
259 // We can't do that! Multiple threads could be stuck, waiting to acquire the
260 // lock above. As soon as the 1st function finishes compiling the function,
261 // the next one will be released, and needs to be able to find the function
262 // it needs to call.
263 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000264
Evan Cheng9da60f92007-06-30 00:10:37 +0000265 DOUT << "JIT: Lazily resolving function '" << F->getName()
266 << "' In stub ptr = " << Stub << " actual ptr = "
267 << I->first << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000268
Evan Cheng9da60f92007-06-30 00:10:37 +0000269 Result = TheJIT->getPointerToFunction(F);
270 }
Chris Lattner54266522004-11-20 23:57:07 +0000271
272 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000273 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000274
275 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000276
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000277 // What we will do is set the compiled function address to map to the
278 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000279 // if they see it still using the stub address.
280 // Note: this is done so the Resolver doesn't have to manage GOT memory
281 // Do this without allocating map space if the target isn't using a GOT
282 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
283 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
284
Chris Lattner54266522004-11-20 23:57:07 +0000285 return Result;
286}
Chris Lattner688506d2003-08-14 18:35:27 +0000287
Chris Lattner8ac66c12008-04-04 05:51:42 +0000288//===----------------------------------------------------------------------===//
289// Function Index Support
290
291// On MacOS we generate an index of currently JIT'd functions so that
292// performance tools can determine a symbol name and accurate code range for a
293// PC value. Because performance tools are generally asynchronous, the code
294// below is written with the hope that it could be interrupted at any time and
295// have useful answers. However, we don't go crazy with atomic operations, we
296// just do a "reasonable effort".
297#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000298#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000299#endif
300
301/// JitSymbolEntry - Each function that is JIT compiled results in one of these
302/// being added to an array of symbols. This indicates the name of the function
303/// as well as the address range it occupies. This allows the client to map
304/// from a PC value to the name of the function.
305struct JitSymbolEntry {
306 const char *FnName; // FnName - a strdup'd string.
307 void *FnStart;
308 intptr_t FnSize;
309};
310
311
312struct JitSymbolTable {
313 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
314 /// pointer is not used right now, but might be used in the future. Consider
315 /// it reserved for future use.
316 JitSymbolTable *NextPtr;
317
318 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
319 /// 'NumSymbols' symbols are valid.
320 JitSymbolEntry *Symbols;
321
322 /// NumSymbols - This indicates the number entries in the Symbols array that
323 /// are valid.
324 unsigned NumSymbols;
325
326 /// NumAllocated - This indicates the amount of space we have in the Symbols
327 /// array. This is a private field that should not be read by external tools.
328 unsigned NumAllocated;
329};
330
331#if ENABLE_JIT_SYMBOL_TABLE
332JitSymbolTable *__jitSymbolTable;
333#endif
334
335static void AddFunctionToSymbolTable(const char *FnName,
336 void *FnStart, intptr_t FnSize) {
337 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
338 JitSymbolTable **SymTabPtrPtr = 0;
339#if !ENABLE_JIT_SYMBOL_TABLE
340 return;
341#else
342 SymTabPtrPtr = &__jitSymbolTable;
343#endif
344
345 // If this is the first entry in the symbol table, add the JitSymbolTable
346 // index.
347 if (*SymTabPtrPtr == 0) {
348 JitSymbolTable *New = new JitSymbolTable();
349 New->NextPtr = 0;
350 New->Symbols = 0;
351 New->NumSymbols = 0;
352 New->NumAllocated = 0;
353 *SymTabPtrPtr = New;
354 }
355
356 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
357
358 // If we have space in the table, reallocate the table.
359 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
360 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000361 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000362 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
363 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
364
365 // Copy the old entries over.
366 memcpy(NewSymbols, OldSymbols,
Chris Lattner3b374482008-04-13 07:04:56 +0000367 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000368
369 // Swap the new symbols in, delete the old ones.
370 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000371 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000372 delete [] OldSymbols;
373 }
374
375 // Otherwise, we have enough space, just tack it onto the end of the array.
376 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
377 Entry.FnName = strdup(FnName);
378 Entry.FnStart = FnStart;
379 Entry.FnSize = FnSize;
380 ++SymTabPtr->NumSymbols;
381}
382
383static void RemoveFunctionFromSymbolTable(void *FnStart) {
384 assert(FnStart && "Invalid function pointer");
385 JitSymbolTable **SymTabPtrPtr = 0;
386#if !ENABLE_JIT_SYMBOL_TABLE
387 return;
388#else
389 SymTabPtrPtr = &__jitSymbolTable;
390#endif
391
392 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
393 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
394
395 // Scan the table to find its index. The table is not sorted, so do a linear
396 // scan.
397 unsigned Index;
398 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
399 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
400
401 // Once we have an index, we know to nuke this entry, overwrite it with the
402 // entry at the end of the array, making the last entry redundant.
403 const char *OldName = Symbols[Index].FnName;
404 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
405 free((void*)OldName);
406
407 // Drop the number of symbols in the table.
408 --SymTabPtr->NumSymbols;
409
410 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begemanf44085a2008-05-18 19:09:10 +0000411 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000412 return;
413
414 *SymTabPtrPtr = 0;
415 delete [] Symbols;
416 delete SymTabPtr;
417}
Chris Lattner688506d2003-08-14 18:35:27 +0000418
Chris Lattner54266522004-11-20 23:57:07 +0000419//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000420// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000421//
Chris Lattner688506d2003-08-14 18:35:27 +0000422namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000423 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
424 /// used to output functions to memory for execution.
425 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000426 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000427
Chris Lattner6125fdd2003-05-09 03:30:07 +0000428 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000429 // save BufferBegin/BufferEnd/CurBufferPtr here.
430 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000431
Chris Lattner5be478f2004-11-20 03:46:14 +0000432 /// Relocations - These are the relocations that the function needs, as
433 /// emitted.
434 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000435
436 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
437 /// It is filled in by the StartMachineBasicBlock callback and queried by
438 /// the getMachineBasicBlockAddress callback.
439 std::vector<intptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000440
Chris Lattner239862c2006-02-09 04:49:59 +0000441 /// ConstantPool - The constant pool for the current function.
442 ///
443 MachineConstantPool *ConstantPool;
444
445 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
446 ///
447 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000448
Nate Begeman019f8512006-09-10 23:03:44 +0000449 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000450 ///
451 MachineJumpTableInfo *JumpTable;
452
453 /// JumpTableBase - A pointer to the first entry in the jump table.
454 ///
455 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000456
Chris Lattnere7484012007-02-24 02:57:03 +0000457 /// Resolver - This contains info about the currently resolved functions.
458 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000459
460 /// DE - The dwarf emitter for the jit.
461 JITDwarfEmitter *DE;
462
463 /// LabelLocations - This vector is a mapping from Label ID's to their
464 /// address.
465 std::vector<intptr_t> LabelLocations;
466
467 /// MMI - Machine module info for exception informations
468 MachineModuleInfo* MMI;
469
Chris Lattnere7484012007-02-24 02:57:03 +0000470 public:
Chris Lattner9f2f1422007-12-06 01:08:09 +0000471 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
472 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000473 if (jit.getJITInfo().needsGOT()) {
474 MemMgr->AllocateGOT();
475 DOUT << "JIT is managing a GOT\n";
476 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000477
478 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000479 }
480 ~JITEmitter() {
481 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000482 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000483 }
Chris Lattnere7484012007-02-24 02:57:03 +0000484
485 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000486
487 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000488 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000489
490 void emitConstantPool(MachineConstantPool *MCP);
491 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000492 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000493
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000494 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
495 unsigned Alignment = 1);
496 virtual void* finishFunctionStub(const GlobalValue *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000497
Chris Lattner5be478f2004-11-20 03:46:14 +0000498 virtual void addRelocation(const MachineRelocation &MR) {
499 Relocations.push_back(MR);
500 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000501
502 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
503 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
504 MBBLocations.resize((MBB->getNumber()+1)*2);
505 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
506 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000507
Chris Lattnerb4432f32006-05-03 17:10:41 +0000508 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
509 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000510
Chris Lattnerb4432f32006-05-03 17:10:41 +0000511 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
512 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
513 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
514 return MBBLocations[MBB->getNumber()];
515 }
516
Chris Lattnere993cc22006-05-11 23:08:08 +0000517 /// deallocateMemForFunction - Deallocate all memory for the specified
518 /// function body.
519 void deallocateMemForFunction(Function *F) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000520 MemMgr->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000521 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000522
523 virtual void emitLabel(uint64_t LabelID) {
524 if (LabelLocations.size() <= LabelID)
525 LabelLocations.resize((LabelID+1)*2);
526 LabelLocations[LabelID] = getCurrentPCValue();
527 }
528
529 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
530 assert(LabelLocations.size() > (unsigned)LabelID &&
531 LabelLocations[LabelID] && "Label not emitted!");
532 return LabelLocations[LabelID];
533 }
534
535 virtual void setModuleInfo(MachineModuleInfo* Info) {
536 MMI = Info;
537 if (ExceptionHandling) DE->setModuleInfo(Info);
538 }
539
Chris Lattner54266522004-11-20 23:57:07 +0000540 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000541 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000542 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
543 bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000544 };
545}
546
Chris Lattner166f2262004-11-22 22:00:25 +0000547void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
548 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000549 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
550 /// FIXME: If we straightened things out, this could actually emit the
551 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000552 return TheJIT->getOrEmitGlobalVariable(GV);
553 }
Chris Lattner18e04592008-06-25 20:21:35 +0000554 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
555 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal());
Chris Lattner54266522004-11-20 23:57:07 +0000556
557 // If we have already compiled the function, return a pointer to its body.
558 Function *F = cast<Function>(V);
559 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
560 if (ResultPtr) return ResultPtr;
561
Gabor Greifa99be512007-07-05 17:07:56 +0000562 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattner54266522004-11-20 23:57:07 +0000563 // If this is an external function pointer, we can force the JIT to
564 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000565 if (DoesntNeedStub)
566 return TheJIT->getPointerToFunction(F);
567
Chris Lattnere7484012007-02-24 02:57:03 +0000568 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000569 }
570
Chris Lattner5e225582004-11-21 03:37:42 +0000571 // Okay, the function has not been compiled yet, if the target callback
572 // mechanism is capable of rewriting the instruction directly, prefer to do
573 // that instead of emitting a stub.
574 if (DoesntNeedStub)
Chris Lattnere7484012007-02-24 02:57:03 +0000575 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000576
Chris Lattner54266522004-11-20 23:57:07 +0000577 // Otherwise, we have to emit a lazy resolving stub.
Chris Lattnere7484012007-02-24 02:57:03 +0000578 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000579}
580
Evan Chengbe8c03f2008-01-04 10:46:51 +0000581void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
582 bool DoesntNeedStub) {
583 // Make sure GV is emitted first.
584 // FIXME: For now, if the GV is an external function we force the JIT to
585 // compile it so the lazy pointer will contain the fully resolved address.
586 void *GVAddress = getPointerToGlobal(V, Reference, true);
587 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
588}
589
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000590static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
591 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
592 if (Constants.empty()) return 0;
593
594 MachineConstantPoolEntry CPE = Constants.back();
595 unsigned Size = CPE.Offset;
596 const Type *Ty = CPE.isMachineConstantPoolEntry()
597 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
598 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
599 return Size;
600}
601
602static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
603 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
604 if (JT.empty()) return 0;
605
606 unsigned NumEntries = 0;
607 for (unsigned i = 0, e = JT.size(); i != e; ++i)
608 NumEntries += JT[i].MBBs.size();
609
610 unsigned EntrySize = MJTI->getEntrySize();
611
612 return NumEntries * EntrySize;
613}
614
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000615static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000616 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000617 // Since we do not know where the buffer will be allocated, be pessimistic.
618 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000619}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000620
Chris Lattner166f2262004-11-22 22:00:25 +0000621void JITEmitter::startFunction(MachineFunction &F) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000622 uintptr_t ActualSize = 0;
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000623 if (MemMgr->NeedsExactSize()) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000624 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
625 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
626 MachineConstantPool *MCP = F.getConstantPool();
627
628 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000629 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000630
631 // Add the alignment of the constant pool
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000632 ActualSize = RoundUpToAlign(ActualSize,
633 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000634
635 // Add the constant pool size
636 ActualSize += GetConstantPoolSizeInBytes(MCP);
637
638 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000639 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000640
641 // Add the jump table size
642 ActualSize += GetJumpTableSizeInBytes(MJTI);
643
644 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000645 ActualSize = RoundUpToAlign(ActualSize,
646 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000647
648 // Add the function size
649 ActualSize += TII->GetFunctionSizeInBytes(F);
650 }
651
Chris Lattner8907b4b2007-12-05 23:39:57 +0000652 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
653 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000654 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000655
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000656 // Ensure the constant pool/jump table info is at least 4-byte aligned.
657 emitAlignment(16);
658
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000659 emitConstantPool(F.getConstantPool());
660 initJumpTableInfo(F.getJumpTableInfo());
661
662 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000663 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000664 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000665
Chris Lattnerb4432f32006-05-03 17:10:41 +0000666 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000667}
668
Chris Lattner43b429b2006-05-02 18:27:26 +0000669bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000670 if (CurBufferPtr == BufferEnd) {
671 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +0000672 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +0000673 abort();
674 }
675
Jim Laskeyb92767a2006-12-14 22:53:42 +0000676 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +0000677
Chris Lattnera8279532006-06-16 18:09:26 +0000678 // FnStart is the start of the text, not the start of the constant pool and
679 // other per-function data.
680 unsigned char *FnStart =
681 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
682 unsigned char *FnEnd = CurBufferPtr;
683
Chris Lattner8907b4b2007-12-05 23:39:57 +0000684 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Chris Lattnera8279532006-06-16 18:09:26 +0000685 NumBytes += FnEnd-FnStart;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000686
Chris Lattner5be478f2004-11-20 03:46:14 +0000687 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000688 NumRelos += Relocations.size();
689
Chris Lattner5be478f2004-11-20 03:46:14 +0000690 // Resolve the relocations to concrete pointers.
691 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
692 MachineRelocation &MR = Relocations[i];
693 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000694 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000695 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000696
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000697 // If the target REALLY wants a stub for this function, emit it now.
Evan Cheng02aabbf2008-01-03 02:56:28 +0000698 if (!MR.doesntNeedStub())
Chris Lattnere7484012007-02-24 02:57:03 +0000699 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000700 } else if (MR.isGlobalValue()) {
Chris Lattner5e225582004-11-21 03:37:42 +0000701 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
Chris Lattner43b429b2006-05-02 18:27:26 +0000702 BufferBegin+MR.getMachineCodeOffset(),
Evan Cheng02aabbf2008-01-03 02:56:28 +0000703 MR.doesntNeedStub());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000704 } else if (MR.isGlobalValueLazyPtr()) {
705 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
706 BufferBegin+MR.getMachineCodeOffset(),
707 MR.doesntNeedStub());
Evan Chengf141cc42006-07-27 18:21:10 +0000708 } else if (MR.isBasicBlock()) {
709 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000710 } else if (MR.isConstantPoolIndex()) {
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000711 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Evan Cheng52b510b2006-06-23 01:02:37 +0000712 } else {
713 assert(MR.isJumpTableIndex());
714 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000715 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000716
Chris Lattner5be478f2004-11-20 03:46:14 +0000717 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000718
Andrew Lenharth6a974612005-07-28 12:44:13 +0000719 // if we are managing the GOT and the relocation wants an index,
720 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +0000721 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000722 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000723 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000724 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Bill Wendling832171c2006-12-07 20:04:42 +0000725 DOUT << "GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +0000726 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +0000727 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +0000728 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000729 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000730 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000731 }
732
Chris Lattner43b429b2006-05-02 18:27:26 +0000733 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +0000734 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000735 }
736
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000737 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000738 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000739 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000740 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Bill Wendling832171c2006-12-07 20:04:42 +0000741 DOUT << "GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +0000742 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
743 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000744 }
745 }
746
Evan Cheng55fc2802006-07-25 20:40:54 +0000747 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +0000748 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000749
750 // Add it to the JIT symbol table if the host wants it.
751 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
752 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +0000753
Bill Wendling832171c2006-12-07 20:04:42 +0000754 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
755 << "] Function: " << F.getFunction()->getName()
756 << ": " << (FnEnd-FnStart) << " bytes of text, "
757 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +0000758 Relocations.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +0000759
Chris Lattnerc5633c22007-01-20 20:51:43 +0000760#ifndef NDEBUG
Anton Korobeynikovc6551ff2007-03-06 05:32:48 +0000761 if (sys::hasDisassembler())
762 DOUT << "Disassembled code:\n"
763 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Chris Lattnerc5633c22007-01-20 20:51:43 +0000764#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000765 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000766 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000767 SavedBufferBegin = BufferBegin;
768 SavedBufferEnd = BufferEnd;
769 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000770
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000771 if (MemMgr->NeedsExactSize()) {
772 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000773 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000774
775 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
776 ActualSize);
777 BufferEnd = BufferBegin+ActualSize;
778 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +0000779 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
780 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000781 BufferBegin = SavedBufferBegin;
782 BufferEnd = SavedBufferEnd;
783 CurBufferPtr = SavedCurBufferPtr;
784
785 TheJIT->RegisterTable(FrameRegister);
786 }
787 MMI->EndFunction();
788
Chris Lattner43b429b2006-05-02 18:27:26 +0000789 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000790}
791
Chris Lattner166f2262004-11-22 22:00:25 +0000792void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000793 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000794 if (Constants.empty()) return;
795
Evan Chengcd5731d2006-09-12 20:59:59 +0000796 MachineConstantPoolEntry CPE = Constants.back();
797 unsigned Size = CPE.Offset;
798 const Type *Ty = CPE.isMachineConstantPoolEntry()
Chris Lattner8a650092006-09-13 16:21:10 +0000799 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +0000800 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000801
Evan Cheng97b8c402008-04-12 00:22:01 +0000802 unsigned Align = 1 << MCP->getConstantPoolAlignment();
803 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +0000804 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000805
806 if (ConstantPoolBase == 0) return; // Buffer overflow.
807
Evan Cheng97b8c402008-04-12 00:22:01 +0000808 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
809 << "] (size: " << Size << ", alignment: " << Align << ")\n";
810
Chris Lattner239862c2006-02-09 04:49:59 +0000811 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +0000812 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +0000813 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Evan Chengcd5731d2006-09-12 20:59:59 +0000814 if (Constants[i].isMachineConstantPoolEntry()) {
815 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +0000816 cerr << "Initialize memory with machine specific constant pool entry"
817 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +0000818 abort();
819 }
820 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng97b8c402008-04-12 00:22:01 +0000821 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Chris Lattner1cc08382003-01-13 01:00:12 +0000822 }
823}
824
Nate Begeman37efe672006-04-22 18:53:45 +0000825void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
826 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
827 if (JT.empty()) return;
828
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000829 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +0000830 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000831 NumEntries += JT[i].MBBs.size();
832
833 unsigned EntrySize = MJTI->getEntrySize();
834
Nate Begeman37efe672006-04-22 18:53:45 +0000835 // Just allocate space for all the jump tables now. We will fix up the actual
836 // MBB entries in the tables after we emit the code for each block, since then
837 // we will know the final locations of the MBBs in memory.
838 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000839 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +0000840}
841
Jim Laskeyb92767a2006-12-14 22:53:42 +0000842void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Nate Begeman37efe672006-04-22 18:53:45 +0000843 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000844 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +0000845
Jim Laskeyb92767a2006-12-14 22:53:42 +0000846 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000847 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
848 // For each jump table, place the offset from the beginning of the table
849 // to the target address.
850 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +0000851
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000852 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
853 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
854 // Store the offset of the basic block for this jump table slot in the
855 // memory we allocated for the jump table in 'initJumpTableInfo'
856 intptr_t Base = (intptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000857 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
858 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
859 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
860 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000861 }
862 } else {
863 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
864
865 // For each jump table, map each target in the jump table to the address of
866 // an emitted MachineBasicBlock.
867 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
868
869 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
870 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
871 // Store the address of the basic block for this jump table slot in the
872 // memory we allocated for the jump table in 'initJumpTableInfo'
873 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
874 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
875 }
Nate Begeman37efe672006-04-22 18:53:45 +0000876 }
877}
878
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000879void JITEmitter::startFunctionStub(const GlobalValue* F, unsigned StubSize,
880 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000881 SavedBufferBegin = BufferBegin;
882 SavedBufferEnd = BufferEnd;
883 SavedCurBufferPtr = CurBufferPtr;
884
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000885 BufferBegin = CurBufferPtr = MemMgr->allocateStub(F, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +0000886 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000887}
888
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000889void *JITEmitter::finishFunctionStub(const GlobalValue* F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000890 NumBytes += getCurrentPCOffset();
891 std::swap(SavedBufferBegin, BufferBegin);
892 BufferEnd = SavedBufferEnd;
893 CurBufferPtr = SavedCurBufferPtr;
894 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000895}
896
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000897// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
898// in the constant pool that was last emitted with the 'emitConstantPool'
899// method.
900//
Chris Lattnerb4432f32006-05-03 17:10:41 +0000901intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +0000902 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000903 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +0000904 return (intptr_t)ConstantPoolBase +
905 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000906}
907
Nate Begeman37efe672006-04-22 18:53:45 +0000908// getJumpTableEntryAddress - Return the address of the JumpTable with index
909// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
910//
Chris Lattnerb4432f32006-05-03 17:10:41 +0000911intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +0000912 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
913 assert(Index < JT.size() && "Invalid jump table index!");
914
915 unsigned Offset = 0;
916 unsigned EntrySize = JumpTable->getEntrySize();
917
918 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000919 Offset += JT[i].MBBs.size();
920
921 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +0000922
Nate Begemanc34b2272006-04-25 17:46:32 +0000923 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +0000924}
925
Chris Lattnere993cc22006-05-11 23:08:08 +0000926//===----------------------------------------------------------------------===//
927// Public interface to this file
928//===----------------------------------------------------------------------===//
929
Chris Lattner9f2f1422007-12-06 01:08:09 +0000930MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
931 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +0000932}
933
Misha Brukmand69c1e62003-07-28 19:09:06 +0000934// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000935// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000936// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
937// need to resolve function(s) that are being mis-codegenerated, so we need to
938// resolve their addresses at runtime, and this is the way to do it.
939extern "C" {
940 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000941 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000942 return TheJIT->getPointerToFunction(F);
943 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000944 }
945}
Chris Lattnere993cc22006-05-11 23:08:08 +0000946
947// getPointerToFunctionOrStub - If the specified function has been
948// code-gen'd, return a pointer to the function. If not, compile it, or use
949// a stub to implement lazy compilation if available.
950//
951void *JIT::getPointerToFunctionOrStub(Function *F) {
952 // If we have already code generated the function, just return the address.
953 if (void *Addr = getPointerToGlobalIfAvailable(F))
954 return Addr;
955
Chris Lattnere7484012007-02-24 02:57:03 +0000956 // Get a stub if the target supports it.
957 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
958 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
959 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000960}
961
962/// freeMachineCodeForFunction - release machine code memory for given Function.
963///
964void JIT::freeMachineCodeForFunction(Function *F) {
Chris Lattner8ac66c12008-04-04 05:51:42 +0000965
Chris Lattnere993cc22006-05-11 23:08:08 +0000966 // Delete translation for this from the ExecutionEngine, so it will get
967 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +0000968 void *OldPtr = updateGlobalMapping(F, 0);
969
970 if (OldPtr)
971 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +0000972
973 // Free the actual memory for the function body and related stuff.
974 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
Chris Lattnere7484012007-02-24 02:57:03 +0000975 static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000976}
977