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