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