blob: 91c8caf50c1e4bcd01aaeeb1bfdbcd1409b0ab40 [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"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000025#include "llvm/System/DynamicLibrary.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000026#include "llvm/Target/TargetMachine.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000027#include "llvm/Target/TargetJITInfo.h"
Reid Spencer954da372004-07-04 12:19:56 +000028#include <iostream>
Chris Lattnerc19aade2003-12-08 08:06:28 +000029using namespace llvm;
Misha Brukmanabb027c2003-05-27 21:40:39 +000030
Chris Lattner2fe4bb02006-03-22 06:07:50 +000031static struct RegisterJIT {
32 RegisterJIT() { JIT::Register(); }
33} JITRegistrator;
34
Jeff Cohen2f519142006-03-24 02:53:49 +000035namespace llvm {
36 void LinkInJIT() {
37 }
38}
39
Chris Lattner4d326fa2003-12-20 01:46:27 +000040JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
Reid Spenceree448632005-07-12 15:51:55 +000041 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +000042 setTargetData(TM.getTargetData());
Misha Brukmanabb027c2003-05-27 21:40:39 +000043
44 // Initialize MCE
Misha Brukman906f5fa2003-06-02 03:23:16 +000045 MCE = createEmitter(*this);
Misha Brukmanf976c852005-04-21 22:55:34 +000046
Brian Gaeke50872d52004-04-14 17:45:52 +000047 // Add target data
Reid Spenceree448632005-07-12 15:51:55 +000048 MutexGuard locked(lock);
49 FunctionPassManager& PM = state.getPM(locked);
Chris Lattnercc22e9f2004-08-16 00:14:18 +000050 PM.add(new TargetData(TM.getTargetData()));
Brian Gaeke50872d52004-04-14 17:45:52 +000051
Chris Lattner4d326fa2003-12-20 01:46:27 +000052 // Compile LLVM Code down to machine code in the intermediate representation
53 TJI.addPassesToJITCompile(PM);
54
55 // Turn the machine code intermediate representation into bytes in memory that
56 // may be executed.
57 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
Chris Lattnercc22e9f2004-08-16 00:14:18 +000058 std::cerr << "Target '" << TM.getName()
Chris Lattner4d326fa2003-12-20 01:46:27 +000059 << "' doesn't support machine code emission!\n";
60 abort();
61 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +000062}
63
Chris Lattner4d326fa2003-12-20 01:46:27 +000064JIT::~JIT() {
65 delete MCE;
66 delete &TM;
67}
68
Brian Gaeke70975ee2003-09-05 18:42:01 +000069/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +000070///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +000071GenericValue JIT::runFunction(Function *F,
72 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +000073 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +000074
75 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +000076 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +000077 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +000078 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +000079
Chris Lattnere5eab142004-08-15 23:53:06 +000080 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
81 "Too many arguments passed into function!");
82 assert(FTy->getNumParams() == ArgValues.size() &&
83 "This doesn't support passing arguments through varargs (yet)!");
84
Misha Brukmanec843022004-10-22 23:35:57 +000085 // Handle some common cases first. These cases correspond to common `main'
Chris Lattnere5eab142004-08-15 23:53:06 +000086 // prototypes.
Chris Lattnerd297aea2004-08-15 23:34:48 +000087 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +000088 switch (ArgValues.size()) {
89 case 3:
Misha Brukmanf976c852005-04-21 22:55:34 +000090 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +000091 FTy->getParamType(0) == Type::UIntTy) &&
92 isa<PointerType>(FTy->getParamType(1)) &&
93 isa<PointerType>(FTy->getParamType(2))) {
94 int (*PF)(int, char **, const char **) =
95 (int(*)(int, char **, const char **))FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +000096
Chris Lattnerf7bedf42004-08-15 23:39:59 +000097 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +000098 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +000099 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
100 (const char **)GVTOP(ArgValues[2]));
101 return rv;
102 }
103 break;
Chris Lattner174f2262004-08-16 01:07:04 +0000104 case 2:
Misha Brukmanf976c852005-04-21 22:55:34 +0000105 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattner174f2262004-08-16 01:07:04 +0000106 FTy->getParamType(0) == Type::UIntTy) &&
107 isa<PointerType>(FTy->getParamType(1))) {
108 int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000109
Chris Lattner174f2262004-08-16 01:07:04 +0000110 // Call the function.
111 GenericValue rv;
112 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
113 return rv;
114 }
115 break;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000116 case 1:
117 if (FTy->getNumParams() == 1 &&
Misha Brukmanf976c852005-04-21 22:55:34 +0000118 (FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000119 FTy->getParamType(0) == Type::UIntTy)) {
Chris Lattnere5eab142004-08-15 23:53:06 +0000120 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000121 int (*PF)(int) = (int(*)(int))FPtr;
122 rv.IntVal = PF(ArgValues[0].IntVal);
123 return rv;
124 }
125 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000126 }
127 }
128
129 // Handle cases where no arguments are passed first.
130 if (ArgValues.empty()) {
131 GenericValue rv;
132 switch (RetTy->getTypeID()) {
133 default: assert(0 && "Unknown return type for function call!");
134 case Type::BoolTyID:
135 rv.BoolVal = ((bool(*)())FPtr)();
Chris Lattnerd297aea2004-08-15 23:34:48 +0000136 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000137 case Type::SByteTyID:
138 case Type::UByteTyID:
139 rv.SByteVal = ((char(*)())FPtr)();
140 return rv;
141 case Type::ShortTyID:
142 case Type::UShortTyID:
143 rv.ShortVal = ((short(*)())FPtr)();
144 return rv;
145 case Type::VoidTyID:
146 case Type::IntTyID:
147 case Type::UIntTyID:
148 rv.IntVal = ((int(*)())FPtr)();
149 return rv;
150 case Type::LongTyID:
151 case Type::ULongTyID:
152 rv.LongVal = ((int64_t(*)())FPtr)();
153 return rv;
154 case Type::FloatTyID:
155 rv.FloatVal = ((float(*)())FPtr)();
156 return rv;
157 case Type::DoubleTyID:
158 rv.DoubleVal = ((double(*)())FPtr)();
159 return rv;
160 case Type::PointerTyID:
161 return PTOGV(((void*(*)())FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000162 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000163 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000164
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000165 // Okay, this is not one of our quick and easy cases. Because we don't have a
166 // full FFI, we have to codegen a nullary stub function that just calls the
167 // function we are interested in, passing in constants for all of the
168 // arguments. Make this function and return.
169
170 // First, create the function.
171 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
172 Function *Stub = new Function(STy, Function::InternalLinkage, "",
173 F->getParent());
174
175 // Insert a basic block.
176 BasicBlock *StubBB = new BasicBlock("", Stub);
177
178 // Convert all of the GenericValue arguments over to constants. Note that we
179 // currently don't support varargs.
180 std::vector<Value*> Args;
181 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
182 Constant *C = 0;
183 const Type *ArgTy = FTy->getParamType(i);
184 const GenericValue &AV = ArgValues[i];
185 switch (ArgTy->getTypeID()) {
186 default: assert(0 && "Unknown argument type for function call!");
187 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
188 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
189 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
190 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
191 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
192 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
193 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
194 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
195 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
196 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
197 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
198 case Type::PointerTyID:
199 void *ArgPtr = GVTOP(AV);
200 if (sizeof(void*) == 4) {
201 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
202 } else {
203 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
204 }
205 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
206 break;
207 }
208 Args.push_back(C);
209 }
210
Chris Lattnera471e042005-05-06 06:48:54 +0000211 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
212 TheCall->setTailCall();
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000213 if (TheCall->getType() != Type::VoidTy)
214 new ReturnInst(TheCall, StubBB); // Return result of the call.
215 else
216 new ReturnInst(StubBB); // Just return void.
217
218 // Finally, return the value returned by our nullary stub function.
219 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000220}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000221
222/// runJITOnFunction - Run the FunctionPassManager full of
223/// just-in-time compilation passes on F, hopefully filling in
224/// GlobalAddress[F] with the address of F's machine code.
225///
226void JIT::runJITOnFunction(Function *F) {
227 static bool isAlreadyCodeGenerating = false;
228 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Jeff Cohen00b168892005-07-27 06:12:32 +0000229
Reid Spenceree448632005-07-12 15:51:55 +0000230 MutexGuard locked(lock);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000231
232 // JIT the function
233 isAlreadyCodeGenerating = true;
Reid Spenceree448632005-07-12 15:51:55 +0000234 state.getPM(locked).run(*F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000235 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000236
237 // If the function referred to a global variable that had not yet been
238 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
239 // all of these globals now.
Reid Spenceree448632005-07-12 15:51:55 +0000240 while (!state.getPendingGlobals(locked).empty()) {
241 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
242 state.getPendingGlobals(locked).pop_back();
Chris Lattnerc07ed132003-12-20 03:36:47 +0000243 EmitGlobalVariable(GV);
244 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000245}
246
247/// getPointerToFunction - This method is used to get the address of the
248/// specified function, compiling it if neccesary.
249///
250void *JIT::getPointerToFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000251 MutexGuard locked(lock);
252
Chris Lattnerc07ed132003-12-20 03:36:47 +0000253 if (void *Addr = getPointerToGlobalIfAvailable(F))
254 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000255
256 // Make sure we read in the function if it exists in this Module
Misha Brukmanf976c852005-04-21 22:55:34 +0000257 if (F->hasNotBeenReadFromBytecode())
Chris Lattner0050ef82004-11-15 23:18:09 +0000258 try {
259 MP->materializeFunction(F);
260 } catch ( std::string& errmsg ) {
261 std::cerr << "Error reading function '" << F->getName()
262 << "' from bytecode file: " << errmsg << "\n";
263 abort();
264 } catch (...) {
265 std::cerr << "Error reading function '" << F->getName()
266 << "from bytecode file!\n";
267 abort();
268 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000269
Chris Lattnerc07ed132003-12-20 03:36:47 +0000270 if (F->isExternal()) {
271 void *Addr = getPointerToNamedFunction(F->getName());
272 addGlobalMapping(F, Addr);
273 return Addr;
274 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000275
276 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000277
278 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000279 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
280 return Addr;
281}
282
Chris Lattnerc07ed132003-12-20 03:36:47 +0000283/// getOrEmitGlobalVariable - Return the address of the specified global
284/// variable, possibly emitting it to memory if needed. This is used by the
285/// Emitter.
286void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
Reid Spenceree448632005-07-12 15:51:55 +0000287 MutexGuard locked(lock);
288
Chris Lattnerc07ed132003-12-20 03:36:47 +0000289 void *Ptr = getPointerToGlobalIfAvailable(GV);
290 if (Ptr) return Ptr;
291
292 // If the global is external, just remember the address.
293 if (GV->isExternal()) {
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000294 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
Chris Lattnerc07ed132003-12-20 03:36:47 +0000295 if (Ptr == 0) {
296 std::cerr << "Could not resolve external global address: "
297 << GV->getName() << "\n";
298 abort();
299 }
300 } else {
301 // If the global hasn't been emitted to memory yet, allocate space. We will
302 // actually initialize the global after current function has finished
303 // compilation.
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000304 const Type *GlobalType = GV->getType()->getElementType();
Owen Andersona69571c2006-05-03 01:29:57 +0000305 size_t S = getTargetData()->getTypeSize(GlobalType);
306 size_t A = getTargetData()->getTypeAlignment(GlobalType);
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000307 if (A <= 8) {
308 Ptr = malloc(S);
309 } else {
310 // Allocate S+A bytes of memory, then use an aligned pointer within that
311 // space.
312 Ptr = malloc(S+A);
313 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
314 unsigned Offset = MisAligned ? (A-MisAligned) : 0;
315
316 // Trim the tail off the memory block.
317 realloc(Ptr, S+Offset);
318 Ptr = (char*)Ptr + Offset;
319 }
Reid Spenceree448632005-07-12 15:51:55 +0000320 state.getPendingGlobals(locked).push_back(GV);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000321 }
322 addGlobalMapping(GV, Ptr);
323 return Ptr;
324}
325
326
Chris Lattner4d326fa2003-12-20 01:46:27 +0000327/// recompileAndRelinkFunction - This method is used to force a function
328/// which has already been compiled, to be compiled again, possibly
329/// after it has been modified. Then the entry to the old copy is overwritten
330/// with a branch to the new copy. If there was no old copy, this acts
331/// just like JIT::getPointerToFunction().
332///
333void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000334 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000335
Chris Lattnerc07ed132003-12-20 03:36:47 +0000336 // If it's not already compiled there is no reason to patch it up.
337 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000338
Chris Lattnerc07ed132003-12-20 03:36:47 +0000339 // Delete the old function mapping.
340 addGlobalMapping(F, 0);
341
Chris Lattnerc07ed132003-12-20 03:36:47 +0000342 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000343 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000344
345 // Update state, forward the old function to the new function.
346 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000347 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
348 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
349 return Addr;
350}
Misha Brukman895eddf2004-11-07 23:58:46 +0000351
352/// freeMachineCodeForFunction - release machine code memory for given Function
353///
354void JIT::freeMachineCodeForFunction(Function *F) {
355 // currently a no-op
356}