blob: a611e82585cdf1ec93c9ae2f92186a09ac1587e7 [file] [log] [blame]
Chris Lattner4d326fa2003-12-20 01:46:27 +00001//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
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 Lattner4d326fa2003-12-20 01:46:27 +000010// This tool implements a just-in-time compiler for LLVM, allowing direct
Gabor Greifa99be512007-07-05 17:07:56 +000011// execution of LLVM bitcode in an efficient manner.
Chris Lattnerbd199fb2002-12-24 00:01:05 +000012//
13//===----------------------------------------------------------------------===//
14
Chris Lattner4d326fa2003-12-20 01:46:27 +000015#include "JIT.h"
Chris Lattnercc22e9f2004-08-16 00:14:18 +000016#include "llvm/Constants.h"
Chris Lattnerc07ed132003-12-20 03:36:47 +000017#include "llvm/DerivedTypes.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000018#include "llvm/Function.h"
Chris Lattnerc07ed132003-12-20 03:36:47 +000019#include "llvm/GlobalVariable.h"
Chris Lattnercc22e9f2004-08-16 00:14:18 +000020#include "llvm/Instructions.h"
Misha Brukman0f4f7d92003-10-16 21:19:34 +000021#include "llvm/ModuleProvider.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000022#include "llvm/CodeGen/MachineCodeEmitter.h"
Brian Gaeke97222942003-09-05 19:39:22 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000024#include "llvm/Support/MutexGuard.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000025#include "llvm/System/DynamicLibrary.h"
Owen Anderson07000c62006-05-12 06:33:49 +000026#include "llvm/Target/TargetData.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000027#include "llvm/Target/TargetMachine.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000028#include "llvm/Target/TargetJITInfo.h"
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +000029
30#include "llvm/Config/config.h"
31
Chris Lattnerc19aade2003-12-08 08:06:28 +000032using namespace llvm;
Misha Brukmanabb027c2003-05-27 21:40:39 +000033
Nate Begemanb76ea742006-07-22 16:59:38 +000034#ifdef __APPLE__
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +000035// Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
36// of atexit). It passes the address of linker generated symbol __dso_handle
37// to the function.
38// This configuration change happened at version 5330.
39# include <AvailabilityMacros.h>
40# if defined(MAC_OS_X_VERSION_10_4) && \
41 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
42 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
43 __APPLE_CC__ >= 5330))
44# ifndef HAVE___DSO_HANDLE
45# define HAVE___DSO_HANDLE 1
46# endif
47# endif
Evan Cheng5f42c552006-07-21 23:06:20 +000048#endif
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +000049
50#if HAVE___DSO_HANDLE
51extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
Nate Begemanb76ea742006-07-22 16:59:38 +000052#endif
Evan Cheng5f42c552006-07-21 23:06:20 +000053
Dan Gohman844731a2008-05-13 00:00:25 +000054namespace {
55
Chris Lattner2fe4bb02006-03-22 06:07:50 +000056static struct RegisterJIT {
57 RegisterJIT() { JIT::Register(); }
58} JITRegistrator;
59
Dan Gohman844731a2008-05-13 00:00:25 +000060}
61
Jeff Cohen2f519142006-03-24 02:53:49 +000062namespace llvm {
63 void LinkInJIT() {
64 }
65}
66
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +000067
Evan Cheng2d5424d2009-02-01 06:42:27 +000068#if defined(__GNUC__) && !defined(__ARM__EABI__)
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +000069
70// libgcc defines the __register_frame function to dynamically register new
71// dwarf frames for exception handling. This functionality is not portable
72// across compilers and is only provided by GCC. We use the __register_frame
73// function here so that code generated by the JIT cooperates with the unwinding
74// runtime of libgcc. When JITting with exception handling enable, LLVM
75// generates dwarf frames and registers it to libgcc with __register_frame.
76//
77// The __register_frame function works with Linux.
78//
79// Unfortunately, this functionality seems to be in libgcc after the unwinding
80// library of libgcc for darwin was written. The code for darwin overwrites the
81// value updated by __register_frame with a value fetched with "keymgr".
82// "keymgr" is an obsolete functionality, which should be rewritten some day.
83// In the meantime, since "keymgr" is on all libgccs shipped with apple-gcc, we
84// need a workaround in LLVM which uses the "keymgr" to dynamically modify the
85// values of an opaque key, used by libgcc to find dwarf tables.
86
Anton Korobeynikov299d9d72008-03-22 08:53:09 +000087extern "C" void __register_frame(void*);
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +000088
Evan Cheng2d5424d2009-02-01 06:42:27 +000089#if defined(__APPLE__)
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +000090
91namespace {
92
93// LibgccObject - This is the structure defined in libgcc. There is no #include
94// provided for this structure, so we also define it here. libgcc calls it
95// "struct object". The structure is undocumented in libgcc.
96struct LibgccObject {
97 void *unused1;
98 void *unused2;
99 void *unused3;
100
101 /// frame - Pointer to the exception table.
102 void *frame;
103
104 /// encoding - The encoding of the object?
105 union {
106 struct {
107 unsigned long sorted : 1;
108 unsigned long from_array : 1;
109 unsigned long mixed_encoding : 1;
110 unsigned long encoding : 8;
111 unsigned long count : 21;
112 } b;
113 size_t i;
114 } encoding;
115
116 /// fde_end - libgcc defines this field only if some macro is defined. We
117 /// include this field even if it may not there, to make libgcc happy.
118 char *fde_end;
119
120 /// next - At least we know it's a chained list!
121 struct LibgccObject *next;
122};
123
124// "kemgr" stuff. Apparently, all frame tables are stored there.
125extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
126extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
127#define KEYMGR_GCC3_DW2_OBJ_LIST 302 /* Dwarf2 object list */
128
129/// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
130/// probably contains all dwarf tables that are loaded.
131struct LibgccObjectInfo {
132
133 /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
134 ///
135 struct LibgccObject* seenObjects;
136
137 /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
138 ///
139 struct LibgccObject* unseenObjects;
140
141 unsigned unused[2];
142};
143
144// for DW_EH_PE_omit
145#include "llvm/Support/Dwarf.h"
146
147/// darwin_register_frame - Since __register_frame does not work with darwin's
148/// libgcc,we provide our own function, which "tricks" libgcc by modifying the
149/// "Dwarf2 object list" key.
150void DarwinRegisterFrame(void* FrameBegin) {
151 // Get the key.
152 struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
153 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
154
155 // Allocate a new LibgccObject to represent this frame. Deallocation of this
156 // object may be impossible: since darwin code in libgcc was written after
157 // the ability to dynamically register frames, things may crash if we
158 // deallocate it.
159 struct LibgccObject* ob = (struct LibgccObject*)
160 malloc(sizeof(struct LibgccObject));
161
162 // Do like libgcc for the values of the field.
163 ob->unused1 = (void *)-1;
164 ob->unused2 = 0;
165 ob->unused3 = 0;
166 ob->frame = FrameBegin;
167 ob->encoding.i = 0;
168 ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
169
170 // Put the info on both places, as libgcc uses the first or the the second
171 // field. Note that we rely on having two pointers here. If fde_end was a
172 // char, things would get complicated.
173 ob->fde_end = (char*)LOI->unseenObjects;
174 ob->next = LOI->unseenObjects;
175
176 // Update the key's unseenObjects list.
177 LOI->unseenObjects = ob;
178
179 // Finally update the "key". Apparently, libgcc requires it.
180 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
181 LOI);
182
183}
184
185}
186#endif // __APPLE__
187#endif // __GNUC__
Anton Korobeynikov299d9d72008-03-22 08:53:09 +0000188
Chris Lattner34c94332007-12-06 01:34:04 +0000189/// createJIT - This is the factory method for creating a JIT for the current
190/// machine, it does not fall back to the interpreter. This takes ownership
191/// of the module provider.
192ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
193 std::string *ErrorStr,
Evan Cheng502f20b2008-08-08 08:11:34 +0000194 JITMemoryManager *JMM,
195 bool Fast) {
196 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, Fast);
Chris Lattner34c94332007-12-06 01:34:04 +0000197 if (!EE) return 0;
198
Chris Lattner34c94332007-12-06 01:34:04 +0000199 // Make sure we can resolve symbols in the program as well. The zero arg
200 // to the function tells DynamicLibrary to load the program, not a library.
201 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
202 return EE;
203}
204
205JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
Evan Cheng502f20b2008-08-08 08:11:34 +0000206 JITMemoryManager *JMM, bool Fast)
Nate Begemanf049e072008-05-21 16:34:48 +0000207 : ExecutionEngine(MP), TM(tm), TJI(tji) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000208 setTargetData(TM.getTargetData());
Misha Brukmanabb027c2003-05-27 21:40:39 +0000209
Nate Begemanf049e072008-05-21 16:34:48 +0000210 jitstate = new JITState(MP);
211
Misha Brukmanabb027c2003-05-27 21:40:39 +0000212 // Initialize MCE
Chris Lattner34c94332007-12-06 01:34:04 +0000213 MCE = createEmitter(*this, JMM);
Misha Brukmanf976c852005-04-21 22:55:34 +0000214
Brian Gaeke50872d52004-04-14 17:45:52 +0000215 // Add target data
Reid Spenceree448632005-07-12 15:51:55 +0000216 MutexGuard locked(lock);
Nate Begemanf049e072008-05-21 16:34:48 +0000217 FunctionPassManager &PM = jitstate->getPM(locked);
Chris Lattnerb93b0342006-05-04 21:18:40 +0000218 PM.add(new TargetData(*TM.getTargetData()));
Brian Gaeke50872d52004-04-14 17:45:52 +0000219
Chris Lattner4d326fa2003-12-20 01:46:27 +0000220 // Turn the machine code intermediate representation into bytes in memory that
221 // may be executed.
Evan Cheng502f20b2008-08-08 08:11:34 +0000222 if (TM.addPassesToEmitMachineCode(PM, *MCE, Fast)) {
Bill Wendling832171c2006-12-07 20:04:42 +0000223 cerr << "Target does not support machine code emission!\n";
Chris Lattner4d326fa2003-12-20 01:46:27 +0000224 abort();
225 }
Chris Lattner1911fd42006-09-04 04:14:57 +0000226
Nicolas Geoffraya7ec87c2008-08-18 14:53:56 +0000227 // Register routine for informing unwinding runtime about new EH frames
Evan Cheng2d5424d2009-02-01 06:42:27 +0000228#if defined(__GNUC__) && !defined(__ARM_EABI__)
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +0000229#if defined(__APPLE__)
230 struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
231 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
232
233 // The key is created on demand, and libgcc creates it the first time an
234 // exception occurs. Since we need the key to register frames, we create
235 // it now.
236 if (!LOI) {
237 LOI = (LibgccObjectInfo*)malloc(sizeof(struct LibgccObjectInfo));
238 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
239 LOI);
240 }
241 InstallExceptionTableRegister(DarwinRegisterFrame);
242#else
Nicolas Geoffraya7ec87c2008-08-18 14:53:56 +0000243 InstallExceptionTableRegister(__register_frame);
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +0000244#endif // __APPLE__
245#endif // __GNUC__
Nicolas Geoffraya7ec87c2008-08-18 14:53:56 +0000246
Chris Lattner1911fd42006-09-04 04:14:57 +0000247 // Initialize passes.
248 PM.doInitialization();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000249}
250
Chris Lattner4d326fa2003-12-20 01:46:27 +0000251JIT::~JIT() {
Nate Begemanf049e072008-05-21 16:34:48 +0000252 delete jitstate;
Chris Lattner4d326fa2003-12-20 01:46:27 +0000253 delete MCE;
254 delete &TM;
255}
256
Nate Begemanf049e072008-05-21 16:34:48 +0000257/// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
258/// removed the last ModuleProvider, we need re-initialize jitstate with a valid
259/// ModuleProvider.
260void JIT::addModuleProvider(ModuleProvider *MP) {
261 MutexGuard locked(lock);
262
263 if (Modules.empty()) {
264 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
265
266 jitstate = new JITState(MP);
267
268 FunctionPassManager &PM = jitstate->getPM(locked);
269 PM.add(new TargetData(*TM.getTargetData()));
270
271 // Turn the machine code intermediate representation into bytes in memory
272 // that may be executed.
273 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
274 cerr << "Target does not support machine code emission!\n";
275 abort();
276 }
277
278 // Initialize passes.
279 PM.doInitialization();
280 }
281
282 ExecutionEngine::addModuleProvider(MP);
283}
284
285/// removeModuleProvider - If we are removing the last ModuleProvider,
286/// invalidate the jitstate since the PassManager it contains references a
287/// released ModuleProvider.
288Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
289 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
290
291 MutexGuard locked(lock);
Nate Begemand6b7a242009-02-18 08:31:02 +0000292
293 if (jitstate->getMP() == MP) {
Nate Begemanf049e072008-05-21 16:34:48 +0000294 delete jitstate;
295 jitstate = 0;
296 }
297
Nate Begemand6b7a242009-02-18 08:31:02 +0000298 if (!jitstate && !Modules.empty()) {
299 jitstate = new JITState(Modules[0]);
300
301 FunctionPassManager &PM = jitstate->getPM(locked);
302 PM.add(new TargetData(*TM.getTargetData()));
303
304 // Turn the machine code intermediate representation into bytes in memory
305 // that may be executed.
306 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
307 cerr << "Target does not support machine code emission!\n";
308 abort();
309 }
310
311 // Initialize passes.
312 PM.doInitialization();
313 }
Nate Begemanf049e072008-05-21 16:34:48 +0000314 return result;
315}
316
Nate Begeman60789e42009-01-23 19:27:28 +0000317/// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
318/// and deletes the ModuleProvider and owned Module. Avoids materializing
319/// the underlying module.
320void JIT::deleteModuleProvider(ModuleProvider *MP, std::string *E) {
321 ExecutionEngine::deleteModuleProvider(MP, E);
322
323 MutexGuard locked(lock);
Nate Begemand6b7a242009-02-18 08:31:02 +0000324
325 if (jitstate->getMP() == MP) {
Nate Begeman60789e42009-01-23 19:27:28 +0000326 delete jitstate;
327 jitstate = 0;
328 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000329
330 if (!jitstate && !Modules.empty()) {
331 jitstate = new JITState(Modules[0]);
332
333 FunctionPassManager &PM = jitstate->getPM(locked);
334 PM.add(new TargetData(*TM.getTargetData()));
335
336 // Turn the machine code intermediate representation into bytes in memory
337 // that may be executed.
338 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
339 cerr << "Target does not support machine code emission!\n";
340 abort();
341 }
342
343 // Initialize passes.
344 PM.doInitialization();
345 }
Nate Begeman60789e42009-01-23 19:27:28 +0000346}
347
Brian Gaeke70975ee2003-09-05 18:42:01 +0000348/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +0000349///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000350GenericValue JIT::runFunction(Function *F,
351 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +0000352 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +0000353
354 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +0000355 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000356 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +0000357 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000358
Dan Gohman07ab52b2009-02-19 02:55:18 +0000359 assert((FTy->getNumParams() == ArgValues.size() ||
360 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
361 "Wrong number of arguments passed into function!");
Chris Lattnere5eab142004-08-15 23:53:06 +0000362 assert(FTy->getNumParams() == ArgValues.size() &&
363 "This doesn't support passing arguments through varargs (yet)!");
364
Misha Brukmanec843022004-10-22 23:35:57 +0000365 // Handle some common cases first. These cases correspond to common `main'
Chris Lattnere5eab142004-08-15 23:53:06 +0000366 // prototypes.
Chris Lattner79e038a2007-08-08 16:19:57 +0000367 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000368 switch (ArgValues.size()) {
369 case 3:
Chris Lattner79e038a2007-08-08 16:19:57 +0000370 if (FTy->getParamType(0) == Type::Int32Ty &&
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000371 isa<PointerType>(FTy->getParamType(1)) &&
372 isa<PointerType>(FTy->getParamType(2))) {
373 int (*PF)(int, char **, const char **) =
Chris Lattner870286a2006-06-01 17:29:22 +0000374 (int(*)(int, char **, const char **))(intptr_t)FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000375
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000376 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +0000377 GenericValue rv;
Reid Spencer38f6a152007-03-06 03:11:31 +0000378 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
379 (char **)GVTOP(ArgValues[1]),
380 (const char **)GVTOP(ArgValues[2])));
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000381 return rv;
382 }
383 break;
Chris Lattner174f2262004-08-16 01:07:04 +0000384 case 2:
Chris Lattner79e038a2007-08-08 16:19:57 +0000385 if (FTy->getParamType(0) == Type::Int32Ty &&
Chris Lattner174f2262004-08-16 01:07:04 +0000386 isa<PointerType>(FTy->getParamType(1))) {
Chris Lattner870286a2006-06-01 17:29:22 +0000387 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000388
Chris Lattner174f2262004-08-16 01:07:04 +0000389 // Call the function.
390 GenericValue rv;
Reid Spencer38f6a152007-03-06 03:11:31 +0000391 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
392 (char **)GVTOP(ArgValues[1])));
Chris Lattner174f2262004-08-16 01:07:04 +0000393 return rv;
394 }
395 break;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000396 case 1:
397 if (FTy->getNumParams() == 1 &&
Chris Lattner79e038a2007-08-08 16:19:57 +0000398 FTy->getParamType(0) == Type::Int32Ty) {
Chris Lattnere5eab142004-08-15 23:53:06 +0000399 GenericValue rv;
Chris Lattner870286a2006-06-01 17:29:22 +0000400 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
Reid Spencer38f6a152007-03-06 03:11:31 +0000401 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000402 return rv;
403 }
404 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000405 }
406 }
407
408 // Handle cases where no arguments are passed first.
409 if (ArgValues.empty()) {
410 GenericValue rv;
411 switch (RetTy->getTypeID()) {
412 default: assert(0 && "Unknown return type for function call!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000413 case Type::IntegerTyID: {
414 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
415 if (BitWidth == 1)
Reid Spencer38f6a152007-03-06 03:11:31 +0000416 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000417 else if (BitWidth <= 8)
Reid Spencer38f6a152007-03-06 03:11:31 +0000418 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000419 else if (BitWidth <= 16)
Reid Spencer38f6a152007-03-06 03:11:31 +0000420 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000421 else if (BitWidth <= 32)
Reid Spencer38f6a152007-03-06 03:11:31 +0000422 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000423 else if (BitWidth <= 64)
Reid Spencer38f6a152007-03-06 03:11:31 +0000424 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000425 else
426 assert(0 && "Integer types > 64 bits not supported");
Chris Lattnerd297aea2004-08-15 23:34:48 +0000427 return rv;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000428 }
Chris Lattnere5eab142004-08-15 23:53:06 +0000429 case Type::VoidTyID:
Reid Spencer38f6a152007-03-06 03:11:31 +0000430 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
Chris Lattnere5eab142004-08-15 23:53:06 +0000431 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000432 case Type::FloatTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000433 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000434 return rv;
435 case Type::DoubleTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000436 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000437 return rv;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000438 case Type::X86_FP80TyID:
439 case Type::FP128TyID:
440 case Type::PPC_FP128TyID:
441 assert(0 && "long double not supported yet");
442 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000443 case Type::PointerTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000444 return PTOGV(((void*(*)())(intptr_t)FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000445 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000446 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000447
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000448 // Okay, this is not one of our quick and easy cases. Because we don't have a
449 // full FFI, we have to codegen a nullary stub function that just calls the
450 // function we are interested in, passing in constants for all of the
451 // arguments. Make this function and return.
452
453 // First, create the function.
454 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
Gabor Greif051a9502008-04-06 20:25:17 +0000455 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
456 F->getParent());
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000457
458 // Insert a basic block.
Gabor Greif051a9502008-04-06 20:25:17 +0000459 BasicBlock *StubBB = BasicBlock::Create("", Stub);
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000460
461 // Convert all of the GenericValue arguments over to constants. Note that we
462 // currently don't support varargs.
Chris Lattner990b8492007-02-13 06:01:22 +0000463 SmallVector<Value*, 8> Args;
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000464 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
465 Constant *C = 0;
466 const Type *ArgTy = FTy->getParamType(i);
467 const GenericValue &AV = ArgValues[i];
468 switch (ArgTy->getTypeID()) {
469 default: assert(0 && "Unknown argument type for function call!");
Chris Lattner02a260a2008-04-20 00:41:09 +0000470 case Type::IntegerTyID:
471 C = ConstantInt::get(AV.IntVal);
472 break;
473 case Type::FloatTyID:
474 C = ConstantFP::get(APFloat(AV.FloatVal));
475 break;
476 case Type::DoubleTyID:
477 C = ConstantFP::get(APFloat(AV.DoubleVal));
478 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000479 case Type::PPC_FP128TyID:
480 case Type::X86_FP80TyID:
Chris Lattner02a260a2008-04-20 00:41:09 +0000481 case Type::FP128TyID:
482 C = ConstantFP::get(APFloat(AV.IntVal));
483 break;
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000484 case Type::PointerTyID:
485 void *ArgPtr = GVTOP(AV);
Chris Lattner02a260a2008-04-20 00:41:09 +0000486 if (sizeof(void*) == 4)
Reid Spencere49661b2006-12-31 05:51:36 +0000487 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
Chris Lattner02a260a2008-04-20 00:41:09 +0000488 else
Reid Spencere49661b2006-12-31 05:51:36 +0000489 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
Reid Spencer15f46d62006-12-12 01:17:41 +0000490 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000491 break;
492 }
493 Args.push_back(C);
494 }
495
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000496 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
497 "", StubBB);
Chris Lattnercdfc51f2008-11-23 08:00:11 +0000498 TheCall->setCallingConv(F->getCallingConv());
Chris Lattnera471e042005-05-06 06:48:54 +0000499 TheCall->setTailCall();
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000500 if (TheCall->getType() != Type::VoidTy)
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000501 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000502 else
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000503 ReturnInst::Create(StubBB); // Just return void.
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000504
505 // Finally, return the value returned by our nullary stub function.
506 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000507}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000508
509/// runJITOnFunction - Run the FunctionPassManager full of
510/// just-in-time compilation passes on F, hopefully filling in
511/// GlobalAddress[F] with the address of F's machine code.
512///
513void JIT::runJITOnFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000514 MutexGuard locked(lock);
Dan Gohman21afcda2009-02-06 21:25:08 +0000515 runJITOnFunctionUnlocked(F, locked);
516}
517
518void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
519 static bool isAlreadyCodeGenerating = false;
Chris Lattner17f218e2007-08-13 20:08:16 +0000520 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Chris Lattner4d326fa2003-12-20 01:46:27 +0000521
522 // JIT the function
523 isAlreadyCodeGenerating = true;
Nate Begemanf049e072008-05-21 16:34:48 +0000524 jitstate->getPM(locked).run(*F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000525 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000526
Nate Begemand6b7a242009-02-18 08:31:02 +0000527 // If the function referred to another function that had not yet been
528 // read from bitcode, but we are jitting non-lazily, emit it now.
529 while (!jitstate->getPendingFunctions(locked).empty()) {
530 Function *PF = jitstate->getPendingFunctions(locked).back();
531 jitstate->getPendingFunctions(locked).pop_back();
532
533 // JIT the function
534 isAlreadyCodeGenerating = true;
535 jitstate->getPM(locked).run(*PF);
536 isAlreadyCodeGenerating = false;
537
538 // Now that the function has been jitted, ask the JITEmitter to rewrite
539 // the stub with real address of the function.
540 updateFunctionStub(PF);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000541 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000542
543 // If the JIT is configured to emit info so that dlsym can be used to
544 // rewrite stubs to external globals, do so now.
545 if (areDlsymStubsEnabled() && isLazyCompilationDisabled())
546 updateDlsymStubTable();
Chris Lattner4d326fa2003-12-20 01:46:27 +0000547}
548
549/// getPointerToFunction - This method is used to get the address of the
550/// specified function, compiling it if neccesary.
551///
552void *JIT::getPointerToFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000553
Chris Lattnerc07ed132003-12-20 03:36:47 +0000554 if (void *Addr = getPointerToGlobalIfAvailable(F))
555 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000556
Dan Gohmana3ac0c12009-02-19 02:40:15 +0000557 MutexGuard locked(lock);
558
Chris Lattnerfe854032006-08-16 01:24:12 +0000559 // Make sure we read in the function if it exists in this Module.
Gabor Greifa99be512007-07-05 17:07:56 +0000560 if (F->hasNotBeenReadFromBitcode()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000561 // Determine the module provider this function is provided by.
562 Module *M = F->getParent();
563 ModuleProvider *MP = 0;
564 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
565 if (Modules[i]->getModule() == M) {
566 MP = Modules[i];
567 break;
568 }
569 }
570 assert(MP && "Function isn't in a module we know about!");
571
Chris Lattner5c72a3a2006-07-07 17:18:09 +0000572 std::string ErrorMsg;
573 if (MP->materializeFunction(F, &ErrorMsg)) {
Bill Wendling832171c2006-12-07 20:04:42 +0000574 cerr << "Error reading function '" << F->getName()
Gabor Greifa99be512007-07-05 17:07:56 +0000575 << "' from bitcode file: " << ErrorMsg << "\n";
Chris Lattner0050ef82004-11-15 23:18:09 +0000576 abort();
577 }
Mon P Wang1c341c82008-10-10 01:47:42 +0000578
Dan Gohman69f93782009-01-05 05:32:42 +0000579 // Now retry to get the address.
580 if (void *Addr = getPointerToGlobalIfAvailable(F))
581 return Addr;
Nicolas Geoffrayfd7d9912008-04-20 08:33:02 +0000582 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000583
Reid Spencer5cbf9852007-01-30 20:08:39 +0000584 if (F->isDeclaration()) {
Dan Gohman69f93782009-01-05 05:32:42 +0000585 bool AbortOnFailure = F->getLinkage() != GlobalValue::ExternalWeakLinkage;
586 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000587 addGlobalMapping(F, Addr);
588 return Addr;
589 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000590
Dan Gohman21afcda2009-02-06 21:25:08 +0000591 runJITOnFunctionUnlocked(F, locked);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000592
593 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000594 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
595 return Addr;
596}
597
Chris Lattnerc07ed132003-12-20 03:36:47 +0000598/// getOrEmitGlobalVariable - Return the address of the specified global
599/// variable, possibly emitting it to memory if needed. This is used by the
600/// Emitter.
601void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
Reid Spenceree448632005-07-12 15:51:55 +0000602 MutexGuard locked(lock);
603
Chris Lattnerc07ed132003-12-20 03:36:47 +0000604 void *Ptr = getPointerToGlobalIfAvailable(GV);
605 if (Ptr) return Ptr;
606
607 // If the global is external, just remember the address.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000608 if (GV->isDeclaration()) {
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +0000609#if HAVE___DSO_HANDLE
Evan Cheng5f42c552006-07-21 23:06:20 +0000610 if (GV->getName() == "__dso_handle")
611 return (void*)&__dso_handle;
Evan Chengb82ab942006-07-22 00:42:03 +0000612#endif
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000613 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
Chris Lattnerc07ed132003-12-20 03:36:47 +0000614 if (Ptr == 0) {
Bill Wendling832171c2006-12-07 20:04:42 +0000615 cerr << "Could not resolve external global address: "
616 << GV->getName() << "\n";
Chris Lattnerc07ed132003-12-20 03:36:47 +0000617 abort();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000618 addGlobalMapping(GV, Ptr);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000619 }
620 } else {
Evan Cheng4d544a22009-01-16 19:14:49 +0000621 // GlobalVariable's which are not "constant" will cause trouble in a server
622 // situation. It's returned in the same block of memory as code which may
623 // not be writable.
624 if (isGVCompilationDisabled() && !GV->isConstant()) {
Evan Cheng77f86ad2008-12-09 07:31:49 +0000625 cerr << "Compilation of non-internal GlobalValue is disabled!\n";
Evan Cheng446531e2008-09-24 16:25:55 +0000626 abort();
627 }
Dale Johannesendd947ea2008-08-07 01:30:15 +0000628 // If the global hasn't been emitted to memory yet, allocate space and
629 // emit it into memory. It goes in the same array as the generated
630 // code, jump tables, etc.
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000631 const Type *GlobalType = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000632 size_t S = getTargetData()->getTypePaddedSize(GlobalType);
Duncan Sandsd1025932008-01-29 06:23:44 +0000633 size_t A = getTargetData()->getPreferredAlignment(GV);
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000634 if (GV->isThreadLocal()) {
635 MutexGuard locked(lock);
636 Ptr = TJI.allocateThreadLocalMemory(S);
Evan Chengb0b53492008-11-04 09:30:48 +0000637 } else if (TJI.allocateSeparateGVMemory()) {
638 if (A <= 8) {
639 Ptr = malloc(S);
640 } else {
641 // Allocate S+A bytes of memory, then use an aligned pointer within that
642 // space.
643 Ptr = malloc(S+A);
644 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
645 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
646 }
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000647 } else {
648 Ptr = MCE->allocateSpace(S, A);
649 }
Dale Johannesendd947ea2008-08-07 01:30:15 +0000650 addGlobalMapping(GV, Ptr);
651 EmitGlobalVariable(GV);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000652 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000653 return Ptr;
654}
655
Chris Lattner4d326fa2003-12-20 01:46:27 +0000656/// recompileAndRelinkFunction - This method is used to force a function
657/// which has already been compiled, to be compiled again, possibly
658/// after it has been modified. Then the entry to the old copy is overwritten
659/// with a branch to the new copy. If there was no old copy, this acts
660/// just like JIT::getPointerToFunction().
661///
662void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000663 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000664
Chris Lattnerc07ed132003-12-20 03:36:47 +0000665 // If it's not already compiled there is no reason to patch it up.
666 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000667
Chris Lattnerc07ed132003-12-20 03:36:47 +0000668 // Delete the old function mapping.
669 addGlobalMapping(F, 0);
670
Chris Lattnerc07ed132003-12-20 03:36:47 +0000671 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000672 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000673
674 // Update state, forward the old function to the new function.
675 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000676 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
677 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
678 return Addr;
679}
Misha Brukman895eddf2004-11-07 23:58:46 +0000680
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000681/// getMemoryForGV - This method abstracts memory allocation of global
682/// variable so that the JIT can allocate thread local variables depending
683/// on the target.
684///
685char* JIT::getMemoryForGV(const GlobalVariable* GV) {
686 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000687 size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000688 if (GV->isThreadLocal()) {
689 MutexGuard locked(lock);
690 return TJI.allocateThreadLocalMemory(GVSize);
691 } else {
692 return new char[GVSize];
693 }
694}
Nate Begemand6b7a242009-02-18 08:31:02 +0000695
696void JIT::addPendingFunction(Function *F) {
697 MutexGuard locked(lock);
698 jitstate->getPendingFunctions(locked).push_back(F);
699}