blob: 9a3bd3bda1ee49369d49b96a107b19d856406e36 [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,
Evan Chenga6394fc2008-08-08 08:11:34 +000076 JITMemoryManager *JMM,
77 bool Fast) {
78 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, Fast);
Chris Lattner4db98aa2007-12-06 01:34:04 +000079 if (!EE) return 0;
80
Chris Lattner4db98aa2007-12-06 01:34:04 +000081 // Make sure we can resolve symbols in the program as well. The zero arg
82 // to the function tells DynamicLibrary to load the program, not a library.
83 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
84 return EE;
85}
86
87JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
Evan Chenga6394fc2008-08-08 08:11:34 +000088 JITMemoryManager *JMM, bool Fast)
Nate Begemanf7113d92008-05-21 16:34:48 +000089 : ExecutionEngine(MP), TM(tm), TJI(tji) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090 setTargetData(TM.getTargetData());
91
Nate Begemanf7113d92008-05-21 16:34:48 +000092 jitstate = new JITState(MP);
93
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 // Initialize MCE
Chris Lattner4db98aa2007-12-06 01:34:04 +000095 MCE = createEmitter(*this, JMM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096
97 // Add target data
98 MutexGuard locked(lock);
Nate Begemanf7113d92008-05-21 16:34:48 +000099 FunctionPassManager &PM = jitstate->getPM(locked);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100 PM.add(new TargetData(*TM.getTargetData()));
101
102 // Turn the machine code intermediate representation into bytes in memory that
103 // may be executed.
Evan Chenga6394fc2008-08-08 08:11:34 +0000104 if (TM.addPassesToEmitMachineCode(PM, *MCE, Fast)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105 cerr << "Target does not support machine code emission!\n";
106 abort();
107 }
108
Nicolas Geoffraybed46f82008-08-18 14:53:56 +0000109 // Register routine for informing unwinding runtime about new EH frames
110#if defined(__GNUC__)
111 InstallExceptionTableRegister(__register_frame);
112#endif
113
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 // Initialize passes.
115 PM.doInitialization();
116}
117
118JIT::~JIT() {
Nate Begemanf7113d92008-05-21 16:34:48 +0000119 delete jitstate;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 delete MCE;
121 delete &TM;
122}
123
Nate Begemanf7113d92008-05-21 16:34:48 +0000124/// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
125/// removed the last ModuleProvider, we need re-initialize jitstate with a valid
126/// ModuleProvider.
127void JIT::addModuleProvider(ModuleProvider *MP) {
128 MutexGuard locked(lock);
129
130 if (Modules.empty()) {
131 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
132
133 jitstate = new JITState(MP);
134
135 FunctionPassManager &PM = jitstate->getPM(locked);
136 PM.add(new TargetData(*TM.getTargetData()));
137
138 // Turn the machine code intermediate representation into bytes in memory
139 // that may be executed.
140 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
141 cerr << "Target does not support machine code emission!\n";
142 abort();
143 }
144
145 // Initialize passes.
146 PM.doInitialization();
147 }
148
149 ExecutionEngine::addModuleProvider(MP);
150}
151
152/// removeModuleProvider - If we are removing the last ModuleProvider,
153/// invalidate the jitstate since the PassManager it contains references a
154/// released ModuleProvider.
155Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
156 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
157
158 MutexGuard locked(lock);
159 if (Modules.empty()) {
160 delete jitstate;
161 jitstate = 0;
162 }
163
164 return result;
165}
166
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167/// run - Start execution with the specified function and arguments.
168///
169GenericValue JIT::runFunction(Function *F,
170 const std::vector<GenericValue> &ArgValues) {
171 assert(F && "Function *F was null at entry to run()");
172
173 void *FPtr = getPointerToFunction(F);
174 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
175 const FunctionType *FTy = F->getFunctionType();
176 const Type *RetTy = FTy->getReturnType();
177
178 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
179 "Too many arguments passed into function!");
180 assert(FTy->getNumParams() == ArgValues.size() &&
181 "This doesn't support passing arguments through varargs (yet)!");
182
183 // Handle some common cases first. These cases correspond to common `main'
184 // prototypes.
Chris Lattnerbbf22702007-08-08 16:19:57 +0000185 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186 switch (ArgValues.size()) {
187 case 3:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000188 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 isa<PointerType>(FTy->getParamType(1)) &&
190 isa<PointerType>(FTy->getParamType(2))) {
191 int (*PF)(int, char **, const char **) =
192 (int(*)(int, char **, const char **))(intptr_t)FPtr;
193
194 // Call the function.
195 GenericValue rv;
196 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
197 (char **)GVTOP(ArgValues[1]),
198 (const char **)GVTOP(ArgValues[2])));
199 return rv;
200 }
201 break;
202 case 2:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000203 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 isa<PointerType>(FTy->getParamType(1))) {
205 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
206
207 // Call the function.
208 GenericValue rv;
209 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
210 (char **)GVTOP(ArgValues[1])));
211 return rv;
212 }
213 break;
214 case 1:
215 if (FTy->getNumParams() == 1 &&
Chris Lattnerbbf22702007-08-08 16:19:57 +0000216 FTy->getParamType(0) == Type::Int32Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 GenericValue rv;
218 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
219 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
220 return rv;
221 }
222 break;
223 }
224 }
225
226 // Handle cases where no arguments are passed first.
227 if (ArgValues.empty()) {
228 GenericValue rv;
229 switch (RetTy->getTypeID()) {
230 default: assert(0 && "Unknown return type for function call!");
231 case Type::IntegerTyID: {
232 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
233 if (BitWidth == 1)
234 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
235 else if (BitWidth <= 8)
236 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
237 else if (BitWidth <= 16)
238 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
239 else if (BitWidth <= 32)
240 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
241 else if (BitWidth <= 64)
242 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
243 else
244 assert(0 && "Integer types > 64 bits not supported");
245 return rv;
246 }
247 case Type::VoidTyID:
248 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
249 return rv;
250 case Type::FloatTyID:
251 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
252 return rv;
253 case Type::DoubleTyID:
254 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
255 return rv;
Dale Johannesenc560da62007-09-17 18:44:13 +0000256 case Type::X86_FP80TyID:
257 case Type::FP128TyID:
258 case Type::PPC_FP128TyID:
259 assert(0 && "long double not supported yet");
260 return rv;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261 case Type::PointerTyID:
262 return PTOGV(((void*(*)())(intptr_t)FPtr)());
263 }
264 }
265
266 // Okay, this is not one of our quick and easy cases. Because we don't have a
267 // full FFI, we have to codegen a nullary stub function that just calls the
268 // function we are interested in, passing in constants for all of the
269 // arguments. Make this function and return.
270
271 // First, create the function.
272 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000273 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
274 F->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275
276 // Insert a basic block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000277 BasicBlock *StubBB = BasicBlock::Create("", Stub);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278
279 // Convert all of the GenericValue arguments over to constants. Note that we
280 // currently don't support varargs.
281 SmallVector<Value*, 8> Args;
282 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
283 Constant *C = 0;
284 const Type *ArgTy = FTy->getParamType(i);
285 const GenericValue &AV = ArgValues[i];
286 switch (ArgTy->getTypeID()) {
287 default: assert(0 && "Unknown argument type for function call!");
Chris Lattner5e0610f2008-04-20 00:41:09 +0000288 case Type::IntegerTyID:
289 C = ConstantInt::get(AV.IntVal);
290 break;
291 case Type::FloatTyID:
292 C = ConstantFP::get(APFloat(AV.FloatVal));
293 break;
294 case Type::DoubleTyID:
295 C = ConstantFP::get(APFloat(AV.DoubleVal));
296 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000297 case Type::PPC_FP128TyID:
298 case Type::X86_FP80TyID:
Chris Lattner5e0610f2008-04-20 00:41:09 +0000299 case Type::FP128TyID:
300 C = ConstantFP::get(APFloat(AV.IntVal));
301 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 case Type::PointerTyID:
303 void *ArgPtr = GVTOP(AV);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000304 if (sizeof(void*) == 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000306 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
309 break;
310 }
311 Args.push_back(C);
312 }
313
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000314 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
315 "", StubBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 TheCall->setTailCall();
317 if (TheCall->getType() != Type::VoidTy)
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000318 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 else
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000320 ReturnInst::Create(StubBB); // Just return void.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321
322 // Finally, return the value returned by our nullary stub function.
323 return runFunction(Stub, std::vector<GenericValue>());
324}
325
326/// runJITOnFunction - Run the FunctionPassManager full of
327/// just-in-time compilation passes on F, hopefully filling in
328/// GlobalAddress[F] with the address of F's machine code.
329///
330void JIT::runJITOnFunction(Function *F) {
331 static bool isAlreadyCodeGenerating = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332
333 MutexGuard locked(lock);
Chris Lattner700fb1d2007-08-13 20:08:16 +0000334 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335
336 // JIT the function
337 isAlreadyCodeGenerating = true;
Nate Begemanf7113d92008-05-21 16:34:48 +0000338 jitstate->getPM(locked).run(*F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 isAlreadyCodeGenerating = false;
340
341 // If the function referred to a global variable that had not yet been
342 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
343 // all of these globals now.
Nate Begemanf7113d92008-05-21 16:34:48 +0000344 while (!jitstate->getPendingGlobals(locked).empty()) {
345 const GlobalVariable *GV = jitstate->getPendingGlobals(locked).back();
346 jitstate->getPendingGlobals(locked).pop_back();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 EmitGlobalVariable(GV);
348 }
349}
350
351/// getPointerToFunction - This method is used to get the address of the
352/// specified function, compiling it if neccesary.
353///
354void *JIT::getPointerToFunction(Function *F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355
356 if (void *Addr = getPointerToGlobalIfAvailable(F))
357 return Addr; // Check if function already code gen'd
358
359 // Make sure we read in the function if it exists in this Module.
360 if (F->hasNotBeenReadFromBitcode()) {
361 // Determine the module provider this function is provided by.
362 Module *M = F->getParent();
363 ModuleProvider *MP = 0;
364 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
365 if (Modules[i]->getModule() == M) {
366 MP = Modules[i];
367 break;
368 }
369 }
370 assert(MP && "Function isn't in a module we know about!");
371
372 std::string ErrorMsg;
373 if (MP->materializeFunction(F, &ErrorMsg)) {
374 cerr << "Error reading function '" << F->getName()
375 << "' from bitcode file: " << ErrorMsg << "\n";
376 abort();
377 }
378 }
Nicolas Geoffray8ae32352008-04-20 08:33:02 +0000379
380 if (void *Addr = getPointerToGlobalIfAvailable(F)) {
381 return Addr;
382 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383
Nicolas Geoffray8ae32352008-04-20 08:33:02 +0000384 MutexGuard locked(lock);
385
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 if (F->isDeclaration()) {
387 void *Addr = getPointerToNamedFunction(F->getName());
388 addGlobalMapping(F, Addr);
389 return Addr;
390 }
391
392 runJITOnFunction(F);
393
394 void *Addr = getPointerToGlobalIfAvailable(F);
395 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
396 return Addr;
397}
398
399/// getOrEmitGlobalVariable - Return the address of the specified global
400/// variable, possibly emitting it to memory if needed. This is used by the
401/// Emitter.
402void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
403 MutexGuard locked(lock);
404
405 void *Ptr = getPointerToGlobalIfAvailable(GV);
406 if (Ptr) return Ptr;
407
408 // If the global is external, just remember the address.
409 if (GV->isDeclaration()) {
Anton Korobeynikov52f44db2007-07-30 20:02:02 +0000410#if HAVE___DSO_HANDLE
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 if (GV->getName() == "__dso_handle")
412 return (void*)&__dso_handle;
413#endif
414 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
415 if (Ptr == 0) {
416 cerr << "Could not resolve external global address: "
417 << GV->getName() << "\n";
418 abort();
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000419 addGlobalMapping(GV, Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 }
421 } else {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000422 // If the global hasn't been emitted to memory yet, allocate space and
423 // emit it into memory. It goes in the same array as the generated
424 // code, jump tables, etc.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 const Type *GlobalType = GV->getType()->getElementType();
Duncan Sandsf99fdc62007-11-01 20:53:16 +0000426 size_t S = getTargetData()->getABITypeSize(GlobalType);
Duncan Sands935686e2008-01-29 06:23:44 +0000427 size_t A = getTargetData()->getPreferredAlignment(GV);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000428 Ptr = MCE->allocateSpace(S, A);
429 addGlobalMapping(GV, Ptr);
430 EmitGlobalVariable(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 return Ptr;
433}
434
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435/// recompileAndRelinkFunction - This method is used to force a function
436/// which has already been compiled, to be compiled again, possibly
437/// after it has been modified. Then the entry to the old copy is overwritten
438/// with a branch to the new copy. If there was no old copy, this acts
439/// just like JIT::getPointerToFunction().
440///
441void *JIT::recompileAndRelinkFunction(Function *F) {
442 void *OldAddr = getPointerToGlobalIfAvailable(F);
443
444 // If it's not already compiled there is no reason to patch it up.
445 if (OldAddr == 0) { return getPointerToFunction(F); }
446
447 // Delete the old function mapping.
448 addGlobalMapping(F, 0);
449
450 // Recodegen the function
451 runJITOnFunction(F);
452
453 // Update state, forward the old function to the new function.
454 void *Addr = getPointerToGlobalIfAvailable(F);
455 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
456 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
457 return Addr;
458}
459