blob: 5abeb5662ab5d319196f503eda4f43f1a900f567 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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
11// execution of LLVM bytecode 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"
23#include "llvm/CodeGen/MachineFunction.h"
Brian Gaeke97222942003-09-05 19:39:22 +000024#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000025#include "llvm/Support/MutexGuard.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000026#include "llvm/System/DynamicLibrary.h"
Owen Anderson07000c62006-05-12 06:33:49 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000028#include "llvm/Target/TargetMachine.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000029#include "llvm/Target/TargetJITInfo.h"
Reid Spencer954da372004-07-04 12:19:56 +000030#include <iostream>
Chris Lattnerc19aade2003-12-08 08:06:28 +000031using namespace llvm;
Misha Brukmanabb027c2003-05-27 21:40:39 +000032
Evan Cheng5f42c552006-07-21 23:06:20 +000033#ifdef __APPLE__
34// __dso_handle is resolved by Mac OS X dynamic linker.
35extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
36#endif
37
Chris Lattner2fe4bb02006-03-22 06:07:50 +000038static struct RegisterJIT {
39 RegisterJIT() { JIT::Register(); }
40} JITRegistrator;
41
Jeff Cohen2f519142006-03-24 02:53:49 +000042namespace llvm {
43 void LinkInJIT() {
44 }
45}
46
Chris Lattner4d326fa2003-12-20 01:46:27 +000047JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
Reid Spenceree448632005-07-12 15:51:55 +000048 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +000049 setTargetData(TM.getTargetData());
Misha Brukmanabb027c2003-05-27 21:40:39 +000050
51 // Initialize MCE
Misha Brukman906f5fa2003-06-02 03:23:16 +000052 MCE = createEmitter(*this);
Misha Brukmanf976c852005-04-21 22:55:34 +000053
Brian Gaeke50872d52004-04-14 17:45:52 +000054 // Add target data
Reid Spenceree448632005-07-12 15:51:55 +000055 MutexGuard locked(lock);
56 FunctionPassManager& PM = state.getPM(locked);
Chris Lattnerb93b0342006-05-04 21:18:40 +000057 PM.add(new TargetData(*TM.getTargetData()));
Brian Gaeke50872d52004-04-14 17:45:52 +000058
Chris Lattner4d326fa2003-12-20 01:46:27 +000059 // Compile LLVM Code down to machine code in the intermediate representation
60 TJI.addPassesToJITCompile(PM);
61
62 // Turn the machine code intermediate representation into bytes in memory that
63 // may be executed.
64 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
Chris Lattnercc22e9f2004-08-16 00:14:18 +000065 std::cerr << "Target '" << TM.getName()
Chris Lattner4d326fa2003-12-20 01:46:27 +000066 << "' doesn't support machine code emission!\n";
67 abort();
68 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +000069}
70
Chris Lattner4d326fa2003-12-20 01:46:27 +000071JIT::~JIT() {
72 delete MCE;
73 delete &TM;
74}
75
Brian Gaeke70975ee2003-09-05 18:42:01 +000076/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +000077///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +000078GenericValue JIT::runFunction(Function *F,
79 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +000080 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +000081
82 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +000083 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +000084 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +000085 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +000086
Chris Lattnere5eab142004-08-15 23:53:06 +000087 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
88 "Too many arguments passed into function!");
89 assert(FTy->getNumParams() == ArgValues.size() &&
90 "This doesn't support passing arguments through varargs (yet)!");
91
Misha Brukmanec843022004-10-22 23:35:57 +000092 // Handle some common cases first. These cases correspond to common `main'
Chris Lattnere5eab142004-08-15 23:53:06 +000093 // prototypes.
Chris Lattnerd297aea2004-08-15 23:34:48 +000094 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +000095 switch (ArgValues.size()) {
96 case 3:
Misha Brukmanf976c852005-04-21 22:55:34 +000097 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +000098 FTy->getParamType(0) == Type::UIntTy) &&
99 isa<PointerType>(FTy->getParamType(1)) &&
100 isa<PointerType>(FTy->getParamType(2))) {
101 int (*PF)(int, char **, const char **) =
Chris Lattner870286a2006-06-01 17:29:22 +0000102 (int(*)(int, char **, const char **))(intptr_t)FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000103
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000104 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +0000105 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000106 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
107 (const char **)GVTOP(ArgValues[2]));
108 return rv;
109 }
110 break;
Chris Lattner174f2262004-08-16 01:07:04 +0000111 case 2:
Misha Brukmanf976c852005-04-21 22:55:34 +0000112 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattner174f2262004-08-16 01:07:04 +0000113 FTy->getParamType(0) == Type::UIntTy) &&
114 isa<PointerType>(FTy->getParamType(1))) {
Chris Lattner870286a2006-06-01 17:29:22 +0000115 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000116
Chris Lattner174f2262004-08-16 01:07:04 +0000117 // Call the function.
118 GenericValue rv;
119 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
120 return rv;
121 }
122 break;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000123 case 1:
124 if (FTy->getNumParams() == 1 &&
Misha Brukmanf976c852005-04-21 22:55:34 +0000125 (FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000126 FTy->getParamType(0) == Type::UIntTy)) {
Chris Lattnere5eab142004-08-15 23:53:06 +0000127 GenericValue rv;
Chris Lattner870286a2006-06-01 17:29:22 +0000128 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000129 rv.IntVal = PF(ArgValues[0].IntVal);
130 return rv;
131 }
132 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000133 }
134 }
135
136 // Handle cases where no arguments are passed first.
137 if (ArgValues.empty()) {
138 GenericValue rv;
139 switch (RetTy->getTypeID()) {
140 default: assert(0 && "Unknown return type for function call!");
141 case Type::BoolTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000142 rv.BoolVal = ((bool(*)())(intptr_t)FPtr)();
Chris Lattnerd297aea2004-08-15 23:34:48 +0000143 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000144 case Type::SByteTyID:
145 case Type::UByteTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000146 rv.SByteVal = ((char(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000147 return rv;
148 case Type::ShortTyID:
149 case Type::UShortTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000150 rv.ShortVal = ((short(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000151 return rv;
152 case Type::VoidTyID:
153 case Type::IntTyID:
154 case Type::UIntTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000155 rv.IntVal = ((int(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000156 return rv;
157 case Type::LongTyID:
158 case Type::ULongTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000159 rv.LongVal = ((int64_t(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000160 return rv;
161 case Type::FloatTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000162 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000163 return rv;
164 case Type::DoubleTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000165 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000166 return rv;
167 case Type::PointerTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000168 return PTOGV(((void*(*)())(intptr_t)FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000169 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000170 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000171
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000172 // Okay, this is not one of our quick and easy cases. Because we don't have a
173 // full FFI, we have to codegen a nullary stub function that just calls the
174 // function we are interested in, passing in constants for all of the
175 // arguments. Make this function and return.
176
177 // First, create the function.
178 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
179 Function *Stub = new Function(STy, Function::InternalLinkage, "",
180 F->getParent());
181
182 // Insert a basic block.
183 BasicBlock *StubBB = new BasicBlock("", Stub);
184
185 // Convert all of the GenericValue arguments over to constants. Note that we
186 // currently don't support varargs.
187 std::vector<Value*> Args;
188 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
189 Constant *C = 0;
190 const Type *ArgTy = FTy->getParamType(i);
191 const GenericValue &AV = ArgValues[i];
192 switch (ArgTy->getTypeID()) {
193 default: assert(0 && "Unknown argument type for function call!");
194 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
195 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
196 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
197 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
198 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
199 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
200 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
201 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
202 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
203 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
204 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
205 case Type::PointerTyID:
206 void *ArgPtr = GVTOP(AV);
207 if (sizeof(void*) == 4) {
208 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
209 } else {
210 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
211 }
212 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
213 break;
214 }
215 Args.push_back(C);
216 }
217
Chris Lattnera471e042005-05-06 06:48:54 +0000218 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
219 TheCall->setTailCall();
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000220 if (TheCall->getType() != Type::VoidTy)
221 new ReturnInst(TheCall, StubBB); // Return result of the call.
222 else
223 new ReturnInst(StubBB); // Just return void.
224
225 // Finally, return the value returned by our nullary stub function.
226 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000227}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000228
229/// runJITOnFunction - Run the FunctionPassManager full of
230/// just-in-time compilation passes on F, hopefully filling in
231/// GlobalAddress[F] with the address of F's machine code.
232///
233void JIT::runJITOnFunction(Function *F) {
234 static bool isAlreadyCodeGenerating = false;
235 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Jeff Cohen00b168892005-07-27 06:12:32 +0000236
Reid Spenceree448632005-07-12 15:51:55 +0000237 MutexGuard locked(lock);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000238
239 // JIT the function
240 isAlreadyCodeGenerating = true;
Reid Spenceree448632005-07-12 15:51:55 +0000241 state.getPM(locked).run(*F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000242 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000243
244 // If the function referred to a global variable that had not yet been
245 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
246 // all of these globals now.
Reid Spenceree448632005-07-12 15:51:55 +0000247 while (!state.getPendingGlobals(locked).empty()) {
248 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
249 state.getPendingGlobals(locked).pop_back();
Chris Lattnerc07ed132003-12-20 03:36:47 +0000250 EmitGlobalVariable(GV);
251 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000252}
253
254/// getPointerToFunction - This method is used to get the address of the
255/// specified function, compiling it if neccesary.
256///
257void *JIT::getPointerToFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000258 MutexGuard locked(lock);
259
Chris Lattnerc07ed132003-12-20 03:36:47 +0000260 if (void *Addr = getPointerToGlobalIfAvailable(F))
261 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000262
263 // Make sure we read in the function if it exists in this Module
Chris Lattner5c72a3a2006-07-07 17:18:09 +0000264 if (F->hasNotBeenReadFromBytecode()) {
265 std::string ErrorMsg;
266 if (MP->materializeFunction(F, &ErrorMsg)) {
Chris Lattner0050ef82004-11-15 23:18:09 +0000267 std::cerr << "Error reading function '" << F->getName()
Chris Lattner5c72a3a2006-07-07 17:18:09 +0000268 << "' from bytecode file: " << ErrorMsg << "\n";
Chris Lattner0050ef82004-11-15 23:18:09 +0000269 abort();
270 }
Chris Lattner5c72a3a2006-07-07 17:18:09 +0000271 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000272
Chris Lattnerc07ed132003-12-20 03:36:47 +0000273 if (F->isExternal()) {
274 void *Addr = getPointerToNamedFunction(F->getName());
275 addGlobalMapping(F, Addr);
276 return Addr;
277 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000278
279 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000280
281 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000282 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
283 return Addr;
284}
285
Chris Lattnerc07ed132003-12-20 03:36:47 +0000286/// getOrEmitGlobalVariable - Return the address of the specified global
287/// variable, possibly emitting it to memory if needed. This is used by the
288/// Emitter.
289void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
Reid Spenceree448632005-07-12 15:51:55 +0000290 MutexGuard locked(lock);
291
Chris Lattnerc07ed132003-12-20 03:36:47 +0000292 void *Ptr = getPointerToGlobalIfAvailable(GV);
293 if (Ptr) return Ptr;
294
295 // If the global is external, just remember the address.
296 if (GV->isExternal()) {
Evan Chengb82ab942006-07-22 00:42:03 +0000297#ifdef __APPLE__
Evan Cheng5f42c552006-07-21 23:06:20 +0000298 // __dso_handle is resolved by the Mac OS X dynamic linker.
299 if (GV->getName() == "__dso_handle")
300 return (void*)&__dso_handle;
Evan Chengb82ab942006-07-22 00:42:03 +0000301#endif
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000302 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
Chris Lattnerc07ed132003-12-20 03:36:47 +0000303 if (Ptr == 0) {
304 std::cerr << "Could not resolve external global address: "
305 << GV->getName() << "\n";
306 abort();
307 }
308 } else {
309 // If the global hasn't been emitted to memory yet, allocate space. We will
310 // actually initialize the global after current function has finished
311 // compilation.
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000312 const Type *GlobalType = GV->getType()->getElementType();
Owen Andersona69571c2006-05-03 01:29:57 +0000313 size_t S = getTargetData()->getTypeSize(GlobalType);
314 size_t A = getTargetData()->getTypeAlignment(GlobalType);
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000315 if (A <= 8) {
316 Ptr = malloc(S);
317 } else {
318 // Allocate S+A bytes of memory, then use an aligned pointer within that
319 // space.
320 Ptr = malloc(S+A);
321 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
Chris Lattner21c39a62006-07-12 00:31:47 +0000322 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000323 }
Reid Spenceree448632005-07-12 15:51:55 +0000324 state.getPendingGlobals(locked).push_back(GV);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000325 }
326 addGlobalMapping(GV, Ptr);
327 return Ptr;
328}
329
330
Chris Lattner4d326fa2003-12-20 01:46:27 +0000331/// recompileAndRelinkFunction - This method is used to force a function
332/// which has already been compiled, to be compiled again, possibly
333/// after it has been modified. Then the entry to the old copy is overwritten
334/// with a branch to the new copy. If there was no old copy, this acts
335/// just like JIT::getPointerToFunction().
336///
337void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000338 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000339
Chris Lattnerc07ed132003-12-20 03:36:47 +0000340 // If it's not already compiled there is no reason to patch it up.
341 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000342
Chris Lattnerc07ed132003-12-20 03:36:47 +0000343 // Delete the old function mapping.
344 addGlobalMapping(F, 0);
345
Chris Lattnerc07ed132003-12-20 03:36:47 +0000346 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000347 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000348
349 // Update state, forward the old function to the new function.
350 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000351 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
352 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
353 return Addr;
354}
Misha Brukman895eddf2004-11-07 23:58:46 +0000355