blob: 06c195a34f594b14c50d9626105917f9334a26ff [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"
Dale Johannesendd947ea2008-08-07 01:30:15 +000018#include "llvm/Constants.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000019#include "llvm/Module.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000020#include "llvm/DerivedTypes.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"
Dale Johannesendd947ea2008-08-07 01:30:15 +000028#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000029#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000030#include "llvm/Target/TargetJITInfo.h"
Jim Laskeyacd80ac2006-12-14 19:17:33 +000031#include "llvm/Target/TargetMachine.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000032#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000034#include "llvm/Support/MutexGuard.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000035#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000036#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000037#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000038#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000040#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000041#ifndef NDEBUG
42#include <iomanip>
43#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner36343732006-12-19 22:43:32 +000046STATISTIC(NumBytes, "Number of bytes of machine code compiled");
47STATISTIC(NumRelos, "Number of relocations applied");
48static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000049
Andrew Lenhartha00269b2005-07-29 23:40:16 +000050
Chris Lattner54266522004-11-20 23:57:07 +000051//===----------------------------------------------------------------------===//
52// JIT lazy compilation code.
53//
54namespace {
Reid Spenceree448632005-07-12 15:51:55 +000055 class JITResolverState {
56 private:
57 /// FunctionToStubMap - Keep track of the stub created for a particular
58 /// function so that we can reuse them if necessary.
59 std::map<Function*, void*> FunctionToStubMap;
60
61 /// StubToFunctionMap - Keep track of the function that each stub
62 /// corresponds to.
63 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000064
Evan Chengc96a8e72008-11-05 01:50:32 +000065 /// GlobalToNonLazyPtrMap - Keep track of the lazy pointer created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000066 /// particular GlobalVariable so that we can reuse them if necessary.
Evan Chengc96a8e72008-11-05 01:50:32 +000067 std::map<GlobalValue*, void*> GlobalToNonLazyPtrMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000068
Reid Spenceree448632005-07-12 15:51:55 +000069 public:
70 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
71 assert(locked.holds(TheJIT->lock));
72 return FunctionToStubMap;
73 }
Jeff Cohen00b168892005-07-27 06:12:32 +000074
Reid Spenceree448632005-07-12 15:51:55 +000075 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
76 assert(locked.holds(TheJIT->lock));
77 return StubToFunctionMap;
78 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000079
80 std::map<GlobalValue*, void*>&
Evan Chengc96a8e72008-11-05 01:50:32 +000081 getGlobalToNonLazyPtrMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000082 assert(locked.holds(TheJIT->lock));
Evan Chengc96a8e72008-11-05 01:50:32 +000083 return GlobalToNonLazyPtrMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000084 }
Reid Spenceree448632005-07-12 15:51:55 +000085 };
Jeff Cohen00b168892005-07-27 06:12:32 +000086
Chris Lattner54266522004-11-20 23:57:07 +000087 /// JITResolver - Keep track of, and resolve, call sites for functions that
88 /// have not yet been compiled.
89 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +000090 /// LazyResolverFn - The target lazy resolver function that we actually
91 /// rewrite instructions to use.
92 TargetJITInfo::LazyResolverFn LazyResolverFn;
93
Reid Spenceree448632005-07-12 15:51:55 +000094 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +000095
Chris Lattnerd91ff7c2005-04-18 01:44:27 +000096 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
97 /// external functions.
98 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +000099
100 //map addresses to indexes in the GOT
101 std::map<void*, unsigned> revGOTMap;
102 unsigned nextGOTIndex;
103
Chris Lattnere7484012007-02-24 02:57:03 +0000104 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000105 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000106 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000107 TheJIT = &jit;
108
109 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
110 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
111 TheJITResolver = this;
112 }
113
114 ~JITResolver() {
115 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000116 }
Chris Lattner54266522004-11-20 23:57:07 +0000117
118 /// getFunctionStub - This returns a pointer to a function stub, creating
119 /// one on demand as needed.
120 void *getFunctionStub(Function *F);
121
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000122 /// getExternalFunctionStub - Return a stub for the function at the
123 /// specified address, created lazily on demand.
124 void *getExternalFunctionStub(void *FnAddr);
125
Evan Chengc96a8e72008-11-05 01:50:32 +0000126 /// getGlobalValueNonLazyPtr - Return a non-lazy pointer containing the
127 /// specified GV address.
128 void *getGlobalValueNonLazyPtr(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000129
Chris Lattner5e225582004-11-21 03:37:42 +0000130 /// AddCallbackAtLocation - If the target is capable of rewriting an
131 /// instruction without the use of a stub, record the location of the use so
132 /// we know which function is being used at the location.
133 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000134 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000135 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000136 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000137 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000138 }
139
Andrew Lenharth6a974612005-07-28 12:44:13 +0000140 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000141 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000142 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000143 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000144
Chris Lattner54266522004-11-20 23:57:07 +0000145 /// JITCompilerFn - This function is called to resolve a stub to a compiled
146 /// address. If the LLVM Function corresponding to the stub has not yet
147 /// been compiled, this function compiles it first.
148 static void *JITCompilerFn(void *Stub);
149 };
150}
151
Chris Lattnere7484012007-02-24 02:57:03 +0000152JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000153
154/// getFunctionStub - This returns a pointer to a function stub, creating
155/// one on demand as needed.
156void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000157 MutexGuard locked(TheJIT->lock);
158
Chris Lattner54266522004-11-20 23:57:07 +0000159 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000160 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000161 if (Stub) return Stub;
162
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000163 // Call the lazy resolver function unless we already KNOW it is an external
164 // function, in which case we just skip the lazy resolution step.
Chris Lattner870286a2006-06-01 17:29:22 +0000165 void *Actual = (void*)(intptr_t)LazyResolverFn;
Gabor Greifa99be512007-07-05 17:07:56 +0000166 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000167 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000168
Chris Lattner54266522004-11-20 23:57:07 +0000169 // Otherwise, codegen a new stub. For now, the stub will call the lazy
170 // resolver function.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000171 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000172 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000173
Chris Lattner870286a2006-06-01 17:29:22 +0000174 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000175 // If we are getting the stub for an external function, we really want the
176 // address of the stub in the GlobalAddressMap for the JIT, not the address
177 // of the external function.
178 TheJIT->updateGlobalMapping(F, Stub);
179 }
Chris Lattner54266522004-11-20 23:57:07 +0000180
Bill Wendling832171c2006-12-07 20:04:42 +0000181 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
182 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000183
Chris Lattner54266522004-11-20 23:57:07 +0000184 // Finally, keep track of the stub-to-Function mapping so that the
185 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000186 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000187 return Stub;
188}
189
Evan Chengc96a8e72008-11-05 01:50:32 +0000190/// getGlobalValueNonLazyPtr - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000191/// GV address.
Evan Chengc96a8e72008-11-05 01:50:32 +0000192void *JITResolver::getGlobalValueNonLazyPtr(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000193 MutexGuard locked(TheJIT->lock);
194
195 // If we already have a stub for this global variable, recycle it.
Evan Chengc96a8e72008-11-05 01:50:32 +0000196 void *&NonLazyPtr = state.getGlobalToNonLazyPtrMap(locked)[GV];
197 if (NonLazyPtr) return NonLazyPtr;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000198
199 // Otherwise, codegen a new lazy pointer.
Evan Chengc96a8e72008-11-05 01:50:32 +0000200 NonLazyPtr = TheJIT->getJITInfo().emitGlobalValueNonLazyPtr(GV, GVAddress,
201 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000202
Evan Chengc96a8e72008-11-05 01:50:32 +0000203 DOUT << "JIT: Stub emitted at [" << NonLazyPtr << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000204 << GV->getName() << "'\n";
205
Evan Chengc96a8e72008-11-05 01:50:32 +0000206 return NonLazyPtr;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000207}
208
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000209/// getExternalFunctionStub - Return a stub for the function at the
210/// specified address, created lazily on demand.
211void *JITResolver::getExternalFunctionStub(void *FnAddr) {
212 // If we already have a stub for this function, recycle it.
213 void *&Stub = ExternalFnToStubMap[FnAddr];
214 if (Stub) return Stub;
215
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000216 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000217 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000218
Bill Wendling832171c2006-12-07 20:04:42 +0000219 DOUT << "JIT: Stub emitted at [" << Stub
220 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000221 return Stub;
222}
223
Andrew Lenharth6a974612005-07-28 12:44:13 +0000224unsigned JITResolver::getGOTIndexForAddr(void* addr) {
225 unsigned idx = revGOTMap[addr];
226 if (!idx) {
227 idx = ++nextGOTIndex;
228 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000229 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000230 }
231 return idx;
232}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000233
Chris Lattner54266522004-11-20 23:57:07 +0000234/// JITCompilerFn - This function is called when a lazy compilation stub has
235/// been entered. It looks up which function this stub corresponds to, compiles
236/// it if necessary, then returns the resultant function pointer.
237void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000238 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000239
240 Function* F = 0;
241 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000242
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000243 {
244 // Only lock for getting the Function. The call getPointerToFunction made
245 // in this function might trigger function materializing, which requires
246 // JIT lock to be unlocked.
247 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000248
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000249 // The address given to us for the stub may not be exactly right, it might be
250 // a little bit after the stub. As such, use upper_bound to find it.
251 std::map<void*, Function*>::iterator I =
252 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
253 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
254 "This is not a known stub!");
255 F = (--I)->second;
256 ActualPtr = I->first;
257 }
Chris Lattner54266522004-11-20 23:57:07 +0000258
Evan Cheng9da60f92007-06-30 00:10:37 +0000259 // If we have already code generated the function, just return the address.
260 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000261
Evan Cheng9da60f92007-06-30 00:10:37 +0000262 if (!Result) {
263 // Otherwise we don't have it, do lazy compilation now.
264
265 // If lazy compilation is disabled, emit a useful error message and abort.
266 if (TheJIT->isLazyCompilationDisabled()) {
267 cerr << "LLVM JIT requested to do lazy compilation of function '"
268 << F->getName() << "' when lazy compiles are disabled!\n";
269 abort();
270 }
271
272 // We might like to remove the stub from the StubToFunction map.
273 // We can't do that! Multiple threads could be stuck, waiting to acquire the
274 // lock above. As soon as the 1st function finishes compiling the function,
275 // the next one will be released, and needs to be able to find the function
276 // it needs to call.
277 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000278
Evan Cheng9da60f92007-06-30 00:10:37 +0000279 DOUT << "JIT: Lazily resolving function '" << F->getName()
280 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000281 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000282
Evan Cheng9da60f92007-06-30 00:10:37 +0000283 Result = TheJIT->getPointerToFunction(F);
284 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000285
286 // Reacquire the lock to erase the stub in the map.
287 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000288
289 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000290 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000291
292 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000293
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000294 // What we will do is set the compiled function address to map to the
295 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000296 // if they see it still using the stub address.
297 // Note: this is done so the Resolver doesn't have to manage GOT memory
298 // Do this without allocating map space if the target isn't using a GOT
299 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
300 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
301
Chris Lattner54266522004-11-20 23:57:07 +0000302 return Result;
303}
Chris Lattner688506d2003-08-14 18:35:27 +0000304
Chris Lattner8ac66c12008-04-04 05:51:42 +0000305//===----------------------------------------------------------------------===//
306// Function Index Support
307
308// On MacOS we generate an index of currently JIT'd functions so that
309// performance tools can determine a symbol name and accurate code range for a
310// PC value. Because performance tools are generally asynchronous, the code
311// below is written with the hope that it could be interrupted at any time and
312// have useful answers. However, we don't go crazy with atomic operations, we
313// just do a "reasonable effort".
314#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000315#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000316#endif
317
318/// JitSymbolEntry - Each function that is JIT compiled results in one of these
319/// being added to an array of symbols. This indicates the name of the function
320/// as well as the address range it occupies. This allows the client to map
321/// from a PC value to the name of the function.
322struct JitSymbolEntry {
323 const char *FnName; // FnName - a strdup'd string.
324 void *FnStart;
325 intptr_t FnSize;
326};
327
328
329struct JitSymbolTable {
330 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
331 /// pointer is not used right now, but might be used in the future. Consider
332 /// it reserved for future use.
333 JitSymbolTable *NextPtr;
334
335 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
336 /// 'NumSymbols' symbols are valid.
337 JitSymbolEntry *Symbols;
338
339 /// NumSymbols - This indicates the number entries in the Symbols array that
340 /// are valid.
341 unsigned NumSymbols;
342
343 /// NumAllocated - This indicates the amount of space we have in the Symbols
344 /// array. This is a private field that should not be read by external tools.
345 unsigned NumAllocated;
346};
347
348#if ENABLE_JIT_SYMBOL_TABLE
349JitSymbolTable *__jitSymbolTable;
350#endif
351
352static void AddFunctionToSymbolTable(const char *FnName,
353 void *FnStart, intptr_t FnSize) {
354 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
355 JitSymbolTable **SymTabPtrPtr = 0;
356#if !ENABLE_JIT_SYMBOL_TABLE
357 return;
358#else
359 SymTabPtrPtr = &__jitSymbolTable;
360#endif
361
362 // If this is the first entry in the symbol table, add the JitSymbolTable
363 // index.
364 if (*SymTabPtrPtr == 0) {
365 JitSymbolTable *New = new JitSymbolTable();
366 New->NextPtr = 0;
367 New->Symbols = 0;
368 New->NumSymbols = 0;
369 New->NumAllocated = 0;
370 *SymTabPtrPtr = New;
371 }
372
373 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
374
375 // If we have space in the table, reallocate the table.
376 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
377 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000378 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000379 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
380 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
381
382 // Copy the old entries over.
383 memcpy(NewSymbols, OldSymbols,
Chris Lattner3b374482008-04-13 07:04:56 +0000384 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000385
386 // Swap the new symbols in, delete the old ones.
387 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000388 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000389 delete [] OldSymbols;
390 }
391
392 // Otherwise, we have enough space, just tack it onto the end of the array.
393 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
394 Entry.FnName = strdup(FnName);
395 Entry.FnStart = FnStart;
396 Entry.FnSize = FnSize;
397 ++SymTabPtr->NumSymbols;
398}
399
400static void RemoveFunctionFromSymbolTable(void *FnStart) {
401 assert(FnStart && "Invalid function pointer");
402 JitSymbolTable **SymTabPtrPtr = 0;
403#if !ENABLE_JIT_SYMBOL_TABLE
404 return;
405#else
406 SymTabPtrPtr = &__jitSymbolTable;
407#endif
408
409 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
410 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
411
412 // Scan the table to find its index. The table is not sorted, so do a linear
413 // scan.
414 unsigned Index;
415 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
416 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
417
418 // Once we have an index, we know to nuke this entry, overwrite it with the
419 // entry at the end of the array, making the last entry redundant.
420 const char *OldName = Symbols[Index].FnName;
421 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
422 free((void*)OldName);
423
424 // Drop the number of symbols in the table.
425 --SymTabPtr->NumSymbols;
426
427 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begemanf44085a2008-05-18 19:09:10 +0000428 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000429 return;
430
431 *SymTabPtrPtr = 0;
432 delete [] Symbols;
433 delete SymTabPtr;
434}
Chris Lattner688506d2003-08-14 18:35:27 +0000435
Chris Lattner54266522004-11-20 23:57:07 +0000436//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000437// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000438//
Chris Lattner688506d2003-08-14 18:35:27 +0000439namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000440 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
441 /// used to output functions to memory for execution.
442 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000443 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000444
Chris Lattner6125fdd2003-05-09 03:30:07 +0000445 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000446 // save BufferBegin/BufferEnd/CurBufferPtr here.
447 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000448
Chris Lattner5be478f2004-11-20 03:46:14 +0000449 /// Relocations - These are the relocations that the function needs, as
450 /// emitted.
451 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000452
453 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
454 /// It is filled in by the StartMachineBasicBlock callback and queried by
455 /// the getMachineBasicBlockAddress callback.
456 std::vector<intptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000457
Chris Lattner239862c2006-02-09 04:49:59 +0000458 /// ConstantPool - The constant pool for the current function.
459 ///
460 MachineConstantPool *ConstantPool;
461
462 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
463 ///
464 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000465
Nate Begeman019f8512006-09-10 23:03:44 +0000466 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000467 ///
468 MachineJumpTableInfo *JumpTable;
469
470 /// JumpTableBase - A pointer to the first entry in the jump table.
471 ///
472 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000473
Chris Lattnere7484012007-02-24 02:57:03 +0000474 /// Resolver - This contains info about the currently resolved functions.
475 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000476
477 /// DE - The dwarf emitter for the jit.
478 JITDwarfEmitter *DE;
479
480 /// LabelLocations - This vector is a mapping from Label ID's to their
481 /// address.
482 std::vector<intptr_t> LabelLocations;
483
484 /// MMI - Machine module info for exception informations
485 MachineModuleInfo* MMI;
486
Dale Johannesendd947ea2008-08-07 01:30:15 +0000487 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000488 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000489
Chris Lattnere7484012007-02-24 02:57:03 +0000490 public:
Chris Lattner9f2f1422007-12-06 01:08:09 +0000491 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
492 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000493 if (jit.getJITInfo().needsGOT()) {
494 MemMgr->AllocateGOT();
495 DOUT << "JIT is managing a GOT\n";
496 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000497
498 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000499 }
500 ~JITEmitter() {
501 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000502 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000503 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000504
505 /// classof - Methods for support type inquiry through isa, cast, and
506 /// dyn_cast:
507 ///
508 static inline bool classof(const JITEmitter*) { return true; }
509 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000510
511 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000512
513 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000514 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000515
516 void emitConstantPool(MachineConstantPool *MCP);
517 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000518 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000519
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000520 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
521 unsigned Alignment = 1);
522 virtual void* finishFunctionStub(const GlobalValue *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000523
Nuno Lopescef75272008-10-21 11:42:16 +0000524 /// allocateSpace - Reserves space in the current block if any, or
525 /// allocate a new one of the given size.
526 virtual void *allocateSpace(intptr_t Size, unsigned Alignment);
527
Chris Lattner5be478f2004-11-20 03:46:14 +0000528 virtual void addRelocation(const MachineRelocation &MR) {
529 Relocations.push_back(MR);
530 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000531
532 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
533 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
534 MBBLocations.resize((MBB->getNumber()+1)*2);
535 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000536 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
537 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000538 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000539
Chris Lattnerb4432f32006-05-03 17:10:41 +0000540 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
541 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000542
Chris Lattnerb4432f32006-05-03 17:10:41 +0000543 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
544 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
545 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
546 return MBBLocations[MBB->getNumber()];
547 }
548
Chris Lattnere993cc22006-05-11 23:08:08 +0000549 /// deallocateMemForFunction - Deallocate all memory for the specified
550 /// function body.
551 void deallocateMemForFunction(Function *F) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000552 MemMgr->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000553 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000554
555 virtual void emitLabel(uint64_t LabelID) {
556 if (LabelLocations.size() <= LabelID)
557 LabelLocations.resize((LabelID+1)*2);
558 LabelLocations[LabelID] = getCurrentPCValue();
559 }
560
561 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
562 assert(LabelLocations.size() > (unsigned)LabelID &&
563 LabelLocations[LabelID] && "Label not emitted!");
564 return LabelLocations[LabelID];
565 }
566
567 virtual void setModuleInfo(MachineModuleInfo* Info) {
568 MMI = Info;
569 if (ExceptionHandling) DE->setModuleInfo(Info);
570 }
571
Jim Grosbachcce6c292008-10-03 16:17:20 +0000572 void setMemoryExecutable(void) {
573 MemMgr->setMemoryExecutable();
574 }
575
Chris Lattner54266522004-11-20 23:57:07 +0000576 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000577 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Chengc96a8e72008-11-05 01:50:32 +0000578 void *getPointerToGVNonLazyPtr(GlobalValue *V, void *Reference,
579 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000580 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
581 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
582 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
583 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000584 };
585}
586
Chris Lattner166f2262004-11-22 22:00:25 +0000587void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
588 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000589 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
590 /// FIXME: If we straightened things out, this could actually emit the
591 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000592 return TheJIT->getOrEmitGlobalVariable(GV);
593 }
Chris Lattner18e04592008-06-25 20:21:35 +0000594 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000595 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000596
597 // If we have already compiled the function, return a pointer to its body.
598 Function *F = cast<Function>(V);
599 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
600 if (ResultPtr) return ResultPtr;
601
Gabor Greifa99be512007-07-05 17:07:56 +0000602 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattner54266522004-11-20 23:57:07 +0000603 // If this is an external function pointer, we can force the JIT to
604 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000605 if (DoesntNeedStub)
606 return TheJIT->getPointerToFunction(F);
607
Chris Lattnere7484012007-02-24 02:57:03 +0000608 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000609 }
610
Chris Lattner5e225582004-11-21 03:37:42 +0000611 // Okay, the function has not been compiled yet, if the target callback
612 // mechanism is capable of rewriting the instruction directly, prefer to do
613 // that instead of emitting a stub.
614 if (DoesntNeedStub)
Chris Lattnere7484012007-02-24 02:57:03 +0000615 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000616
Chris Lattner54266522004-11-20 23:57:07 +0000617 // Otherwise, we have to emit a lazy resolving stub.
Chris Lattnere7484012007-02-24 02:57:03 +0000618 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000619}
620
Evan Chengc96a8e72008-11-05 01:50:32 +0000621void *JITEmitter::getPointerToGVNonLazyPtr(GlobalValue *V, void *Reference,
Evan Chengbe8c03f2008-01-04 10:46:51 +0000622 bool DoesntNeedStub) {
623 // Make sure GV is emitted first.
624 // FIXME: For now, if the GV is an external function we force the JIT to
Evan Chengc96a8e72008-11-05 01:50:32 +0000625 // compile it so the non-lazy pointer will contain the fully resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000626 void *GVAddress = getPointerToGlobal(V, Reference, true);
Evan Chengc96a8e72008-11-05 01:50:32 +0000627 return Resolver.getGlobalValueNonLazyPtr(V, GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000628}
629
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000630static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
631 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
632 if (Constants.empty()) return 0;
633
634 MachineConstantPoolEntry CPE = Constants.back();
635 unsigned Size = CPE.Offset;
636 const Type *Ty = CPE.isMachineConstantPoolEntry()
637 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
638 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
639 return Size;
640}
641
642static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
643 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
644 if (JT.empty()) return 0;
645
646 unsigned NumEntries = 0;
647 for (unsigned i = 0, e = JT.size(); i != e; ++i)
648 NumEntries += JT[i].MBBs.size();
649
650 unsigned EntrySize = MJTI->getEntrySize();
651
652 return NumEntries * EntrySize;
653}
654
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000655static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000656 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000657 // Since we do not know where the buffer will be allocated, be pessimistic.
658 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000659}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000660
Dale Johannesendd947ea2008-08-07 01:30:15 +0000661/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
662/// into the running total Size.
663
664unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
665 const Type *ElTy = GV->getType()->getElementType();
666 size_t GVSize = (size_t)TheJIT->getTargetData()->getABITypeSize(ElTy);
667 size_t GVAlign =
668 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000669 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000670 DEBUG(GV->dump());
671 // Assume code section ends with worst possible alignment, so first
672 // variable needs maximal padding.
673 if (Size==0)
674 Size = 1;
675 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
676 Size += GVSize;
677 return Size;
678}
679
680/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
681/// but are referenced from the constant; put them in GVSet and add their
682/// size into the running total Size.
683
684unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
685 unsigned Size) {
686 // If its undefined, return the garbage.
687 if (isa<UndefValue>(C))
688 return Size;
689
690 // If the value is a ConstantExpr
691 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
692 Constant *Op0 = CE->getOperand(0);
693 switch (CE->getOpcode()) {
694 case Instruction::GetElementPtr:
695 case Instruction::Trunc:
696 case Instruction::ZExt:
697 case Instruction::SExt:
698 case Instruction::FPTrunc:
699 case Instruction::FPExt:
700 case Instruction::UIToFP:
701 case Instruction::SIToFP:
702 case Instruction::FPToUI:
703 case Instruction::FPToSI:
704 case Instruction::PtrToInt:
705 case Instruction::IntToPtr:
706 case Instruction::BitCast: {
707 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
708 break;
709 }
710 case Instruction::Add:
711 case Instruction::Sub:
712 case Instruction::Mul:
713 case Instruction::UDiv:
714 case Instruction::SDiv:
715 case Instruction::URem:
716 case Instruction::SRem:
717 case Instruction::And:
718 case Instruction::Or:
719 case Instruction::Xor: {
720 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
721 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
722 break;
723 }
724 default: {
725 cerr << "ConstantExpr not handled: " << *CE << "\n";
726 abort();
727 }
728 }
729 }
730
731 if (C->getType()->getTypeID() == Type::PointerTyID)
732 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000733 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000734 Size = addSizeOfGlobal(GV, Size);
735
736 return Size;
737}
738
739/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
740/// but are referenced from the given initializer.
741
742unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
743 unsigned Size) {
744 if (!isa<UndefValue>(Init) &&
745 !isa<ConstantVector>(Init) &&
746 !isa<ConstantAggregateZero>(Init) &&
747 !isa<ConstantArray>(Init) &&
748 !isa<ConstantStruct>(Init) &&
749 Init->getType()->isFirstClassType())
750 Size = addSizeOfGlobalsInConstantVal(Init, Size);
751 return Size;
752}
753
754/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
755/// globals; then walk the initializers of those globals looking for more.
756/// If their size has not been considered yet, add it into the running total
757/// Size.
758
759unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
760 unsigned Size = 0;
761 GVSet.clear();
762
763 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
764 MBB != E; ++MBB) {
765 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
766 I != E; ++I) {
767 const TargetInstrDesc &Desc = I->getDesc();
768 const MachineInstr &MI = *I;
769 unsigned NumOps = Desc.getNumOperands();
770 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
771 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000772 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000773 GlobalValue* V = MO.getGlobal();
774 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
775 if (!GV)
776 continue;
777 // If seen in previous function, it will have an entry here.
778 if (TheJIT->getPointerToGlobalIfAvailable(GV))
779 continue;
780 // If seen earlier in this function, it will have an entry here.
781 // FIXME: it should be possible to combine these tables, by
782 // assuming the addresses of the new globals in this module
783 // start at 0 (or something) and adjusting them after codegen
784 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000785 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000786 // A variable as yet unseen. Add in its size.
787 Size = addSizeOfGlobal(GV, Size);
788 }
789 }
790 }
791 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000792 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000793 // Look for more globals that are referenced only from initializers.
794 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000795 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000796 I != GVSet.end(); I++) {
797 const GlobalVariable* GV = *I;
798 if (GV->hasInitializer())
799 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
800 }
801
802 return Size;
803}
804
Chris Lattner166f2262004-11-22 22:00:25 +0000805void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000806 DOUT << "JIT: Starting CodeGen of Function "
807 << F.getFunction()->getName() << "\n";
808
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000809 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000810 // Set the memory writable, if it's not already
811 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000812 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000813 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000814 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
815 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
816 MachineConstantPool *MCP = F.getConstantPool();
817
818 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000819 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000820
821 // Add the alignment of the constant pool
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000822 ActualSize = RoundUpToAlign(ActualSize,
823 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000824
825 // Add the constant pool size
826 ActualSize += GetConstantPoolSizeInBytes(MCP);
827
828 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000829 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000830
831 // Add the jump table size
832 ActualSize += GetJumpTableSizeInBytes(MJTI);
833
834 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000835 ActualSize = RoundUpToAlign(ActualSize,
836 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000837
838 // Add the function size
839 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000840
Evan Chengeb5d95a2008-11-06 17:46:04 +0000841 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000842 // Add the size of the globals that will be allocated after this function.
843 // These are all the ones referenced from this function that were not
844 // previously allocated.
845 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000846 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000847 }
848
Chris Lattner8907b4b2007-12-05 23:39:57 +0000849 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
850 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000851 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000852
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000853 // Ensure the constant pool/jump table info is at least 4-byte aligned.
854 emitAlignment(16);
855
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000856 emitConstantPool(F.getConstantPool());
857 initJumpTableInfo(F.getJumpTableInfo());
858
859 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000860 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000861 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000862
Chris Lattnerb4432f32006-05-03 17:10:41 +0000863 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000864}
865
Chris Lattner43b429b2006-05-02 18:27:26 +0000866bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000867 if (CurBufferPtr == BufferEnd) {
868 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +0000869 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +0000870 abort();
871 }
872
Jim Laskeyb92767a2006-12-14 22:53:42 +0000873 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +0000874
Chris Lattnera8279532006-06-16 18:09:26 +0000875 // FnStart is the start of the text, not the start of the constant pool and
876 // other per-function data.
877 unsigned char *FnStart =
878 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000879
Chris Lattner5be478f2004-11-20 03:46:14 +0000880 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000881 NumRelos += Relocations.size();
882
Chris Lattner5be478f2004-11-20 03:46:14 +0000883 // Resolve the relocations to concrete pointers.
884 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
885 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +0000886 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +0000887 if (!MR.letTargetResolve()) {
888 if (MR.isString()) {
889 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000890
Evan Chengef5784e2008-10-29 23:54:46 +0000891 // If the target REALLY wants a stub for this function, emit it now.
892 if (!MR.doesntNeedStub())
893 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
894 } else if (MR.isGlobalValue()) {
895 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
896 BufferBegin+MR.getMachineCodeOffset(),
897 MR.doesntNeedStub());
Evan Chengc96a8e72008-11-05 01:50:32 +0000898 } else if (MR.isGlobalValueNonLazyPtr()) {
899 ResultPtr = getPointerToGVNonLazyPtr(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +0000900 BufferBegin+MR.getMachineCodeOffset(),
901 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +0000902 } else if (MR.isBasicBlock()) {
903 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
904 } else if (MR.isConstantPoolIndex()) {
905 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
906 } else {
907 assert(MR.isJumpTableIndex());
908 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
909 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000910
Evan Chengef5784e2008-10-29 23:54:46 +0000911 MR.setResultPointer(ResultPtr);
912 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000913
Andrew Lenharth6a974612005-07-28 12:44:13 +0000914 // if we are managing the GOT and the relocation wants an index,
915 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +0000916 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000917 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000918 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000919 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000920 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +0000921 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +0000922 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +0000923 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000924 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000925 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000926 }
927
Chris Lattner43b429b2006-05-02 18:27:26 +0000928 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +0000929 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000930 }
931
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000932 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000933 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000934 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000935 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000936 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +0000937 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
938 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000939 }
940 }
941
Nuno Lopescef75272008-10-21 11:42:16 +0000942 unsigned char *FnEnd = CurBufferPtr;
943
944 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
945 BufferBegin = CurBufferPtr = 0;
946 NumBytes += FnEnd-FnStart;
947
Evan Cheng55fc2802006-07-25 20:40:54 +0000948 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +0000949 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000950
951 // Add it to the JIT symbol table if the host wants it.
952 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
953 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +0000954
Bill Wendling832171c2006-12-07 20:04:42 +0000955 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
956 << "] Function: " << F.getFunction()->getName()
957 << ": " << (FnEnd-FnStart) << " bytes of text, "
958 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +0000959 Relocations.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +0000960
Evan Chengbc4707a2008-09-18 07:54:21 +0000961 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +0000962 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +0000963
Chris Lattnerc5633c22007-01-20 20:51:43 +0000964#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +0000965 {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000966 DOUT << "JIT: Disassembled code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +0000967 if (sys::hasDisassembler())
Evan Chengeb5d95a2008-11-06 17:46:04 +0000968 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenga7916f52008-11-05 23:44:08 +0000969 else {
970 DOUT << std::hex;
971 int i;
972 unsigned char* q = FnStart;
973 for (i=1; q!=FnEnd; q++, i++) {
974 if (i%8==1)
Evan Chengeb5d95a2008-11-06 17:46:04 +0000975 DOUT << "JIT: 0x" << (long)q << ": ";
Evan Chenga7916f52008-11-05 23:44:08 +0000976 DOUT<< std::setw(2) << std::setfill('0') << (unsigned short)*q << " ";
977 if (i%8==0)
Evan Cheng6863fb02008-11-06 01:18:29 +0000978 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +0000979 }
980 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +0000981 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +0000982 }
983 }
Chris Lattnerc5633c22007-01-20 20:51:43 +0000984#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000985 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000986 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000987 SavedBufferBegin = BufferBegin;
988 SavedBufferEnd = BufferEnd;
989 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000990
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000991 if (MemMgr->NeedsExactSize()) {
992 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000993 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000994
995 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
996 ActualSize);
997 BufferEnd = BufferBegin+ActualSize;
998 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +0000999 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1000 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001001 BufferBegin = SavedBufferBegin;
1002 BufferEnd = SavedBufferEnd;
1003 CurBufferPtr = SavedCurBufferPtr;
1004
1005 TheJIT->RegisterTable(FrameRegister);
1006 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001007
1008 if (MMI)
1009 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001010
Chris Lattner43b429b2006-05-02 18:27:26 +00001011 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001012}
1013
Nuno Lopescef75272008-10-21 11:42:16 +00001014void* JITEmitter::allocateSpace(intptr_t Size, unsigned Alignment) {
1015 if (BufferBegin)
1016 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1017
1018 // create a new memory block if there is no active one.
1019 // care must be taken so that BufferBegin is invalidated when a
1020 // block is trimmed
1021 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1022 BufferEnd = BufferBegin+Size;
1023 return CurBufferPtr;
1024}
1025
Chris Lattner166f2262004-11-22 22:00:25 +00001026void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001027 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001028 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001029
Chris Lattnerfa77d432006-02-09 04:22:52 +00001030 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001031 if (Constants.empty()) return;
1032
Evan Chengcd5731d2006-09-12 20:59:59 +00001033 MachineConstantPoolEntry CPE = Constants.back();
1034 unsigned Size = CPE.Offset;
1035 const Type *Ty = CPE.isMachineConstantPoolEntry()
Chris Lattner8a650092006-09-13 16:21:10 +00001036 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00001037 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001038
Evan Cheng97b8c402008-04-12 00:22:01 +00001039 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1040 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001041 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001042
1043 if (ConstantPoolBase == 0) return; // Buffer overflow.
1044
Evan Cheng97b8c402008-04-12 00:22:01 +00001045 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1046 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1047
Chris Lattner239862c2006-02-09 04:49:59 +00001048 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +00001049 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +00001050 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Evan Chengcd5731d2006-09-12 20:59:59 +00001051 if (Constants[i].isMachineConstantPoolEntry()) {
1052 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001053 cerr << "Initialize memory with machine specific constant pool entry"
1054 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001055 abort();
1056 }
1057 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng97b8c402008-04-12 00:22:01 +00001058 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Chris Lattner1cc08382003-01-13 01:00:12 +00001059 }
1060}
1061
Nate Begeman37efe672006-04-22 18:53:45 +00001062void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001063 if (TheJIT->getJITInfo().hasCustomJumpTables())
1064 return;
1065
Nate Begeman37efe672006-04-22 18:53:45 +00001066 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1067 if (JT.empty()) return;
1068
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001069 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001070 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001071 NumEntries += JT[i].MBBs.size();
1072
1073 unsigned EntrySize = MJTI->getEntrySize();
1074
Nate Begeman37efe672006-04-22 18:53:45 +00001075 // Just allocate space for all the jump tables now. We will fix up the actual
1076 // MBB entries in the tables after we emit the code for each block, since then
1077 // we will know the final locations of the MBBs in memory.
1078 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001079 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001080}
1081
Jim Laskeyb92767a2006-12-14 22:53:42 +00001082void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001083 if (TheJIT->getJITInfo().hasCustomJumpTables())
1084 return;
1085
Nate Begeman37efe672006-04-22 18:53:45 +00001086 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001087 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001088
Jim Laskeyb92767a2006-12-14 22:53:42 +00001089 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001090 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1091 // For each jump table, place the offset from the beginning of the table
1092 // to the target address.
1093 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001094
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001095 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1096 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1097 // Store the offset of the basic block for this jump table slot in the
1098 // memory we allocated for the jump table in 'initJumpTableInfo'
1099 intptr_t Base = (intptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001100 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1101 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1102 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1103 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001104 }
1105 } else {
1106 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1107
1108 // For each jump table, map each target in the jump table to the address of
1109 // an emitted MachineBasicBlock.
1110 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1111
1112 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1113 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1114 // Store the address of the basic block for this jump table slot in the
1115 // memory we allocated for the jump table in 'initJumpTableInfo'
1116 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1117 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1118 }
Nate Begeman37efe672006-04-22 18:53:45 +00001119 }
1120}
1121
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +00001122void JITEmitter::startFunctionStub(const GlobalValue* F, unsigned StubSize,
1123 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001124 SavedBufferBegin = BufferBegin;
1125 SavedBufferEnd = BufferEnd;
1126 SavedCurBufferPtr = CurBufferPtr;
1127
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +00001128 BufferBegin = CurBufferPtr = MemMgr->allocateStub(F, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001129 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001130}
1131
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +00001132void *JITEmitter::finishFunctionStub(const GlobalValue* F) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001133 NumBytes += getCurrentPCOffset();
Jim Grosbachcce6c292008-10-03 16:17:20 +00001134
1135 // Invalidate the icache if necessary.
1136 sys::Memory::InvalidateInstructionCache(BufferBegin, NumBytes);
1137
Chris Lattner43b429b2006-05-02 18:27:26 +00001138 std::swap(SavedBufferBegin, BufferBegin);
1139 BufferEnd = SavedBufferEnd;
1140 CurBufferPtr = SavedCurBufferPtr;
1141 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001142}
1143
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001144// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1145// in the constant pool that was last emitted with the 'emitConstantPool'
1146// method.
1147//
Chris Lattnerb4432f32006-05-03 17:10:41 +00001148intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001149 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001150 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +00001151 return (intptr_t)ConstantPoolBase +
1152 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001153}
1154
Nate Begeman37efe672006-04-22 18:53:45 +00001155// getJumpTableEntryAddress - Return the address of the JumpTable with index
1156// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1157//
Chris Lattnerb4432f32006-05-03 17:10:41 +00001158intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001159 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1160 assert(Index < JT.size() && "Invalid jump table index!");
1161
1162 unsigned Offset = 0;
1163 unsigned EntrySize = JumpTable->getEntrySize();
1164
1165 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001166 Offset += JT[i].MBBs.size();
1167
1168 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001169
Nate Begemanc34b2272006-04-25 17:46:32 +00001170 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001171}
1172
Chris Lattnere993cc22006-05-11 23:08:08 +00001173//===----------------------------------------------------------------------===//
1174// Public interface to this file
1175//===----------------------------------------------------------------------===//
1176
Chris Lattner9f2f1422007-12-06 01:08:09 +00001177MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1178 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001179}
1180
Misha Brukmand69c1e62003-07-28 19:09:06 +00001181// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001182// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001183// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1184// need to resolve function(s) that are being mis-codegenerated, so we need to
1185// resolve their addresses at runtime, and this is the way to do it.
1186extern "C" {
1187 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001188 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001189 return TheJIT->getPointerToFunction(F);
1190 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001191 }
1192}
Chris Lattnere993cc22006-05-11 23:08:08 +00001193
1194// getPointerToFunctionOrStub - If the specified function has been
1195// code-gen'd, return a pointer to the function. If not, compile it, or use
1196// a stub to implement lazy compilation if available.
1197//
1198void *JIT::getPointerToFunctionOrStub(Function *F) {
1199 // If we have already code generated the function, just return the address.
1200 if (void *Addr = getPointerToGlobalIfAvailable(F))
1201 return Addr;
1202
Chris Lattnere7484012007-02-24 02:57:03 +00001203 // Get a stub if the target supports it.
Evan Chenga044dfc2008-08-20 00:28:12 +00001204 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1205 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001206 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001207}
1208
1209/// freeMachineCodeForFunction - release machine code memory for given Function.
1210///
1211void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001212
Chris Lattnere993cc22006-05-11 23:08:08 +00001213 // Delete translation for this from the ExecutionEngine, so it will get
1214 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001215 void *OldPtr = updateGlobalMapping(F, 0);
1216
1217 if (OldPtr)
1218 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001219
1220 // Free the actual memory for the function body and related stuff.
Evan Chenga044dfc2008-08-20 00:28:12 +00001221 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1222 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001223}
1224