blob: d4f190bfc76538076f8742e2e3a82341356ebd8e [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This tool implements a just-in-time compiler for LLVM, allowing direct
11// execution of LLVM bitcode in an efficient manner.
12//
13//===----------------------------------------------------------------------===//
14
15#include "JIT.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19#include "llvm/GlobalVariable.h"
20#include "llvm/Instructions.h"
21#include "llvm/ModuleProvider.h"
22#include "llvm/CodeGen/MachineCodeEmitter.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/ExecutionEngine/GenericValue.h"
24#include "llvm/Support/MutexGuard.h"
25#include "llvm/System/DynamicLibrary.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetJITInfo.h"
Anton Korobeynikov52f44db2007-07-30 20:02:02 +000029
30#include "llvm/Config/config.h"
31
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032using namespace llvm;
33
34#ifdef __APPLE__
Anton Korobeynikov52f44db2007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#endif
Anton Korobeynikov52f44db2007-07-30 20:02:02 +000049
50#if HAVE___DSO_HANDLE
51extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052#endif
53
Dan Gohman089efff2008-05-13 00:00:25 +000054namespace {
55
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056static struct RegisterJIT {
57 RegisterJIT() { JIT::Register(); }
58} JITRegistrator;
59
Dan Gohman089efff2008-05-13 00:00:25 +000060}
61
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062namespace llvm {
63 void LinkInJIT() {
64 }
65}
66
Anton Korobeynikov6556e9e2008-03-22 08:53:09 +000067#if defined (__GNUC__)
68extern "C" void __register_frame(void*);
69#endif
70
Chris Lattner4db98aa2007-12-06 01:34:04 +000071/// createJIT - This is the factory method for creating a JIT for the current
72/// machine, it does not fall back to the interpreter. This takes ownership
73/// of the module provider.
74ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
75 std::string *ErrorStr,
76 JITMemoryManager *JMM) {
77 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM);
78 if (!EE) return 0;
79
Anton Korobeynikov6556e9e2008-03-22 08:53:09 +000080 // Register routine for informing unwinding runtime about new EH frames
81#if defined(__GNUC__)
82 EE->InstallExceptionTableRegister(__register_frame);
83#endif
84
Chris Lattner4db98aa2007-12-06 01:34:04 +000085 // Make sure we can resolve symbols in the program as well. The zero arg
86 // to the function tells DynamicLibrary to load the program, not a library.
87 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
88 return EE;
89}
90
91JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
92 JITMemoryManager *JMM)
Nate Begemanf7113d92008-05-21 16:34:48 +000093 : ExecutionEngine(MP), TM(tm), TJI(tji) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 setTargetData(TM.getTargetData());
95
Nate Begemanf7113d92008-05-21 16:34:48 +000096 jitstate = new JITState(MP);
97
Dan Gohmanf17a25c2007-07-18 16:29:46 +000098 // Initialize MCE
Chris Lattner4db98aa2007-12-06 01:34:04 +000099 MCE = createEmitter(*this, JMM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100
101 // Add target data
102 MutexGuard locked(lock);
Nate Begemanf7113d92008-05-21 16:34:48 +0000103 FunctionPassManager &PM = jitstate->getPM(locked);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104 PM.add(new TargetData(*TM.getTargetData()));
105
106 // Turn the machine code intermediate representation into bytes in memory that
107 // may be executed.
108 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
109 cerr << "Target does not support machine code emission!\n";
110 abort();
111 }
112
113 // Initialize passes.
114 PM.doInitialization();
115}
116
117JIT::~JIT() {
Nate Begemanf7113d92008-05-21 16:34:48 +0000118 delete jitstate;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119 delete MCE;
120 delete &TM;
121}
122
Nate Begemanf7113d92008-05-21 16:34:48 +0000123/// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
124/// removed the last ModuleProvider, we need re-initialize jitstate with a valid
125/// ModuleProvider.
126void JIT::addModuleProvider(ModuleProvider *MP) {
127 MutexGuard locked(lock);
128
129 if (Modules.empty()) {
130 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
131
132 jitstate = new JITState(MP);
133
134 FunctionPassManager &PM = jitstate->getPM(locked);
135 PM.add(new TargetData(*TM.getTargetData()));
136
137 // Turn the machine code intermediate representation into bytes in memory
138 // that may be executed.
139 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
140 cerr << "Target does not support machine code emission!\n";
141 abort();
142 }
143
144 // Initialize passes.
145 PM.doInitialization();
146 }
147
148 ExecutionEngine::addModuleProvider(MP);
149}
150
151/// removeModuleProvider - If we are removing the last ModuleProvider,
152/// invalidate the jitstate since the PassManager it contains references a
153/// released ModuleProvider.
154Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
155 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
156
157 MutexGuard locked(lock);
158 if (Modules.empty()) {
159 delete jitstate;
160 jitstate = 0;
161 }
162
163 return result;
164}
165
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166/// run - Start execution with the specified function and arguments.
167///
168GenericValue JIT::runFunction(Function *F,
169 const std::vector<GenericValue> &ArgValues) {
170 assert(F && "Function *F was null at entry to run()");
171
172 void *FPtr = getPointerToFunction(F);
173 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
174 const FunctionType *FTy = F->getFunctionType();
175 const Type *RetTy = FTy->getReturnType();
176
177 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
178 "Too many arguments passed into function!");
179 assert(FTy->getNumParams() == ArgValues.size() &&
180 "This doesn't support passing arguments through varargs (yet)!");
181
182 // Handle some common cases first. These cases correspond to common `main'
183 // prototypes.
Chris Lattnerbbf22702007-08-08 16:19:57 +0000184 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 switch (ArgValues.size()) {
186 case 3:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000187 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 isa<PointerType>(FTy->getParamType(1)) &&
189 isa<PointerType>(FTy->getParamType(2))) {
190 int (*PF)(int, char **, const char **) =
191 (int(*)(int, char **, const char **))(intptr_t)FPtr;
192
193 // Call the function.
194 GenericValue rv;
195 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
196 (char **)GVTOP(ArgValues[1]),
197 (const char **)GVTOP(ArgValues[2])));
198 return rv;
199 }
200 break;
201 case 2:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000202 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 isa<PointerType>(FTy->getParamType(1))) {
204 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
205
206 // Call the function.
207 GenericValue rv;
208 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
209 (char **)GVTOP(ArgValues[1])));
210 return rv;
211 }
212 break;
213 case 1:
214 if (FTy->getNumParams() == 1 &&
Chris Lattnerbbf22702007-08-08 16:19:57 +0000215 FTy->getParamType(0) == Type::Int32Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 GenericValue rv;
217 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
218 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
219 return rv;
220 }
221 break;
222 }
223 }
224
225 // Handle cases where no arguments are passed first.
226 if (ArgValues.empty()) {
227 GenericValue rv;
228 switch (RetTy->getTypeID()) {
229 default: assert(0 && "Unknown return type for function call!");
230 case Type::IntegerTyID: {
231 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
232 if (BitWidth == 1)
233 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
234 else if (BitWidth <= 8)
235 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
236 else if (BitWidth <= 16)
237 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
238 else if (BitWidth <= 32)
239 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
240 else if (BitWidth <= 64)
241 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
242 else
243 assert(0 && "Integer types > 64 bits not supported");
244 return rv;
245 }
246 case Type::VoidTyID:
247 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
248 return rv;
249 case Type::FloatTyID:
250 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
251 return rv;
252 case Type::DoubleTyID:
253 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
254 return rv;
Dale Johannesenc560da62007-09-17 18:44:13 +0000255 case Type::X86_FP80TyID:
256 case Type::FP128TyID:
257 case Type::PPC_FP128TyID:
258 assert(0 && "long double not supported yet");
259 return rv;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 case Type::PointerTyID:
261 return PTOGV(((void*(*)())(intptr_t)FPtr)());
262 }
263 }
264
265 // Okay, this is not one of our quick and easy cases. Because we don't have a
266 // full FFI, we have to codegen a nullary stub function that just calls the
267 // function we are interested in, passing in constants for all of the
268 // arguments. Make this function and return.
269
270 // First, create the function.
271 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000272 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
273 F->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274
275 // Insert a basic block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000276 BasicBlock *StubBB = BasicBlock::Create("", Stub);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277
278 // Convert all of the GenericValue arguments over to constants. Note that we
279 // currently don't support varargs.
280 SmallVector<Value*, 8> Args;
281 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
282 Constant *C = 0;
283 const Type *ArgTy = FTy->getParamType(i);
284 const GenericValue &AV = ArgValues[i];
285 switch (ArgTy->getTypeID()) {
286 default: assert(0 && "Unknown argument type for function call!");
Chris Lattner5e0610f2008-04-20 00:41:09 +0000287 case Type::IntegerTyID:
288 C = ConstantInt::get(AV.IntVal);
289 break;
290 case Type::FloatTyID:
291 C = ConstantFP::get(APFloat(AV.FloatVal));
292 break;
293 case Type::DoubleTyID:
294 C = ConstantFP::get(APFloat(AV.DoubleVal));
295 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000296 case Type::PPC_FP128TyID:
297 case Type::X86_FP80TyID:
Chris Lattner5e0610f2008-04-20 00:41:09 +0000298 case Type::FP128TyID:
299 C = ConstantFP::get(APFloat(AV.IntVal));
300 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301 case Type::PointerTyID:
302 void *ArgPtr = GVTOP(AV);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000303 if (sizeof(void*) == 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000305 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
308 break;
309 }
310 Args.push_back(C);
311 }
312
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000313 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
314 "", StubBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 TheCall->setTailCall();
316 if (TheCall->getType() != Type::VoidTy)
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000317 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 else
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000319 ReturnInst::Create(StubBB); // Just return void.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320
321 // Finally, return the value returned by our nullary stub function.
322 return runFunction(Stub, std::vector<GenericValue>());
323}
324
325/// runJITOnFunction - Run the FunctionPassManager full of
326/// just-in-time compilation passes on F, hopefully filling in
327/// GlobalAddress[F] with the address of F's machine code.
328///
329void JIT::runJITOnFunction(Function *F) {
330 static bool isAlreadyCodeGenerating = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331
332 MutexGuard locked(lock);
Chris Lattner700fb1d2007-08-13 20:08:16 +0000333 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
335 // JIT the function
336 isAlreadyCodeGenerating = true;
Nate Begemanf7113d92008-05-21 16:34:48 +0000337 jitstate->getPM(locked).run(*F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 isAlreadyCodeGenerating = false;
339
340 // If the function referred to a global variable that had not yet been
341 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
342 // all of these globals now.
Nate Begemanf7113d92008-05-21 16:34:48 +0000343 while (!jitstate->getPendingGlobals(locked).empty()) {
344 const GlobalVariable *GV = jitstate->getPendingGlobals(locked).back();
345 jitstate->getPendingGlobals(locked).pop_back();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 EmitGlobalVariable(GV);
347 }
348}
349
350/// getPointerToFunction - This method is used to get the address of the
351/// specified function, compiling it if neccesary.
352///
353void *JIT::getPointerToFunction(Function *F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354
355 if (void *Addr = getPointerToGlobalIfAvailable(F))
356 return Addr; // Check if function already code gen'd
357
358 // Make sure we read in the function if it exists in this Module.
359 if (F->hasNotBeenReadFromBitcode()) {
360 // Determine the module provider this function is provided by.
361 Module *M = F->getParent();
362 ModuleProvider *MP = 0;
363 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
364 if (Modules[i]->getModule() == M) {
365 MP = Modules[i];
366 break;
367 }
368 }
369 assert(MP && "Function isn't in a module we know about!");
370
371 std::string ErrorMsg;
372 if (MP->materializeFunction(F, &ErrorMsg)) {
373 cerr << "Error reading function '" << F->getName()
374 << "' from bitcode file: " << ErrorMsg << "\n";
375 abort();
376 }
377 }
Nicolas Geoffray8ae32352008-04-20 08:33:02 +0000378
379 if (void *Addr = getPointerToGlobalIfAvailable(F)) {
380 return Addr;
381 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382
Nicolas Geoffray8ae32352008-04-20 08:33:02 +0000383 MutexGuard locked(lock);
384
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385 if (F->isDeclaration()) {
386 void *Addr = getPointerToNamedFunction(F->getName());
387 addGlobalMapping(F, Addr);
388 return Addr;
389 }
390
391 runJITOnFunction(F);
392
393 void *Addr = getPointerToGlobalIfAvailable(F);
394 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
395 return Addr;
396}
397
398/// getOrEmitGlobalVariable - Return the address of the specified global
399/// variable, possibly emitting it to memory if needed. This is used by the
400/// Emitter.
401void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
402 MutexGuard locked(lock);
403
404 void *Ptr = getPointerToGlobalIfAvailable(GV);
405 if (Ptr) return Ptr;
406
407 // If the global is external, just remember the address.
408 if (GV->isDeclaration()) {
Anton Korobeynikov52f44db2007-07-30 20:02:02 +0000409#if HAVE___DSO_HANDLE
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410 if (GV->getName() == "__dso_handle")
411 return (void*)&__dso_handle;
412#endif
413 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
414 if (Ptr == 0) {
415 cerr << "Could not resolve external global address: "
416 << GV->getName() << "\n";
417 abort();
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000418 addGlobalMapping(GV, Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419 }
420 } else {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000421 // If the global hasn't been emitted to memory yet, allocate space and
422 // emit it into memory. It goes in the same array as the generated
423 // code, jump tables, etc.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 const Type *GlobalType = GV->getType()->getElementType();
Duncan Sandsf99fdc62007-11-01 20:53:16 +0000425 size_t S = getTargetData()->getABITypeSize(GlobalType);
Duncan Sands935686e2008-01-29 06:23:44 +0000426 size_t A = getTargetData()->getPreferredAlignment(GV);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000427 Ptr = MCE->allocateSpace(S, A);
428 addGlobalMapping(GV, Ptr);
429 EmitGlobalVariable(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 return Ptr;
432}
433
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434/// recompileAndRelinkFunction - This method is used to force a function
435/// which has already been compiled, to be compiled again, possibly
436/// after it has been modified. Then the entry to the old copy is overwritten
437/// with a branch to the new copy. If there was no old copy, this acts
438/// just like JIT::getPointerToFunction().
439///
440void *JIT::recompileAndRelinkFunction(Function *F) {
441 void *OldAddr = getPointerToGlobalIfAvailable(F);
442
443 // If it's not already compiled there is no reason to patch it up.
444 if (OldAddr == 0) { return getPointerToFunction(F); }
445
446 // Delete the old function mapping.
447 addGlobalMapping(F, 0);
448
449 // Recodegen the function
450 runJITOnFunction(F);
451
452 // Update state, forward the old function to the new function.
453 void *Addr = getPointerToGlobalIfAvailable(F);
454 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
455 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
456 return Addr;
457}
458