66e0468f189a9a1a4e4ef68f6687251bf5a93fd0
[oota-llvm.git] / lib / ExecutionEngine / JIT / JIT.cpp
1 //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
2 //
3 //                     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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bytecode 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"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/System/DynamicLibrary.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetJITInfo.h"
28 #include <iostream>
29 using namespace llvm;
30
31 static struct RegisterJIT {
32   RegisterJIT() { JIT::Register(); }
33 } JITRegistrator;
34
35 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
36   : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
37   setTargetData(TM.getTargetData());
38
39   // Initialize MCE
40   MCE = createEmitter(*this);
41
42   // Add target data
43   MutexGuard locked(lock);
44   FunctionPassManager& PM = state.getPM(locked);
45   PM.add(new TargetData(TM.getTargetData()));
46
47   // Compile LLVM Code down to machine code in the intermediate representation
48   TJI.addPassesToJITCompile(PM);
49
50   // Turn the machine code intermediate representation into bytes in memory that
51   // may be executed.
52   if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
53     std::cerr << "Target '" << TM.getName()
54               << "' doesn't support machine code emission!\n";
55     abort();
56   }
57 }
58
59 JIT::~JIT() {
60   delete MCE;
61   delete &TM;
62 }
63
64 /// run - Start execution with the specified function and arguments.
65 ///
66 GenericValue JIT::runFunction(Function *F,
67                               const std::vector<GenericValue> &ArgValues) {
68   assert(F && "Function *F was null at entry to run()");
69
70   void *FPtr = getPointerToFunction(F);
71   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
72   const FunctionType *FTy = F->getFunctionType();
73   const Type *RetTy = FTy->getReturnType();
74
75   assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
76          "Too many arguments passed into function!");
77   assert(FTy->getNumParams() == ArgValues.size() &&
78          "This doesn't support passing arguments through varargs (yet)!");
79
80   // Handle some common cases first.  These cases correspond to common `main'
81   // prototypes.
82   if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
83     switch (ArgValues.size()) {
84     case 3:
85       if ((FTy->getParamType(0) == Type::IntTy ||
86            FTy->getParamType(0) == Type::UIntTy) &&
87           isa<PointerType>(FTy->getParamType(1)) &&
88           isa<PointerType>(FTy->getParamType(2))) {
89         int (*PF)(int, char **, const char **) =
90           (int(*)(int, char **, const char **))FPtr;
91
92         // Call the function.
93         GenericValue rv;
94         rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
95                        (const char **)GVTOP(ArgValues[2]));
96         return rv;
97       }
98       break;
99     case 2:
100       if ((FTy->getParamType(0) == Type::IntTy ||
101            FTy->getParamType(0) == Type::UIntTy) &&
102           isa<PointerType>(FTy->getParamType(1))) {
103         int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
104
105         // Call the function.
106         GenericValue rv;
107         rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
108         return rv;
109       }
110       break;
111     case 1:
112       if (FTy->getNumParams() == 1 &&
113           (FTy->getParamType(0) == Type::IntTy ||
114            FTy->getParamType(0) == Type::UIntTy)) {
115         GenericValue rv;
116         int (*PF)(int) = (int(*)(int))FPtr;
117         rv.IntVal = PF(ArgValues[0].IntVal);
118         return rv;
119       }
120       break;
121     }
122   }
123
124   // Handle cases where no arguments are passed first.
125   if (ArgValues.empty()) {
126     GenericValue rv;
127     switch (RetTy->getTypeID()) {
128     default: assert(0 && "Unknown return type for function call!");
129     case Type::BoolTyID:
130       rv.BoolVal = ((bool(*)())FPtr)();
131       return rv;
132     case Type::SByteTyID:
133     case Type::UByteTyID:
134       rv.SByteVal = ((char(*)())FPtr)();
135       return rv;
136     case Type::ShortTyID:
137     case Type::UShortTyID:
138       rv.ShortVal = ((short(*)())FPtr)();
139       return rv;
140     case Type::VoidTyID:
141     case Type::IntTyID:
142     case Type::UIntTyID:
143       rv.IntVal = ((int(*)())FPtr)();
144       return rv;
145     case Type::LongTyID:
146     case Type::ULongTyID:
147       rv.LongVal = ((int64_t(*)())FPtr)();
148       return rv;
149     case Type::FloatTyID:
150       rv.FloatVal = ((float(*)())FPtr)();
151       return rv;
152     case Type::DoubleTyID:
153       rv.DoubleVal = ((double(*)())FPtr)();
154       return rv;
155     case Type::PointerTyID:
156       return PTOGV(((void*(*)())FPtr)());
157     }
158   }
159
160   // Okay, this is not one of our quick and easy cases.  Because we don't have a
161   // full FFI, we have to codegen a nullary stub function that just calls the
162   // function we are interested in, passing in constants for all of the
163   // arguments.  Make this function and return.
164
165   // First, create the function.
166   FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
167   Function *Stub = new Function(STy, Function::InternalLinkage, "",
168                                 F->getParent());
169
170   // Insert a basic block.
171   BasicBlock *StubBB = new BasicBlock("", Stub);
172
173   // Convert all of the GenericValue arguments over to constants.  Note that we
174   // currently don't support varargs.
175   std::vector<Value*> Args;
176   for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
177     Constant *C = 0;
178     const Type *ArgTy = FTy->getParamType(i);
179     const GenericValue &AV = ArgValues[i];
180     switch (ArgTy->getTypeID()) {
181     default: assert(0 && "Unknown argument type for function call!");
182     case Type::BoolTyID:   C = ConstantBool::get(AV.BoolVal); break;
183     case Type::SByteTyID:  C = ConstantSInt::get(ArgTy, AV.SByteVal);  break;
184     case Type::UByteTyID:  C = ConstantUInt::get(ArgTy, AV.UByteVal);  break;
185     case Type::ShortTyID:  C = ConstantSInt::get(ArgTy, AV.ShortVal);  break;
186     case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
187     case Type::IntTyID:    C = ConstantSInt::get(ArgTy, AV.IntVal);    break;
188     case Type::UIntTyID:   C = ConstantUInt::get(ArgTy, AV.UIntVal);   break;
189     case Type::LongTyID:   C = ConstantSInt::get(ArgTy, AV.LongVal);   break;
190     case Type::ULongTyID:  C = ConstantUInt::get(ArgTy, AV.ULongVal);  break;
191     case Type::FloatTyID:  C = ConstantFP  ::get(ArgTy, AV.FloatVal);  break;
192     case Type::DoubleTyID: C = ConstantFP  ::get(ArgTy, AV.DoubleVal); break;
193     case Type::PointerTyID:
194       void *ArgPtr = GVTOP(AV);
195       if (sizeof(void*) == 4) {
196         C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
197       } else {
198         C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
199       }
200       C = ConstantExpr::getCast(C, ArgTy);  // Cast the integer to pointer
201       break;
202     }
203     Args.push_back(C);
204   }
205
206   CallInst *TheCall = new CallInst(F, Args, "", StubBB);
207   TheCall->setTailCall();
208   if (TheCall->getType() != Type::VoidTy)
209     new ReturnInst(TheCall, StubBB);             // Return result of the call.
210   else
211     new ReturnInst(StubBB);                      // Just return void.
212
213   // Finally, return the value returned by our nullary stub function.
214   return runFunction(Stub, std::vector<GenericValue>());
215 }
216
217 /// runJITOnFunction - Run the FunctionPassManager full of
218 /// just-in-time compilation passes on F, hopefully filling in
219 /// GlobalAddress[F] with the address of F's machine code.
220 ///
221 void JIT::runJITOnFunction(Function *F) {
222   static bool isAlreadyCodeGenerating = false;
223   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
224
225   MutexGuard locked(lock);
226
227   // JIT the function
228   isAlreadyCodeGenerating = true;
229   state.getPM(locked).run(*F);
230   isAlreadyCodeGenerating = false;
231
232   // If the function referred to a global variable that had not yet been
233   // emitted, it allocates memory for the global, but doesn't emit it yet.  Emit
234   // all of these globals now.
235   while (!state.getPendingGlobals(locked).empty()) {
236     const GlobalVariable *GV = state.getPendingGlobals(locked).back();
237     state.getPendingGlobals(locked).pop_back();
238     EmitGlobalVariable(GV);
239   }
240 }
241
242 /// getPointerToFunction - This method is used to get the address of the
243 /// specified function, compiling it if neccesary.
244 ///
245 void *JIT::getPointerToFunction(Function *F) {
246   MutexGuard locked(lock);
247
248   if (void *Addr = getPointerToGlobalIfAvailable(F))
249     return Addr;   // Check if function already code gen'd
250
251   // Make sure we read in the function if it exists in this Module
252   if (F->hasNotBeenReadFromBytecode())
253     try {
254       MP->materializeFunction(F);
255     } catch ( std::string& errmsg ) {
256       std::cerr << "Error reading function '" << F->getName()
257                 << "' from bytecode file: " << errmsg << "\n";
258       abort();
259     } catch (...) {
260       std::cerr << "Error reading function '" << F->getName()
261                 << "from bytecode file!\n";
262       abort();
263     }
264
265   if (F->isExternal()) {
266     void *Addr = getPointerToNamedFunction(F->getName());
267     addGlobalMapping(F, Addr);
268     return Addr;
269   }
270
271   runJITOnFunction(F);
272
273   void *Addr = getPointerToGlobalIfAvailable(F);
274   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
275   return Addr;
276 }
277
278 /// getOrEmitGlobalVariable - Return the address of the specified global
279 /// variable, possibly emitting it to memory if needed.  This is used by the
280 /// Emitter.
281 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
282   MutexGuard locked(lock);
283
284   void *Ptr = getPointerToGlobalIfAvailable(GV);
285   if (Ptr) return Ptr;
286
287   // If the global is external, just remember the address.
288   if (GV->isExternal()) {
289     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
290     if (Ptr == 0) {
291       std::cerr << "Could not resolve external global address: "
292                 << GV->getName() << "\n";
293       abort();
294     }
295   } else {
296     // If the global hasn't been emitted to memory yet, allocate space.  We will
297     // actually initialize the global after current function has finished
298     // compilation.
299     uint64_t S = getTargetData().getTypeSize(GV->getType()->getElementType());
300     unsigned char A =
301       getTargetData().getTypeAlignment(GV->getType()->getElementType());
302     Ptr = MCE->allocateGlobal(S, A);
303     state.getPendingGlobals(locked).push_back(GV);
304   }
305   addGlobalMapping(GV, Ptr);
306   return Ptr;
307 }
308
309
310 /// recompileAndRelinkFunction - This method is used to force a function
311 /// which has already been compiled, to be compiled again, possibly
312 /// after it has been modified. Then the entry to the old copy is overwritten
313 /// with a branch to the new copy. If there was no old copy, this acts
314 /// just like JIT::getPointerToFunction().
315 ///
316 void *JIT::recompileAndRelinkFunction(Function *F) {
317   void *OldAddr = getPointerToGlobalIfAvailable(F);
318
319   // If it's not already compiled there is no reason to patch it up.
320   if (OldAddr == 0) { return getPointerToFunction(F); }
321
322   // Delete the old function mapping.
323   addGlobalMapping(F, 0);
324
325   // Recodegen the function
326   runJITOnFunction(F);
327
328   // Update state, forward the old function to the new function.
329   void *Addr = getPointerToGlobalIfAvailable(F);
330   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
331   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
332   return Addr;
333 }
334
335 /// freeMachineCodeForFunction - release machine code memory for given Function
336 ///
337 void JIT::freeMachineCodeForFunction(Function *F) {
338   // currently a no-op
339 }