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