LLVM API Documentation
00001 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the common interface used by the various execution engine 00011 // subclasses. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #define DEBUG_TYPE "jit" 00016 #include "llvm/Constants.h" 00017 #include "llvm/DerivedTypes.h" 00018 #include "llvm/Module.h" 00019 #include "llvm/ModuleProvider.h" 00020 #include "llvm/ADT/Statistic.h" 00021 #include "llvm/Config/alloca.h" 00022 #include "llvm/ExecutionEngine/ExecutionEngine.h" 00023 #include "llvm/ExecutionEngine/GenericValue.h" 00024 #include "llvm/Support/Debug.h" 00025 #include "llvm/Support/MutexGuard.h" 00026 #include "llvm/System/DynamicLibrary.h" 00027 #include "llvm/System/Host.h" 00028 #include "llvm/Target/TargetData.h" 00029 #include <cmath> 00030 #include <cstring> 00031 using namespace llvm; 00032 00033 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 00034 STATISTIC(NumGlobals , "Number of global vars initialized"); 00035 00036 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0; 00037 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0; 00038 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0; 00039 00040 00041 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) { 00042 LazyCompilationDisabled = false; 00043 GVCompilationDisabled = false; 00044 SymbolSearchingDisabled = false; 00045 Modules.push_back(P); 00046 assert(P && "ModuleProvider is null?"); 00047 } 00048 00049 ExecutionEngine::~ExecutionEngine() { 00050 clearAllGlobalMappings(); 00051 for (unsigned i = 0, e = Modules.size(); i != e; ++i) 00052 delete Modules[i]; 00053 } 00054 00055 char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) { 00056 const Type *ElTy = GV->getType()->getElementType(); 00057 size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy); 00058 return new char[GVSize]; 00059 } 00060 00061 /// removeModuleProvider - Remove a ModuleProvider from the list of modules. 00062 /// Relases the Module from the ModuleProvider, materializing it in the 00063 /// process, and returns the materialized Module. 00064 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P, 00065 std::string *ErrInfo) { 00066 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 00067 E = Modules.end(); I != E; ++I) { 00068 ModuleProvider *MP = *I; 00069 if (MP == P) { 00070 Modules.erase(I); 00071 clearGlobalMappingsFromModule(MP->getModule()); 00072 return MP->releaseModule(ErrInfo); 00073 } 00074 } 00075 return NULL; 00076 } 00077 00078 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules, 00079 /// and deletes the ModuleProvider and owned Module. Avoids materializing 00080 /// the underlying module. 00081 void ExecutionEngine::deleteModuleProvider(ModuleProvider *P, 00082 std::string *ErrInfo) { 00083 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 00084 E = Modules.end(); I != E; ++I) { 00085 ModuleProvider *MP = *I; 00086 if (MP == P) { 00087 Modules.erase(I); 00088 clearGlobalMappingsFromModule(MP->getModule()); 00089 delete MP; 00090 return; 00091 } 00092 } 00093 } 00094 00095 /// FindFunctionNamed - Search all of the active modules to find the one that 00096 /// defines FnName. This is very slow operation and shouldn't be used for 00097 /// general code. 00098 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 00099 for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 00100 if (Function *F = Modules[i]->getModule()->getFunction(FnName)) 00101 return F; 00102 } 00103 return 0; 00104 } 00105 00106 00107 /// addGlobalMapping - Tell the execution engine that the specified global is 00108 /// at the specified location. This is used internally as functions are JIT'd 00109 /// and as global variables are laid out in memory. It can and should also be 00110 /// used by clients of the EE that want to have an LLVM global overlay 00111 /// existing data in memory. 00112 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 00113 MutexGuard locked(lock); 00114 00115 DOUT << "JIT: Map \'" << GV->getNameStart() << "\' to [" << Addr << "]\n"; 00116 void *&CurVal = state.getGlobalAddressMap(locked)[GV]; 00117 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!"); 00118 CurVal = Addr; 00119 00120 // If we are using the reverse mapping, add it too 00121 if (!state.getGlobalAddressReverseMap(locked).empty()) { 00122 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr]; 00123 assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 00124 V = GV; 00125 } 00126 } 00127 00128 /// clearAllGlobalMappings - Clear all global mappings and start over again 00129 /// use in dynamic compilation scenarios when you want to move globals 00130 void ExecutionEngine::clearAllGlobalMappings() { 00131 MutexGuard locked(lock); 00132 00133 state.getGlobalAddressMap(locked).clear(); 00134 state.getGlobalAddressReverseMap(locked).clear(); 00135 } 00136 00137 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a 00138 /// particular module, because it has been removed from the JIT. 00139 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) { 00140 MutexGuard locked(lock); 00141 00142 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) { 00143 state.getGlobalAddressMap(locked).erase(FI); 00144 state.getGlobalAddressReverseMap(locked).erase(FI); 00145 } 00146 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 00147 GI != GE; ++GI) { 00148 state.getGlobalAddressMap(locked).erase(GI); 00149 state.getGlobalAddressReverseMap(locked).erase(GI); 00150 } 00151 } 00152 00153 /// updateGlobalMapping - Replace an existing mapping for GV with a new 00154 /// address. This updates both maps as required. If "Addr" is null, the 00155 /// entry for the global is removed from the mappings. 00156 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 00157 MutexGuard locked(lock); 00158 00159 std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked); 00160 00161 // Deleting from the mapping? 00162 if (Addr == 0) { 00163 std::map<const GlobalValue*, void *>::iterator I = Map.find(GV); 00164 void *OldVal; 00165 if (I == Map.end()) 00166 OldVal = 0; 00167 else { 00168 OldVal = I->second; 00169 Map.erase(I); 00170 } 00171 00172 if (!state.getGlobalAddressReverseMap(locked).empty()) 00173 state.getGlobalAddressReverseMap(locked).erase(Addr); 00174 return OldVal; 00175 } 00176 00177 void *&CurVal = Map[GV]; 00178 void *OldVal = CurVal; 00179 00180 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty()) 00181 state.getGlobalAddressReverseMap(locked).erase(CurVal); 00182 CurVal = Addr; 00183 00184 // If we are using the reverse mapping, add it too 00185 if (!state.getGlobalAddressReverseMap(locked).empty()) { 00186 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr]; 00187 assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 00188 V = GV; 00189 } 00190 return OldVal; 00191 } 00192 00193 /// getPointerToGlobalIfAvailable - This returns the address of the specified 00194 /// global value if it is has already been codegen'd, otherwise it returns null. 00195 /// 00196 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 00197 MutexGuard locked(lock); 00198 00199 std::map<const GlobalValue*, void*>::iterator I = 00200 state.getGlobalAddressMap(locked).find(GV); 00201 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0; 00202 } 00203 00204 /// getGlobalValueAtAddress - Return the LLVM global value object that starts 00205 /// at the specified address. 00206 /// 00207 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 00208 MutexGuard locked(lock); 00209 00210 // If we haven't computed the reverse mapping yet, do so first. 00211 if (state.getGlobalAddressReverseMap(locked).empty()) { 00212 for (std::map<const GlobalValue*, void *>::iterator 00213 I = state.getGlobalAddressMap(locked).begin(), 00214 E = state.getGlobalAddressMap(locked).end(); I != E; ++I) 00215 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, 00216 I->first)); 00217 } 00218 00219 std::map<void *, const GlobalValue*>::iterator I = 00220 state.getGlobalAddressReverseMap(locked).find(Addr); 00221 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0; 00222 } 00223 00224 // CreateArgv - Turn a vector of strings into a nice argv style array of 00225 // pointers to null terminated strings. 00226 // 00227 static void *CreateArgv(ExecutionEngine *EE, 00228 const std::vector<std::string> &InputArgv) { 00229 unsigned PtrSize = EE->getTargetData()->getPointerSize(); 00230 char *Result = new char[(InputArgv.size()+1)*PtrSize]; 00231 00232 DOUT << "JIT: ARGV = " << (void*)Result << "\n"; 00233 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty); 00234 00235 for (unsigned i = 0; i != InputArgv.size(); ++i) { 00236 unsigned Size = InputArgv[i].size()+1; 00237 char *Dest = new char[Size]; 00238 DOUT << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n"; 00239 00240 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 00241 Dest[Size-1] = 0; 00242 00243 // Endian safe: Result[i] = (PointerTy)Dest; 00244 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize), 00245 SBytePtr); 00246 } 00247 00248 // Null terminate it 00249 EE->StoreValueToMemory(PTOGV(0), 00250 (GenericValue*)(Result+InputArgv.size()*PtrSize), 00251 SBytePtr); 00252 return Result; 00253 } 00254 00255 00256 /// runStaticConstructorsDestructors - This method is used to execute all of 00257 /// the static constructors or destructors for a module, depending on the 00258 /// value of isDtors. 00259 void ExecutionEngine::runStaticConstructorsDestructors(Module *module, bool isDtors) { 00260 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 00261 00262 // Execute global ctors/dtors for each module in the program. 00263 00264 GlobalVariable *GV = module->getNamedGlobal(Name); 00265 00266 // If this global has internal linkage, or if it has a use, then it must be 00267 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 00268 // this is the case, don't execute any of the global ctors, __main will do 00269 // it. 00270 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return; 00271 00272 // Should be an array of '{ int, void ()* }' structs. The first value is 00273 // the init priority, which we ignore. 00274 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 00275 if (!InitList) return; 00276 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 00277 if (ConstantStruct *CS = 00278 dyn_cast<ConstantStruct>(InitList->getOperand(i))) { 00279 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs. 00280 00281 Constant *FP = CS->getOperand(1); 00282 if (FP->isNullValue()) 00283 break; // Found a null terminator, exit. 00284 00285 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 00286 if (CE->isCast()) 00287 FP = CE->getOperand(0); 00288 if (Function *F = dyn_cast<Function>(FP)) { 00289 // Execute the ctor/dtor function! 00290 runFunction(F, std::vector<GenericValue>()); 00291 } 00292 } 00293 } 00294 00295 /// runStaticConstructorsDestructors - This method is used to execute all of 00296 /// the static constructors or destructors for a program, depending on the 00297 /// value of isDtors. 00298 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 00299 // Execute global ctors/dtors for each module in the program. 00300 for (unsigned m = 0, e = Modules.size(); m != e; ++m) 00301 runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors); 00302 } 00303 00304 #ifndef NDEBUG 00305 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null. 00306 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) { 00307 unsigned PtrSize = EE->getTargetData()->getPointerSize(); 00308 for (unsigned i = 0; i < PtrSize; ++i) 00309 if (*(i + (uint8_t*)Loc)) 00310 return false; 00311 return true; 00312 } 00313 #endif 00314 00315 /// runFunctionAsMain - This is a helper function which wraps runFunction to 00316 /// handle the common task of starting up main with the specified argc, argv, 00317 /// and envp parameters. 00318 int ExecutionEngine::runFunctionAsMain(Function *Fn, 00319 const std::vector<std::string> &argv, 00320 const char * const * envp) { 00321 std::vector<GenericValue> GVArgs; 00322 GenericValue GVArgc; 00323 GVArgc.IntVal = APInt(32, argv.size()); 00324 00325 // Check main() type 00326 unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 00327 const FunctionType *FTy = Fn->getFunctionType(); 00328 const Type* PPInt8Ty = 00329 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty)); 00330 switch (NumArgs) { 00331 case 3: 00332 if (FTy->getParamType(2) != PPInt8Ty) { 00333 cerr << "Invalid type for third argument of main() supplied\n"; 00334 abort(); 00335 } 00336 // FALLS THROUGH 00337 case 2: 00338 if (FTy->getParamType(1) != PPInt8Ty) { 00339 cerr << "Invalid type for second argument of main() supplied\n"; 00340 abort(); 00341 } 00342 // FALLS THROUGH 00343 case 1: 00344 if (FTy->getParamType(0) != Type::Int32Ty) { 00345 cerr << "Invalid type for first argument of main() supplied\n"; 00346 abort(); 00347 } 00348 // FALLS THROUGH 00349 case 0: 00350 if (FTy->getReturnType() != Type::Int32Ty && 00351 FTy->getReturnType() != Type::VoidTy) { 00352 cerr << "Invalid return type of main() supplied\n"; 00353 abort(); 00354 } 00355 break; 00356 default: 00357 cerr << "Invalid number of arguments of main() supplied\n"; 00358 abort(); 00359 } 00360 00361 if (NumArgs) { 00362 GVArgs.push_back(GVArgc); // Arg #0 = argc. 00363 if (NumArgs > 1) { 00364 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv. 00365 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) && 00366 "argv[0] was null after CreateArgv"); 00367 if (NumArgs > 2) { 00368 std::vector<std::string> EnvVars; 00369 for (unsigned i = 0; envp[i]; ++i) 00370 EnvVars.push_back(envp[i]); 00371 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp. 00372 } 00373 } 00374 } 00375 return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 00376 } 00377 00378 /// If possible, create a JIT, unless the caller specifically requests an 00379 /// Interpreter or there's an error. If even an Interpreter cannot be created, 00380 /// NULL is returned. 00381 /// 00382 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP, 00383 bool ForceInterpreter, 00384 std::string *ErrorStr, 00385 bool Fast) { 00386 ExecutionEngine *EE = 0; 00387 00388 // Make sure we can resolve symbols in the program as well. The zero arg 00389 // to the function tells DynamicLibrary to load the program, not a library. 00390 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) 00391 return 0; 00392 00393 // Unless the interpreter was explicitly selected, try making a JIT. 00394 if (!ForceInterpreter && JITCtor) 00395 EE = JITCtor(MP, ErrorStr, Fast); 00396 00397 // If we can't make a JIT, make an interpreter instead. 00398 if (EE == 0 && InterpCtor) 00399 EE = InterpCtor(MP, ErrorStr, Fast); 00400 00401 return EE; 00402 } 00403 00404 ExecutionEngine *ExecutionEngine::create(Module *M) { 00405 return create(new ExistingModuleProvider(M)); 00406 } 00407 00408 /// getPointerToGlobal - This returns the address of the specified global 00409 /// value. This may involve code generation if it's a function. 00410 /// 00411 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 00412 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 00413 return getPointerToFunction(F); 00414 00415 MutexGuard locked(lock); 00416 void *p = state.getGlobalAddressMap(locked)[GV]; 00417 if (p) 00418 return p; 00419 00420 // Global variable might have been added since interpreter started. 00421 if (GlobalVariable *GVar = 00422 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 00423 EmitGlobalVariable(GVar); 00424 else 00425 assert(0 && "Global hasn't had an address allocated yet!"); 00426 return state.getGlobalAddressMap(locked)[GV]; 00427 } 00428 00429 /// This function converts a Constant* into a GenericValue. The interesting 00430 /// part is if C is a ConstantExpr. 00431 /// @brief Get a GenericValue for a Constant* 00432 GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 00433 // If its undefined, return the garbage. 00434 if (isa<UndefValue>(C)) 00435 return GenericValue(); 00436 00437 // If the value is a ConstantExpr 00438 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 00439 Constant *Op0 = CE->getOperand(0); 00440 switch (CE->getOpcode()) { 00441 case Instruction::GetElementPtr: { 00442 // Compute the index 00443 GenericValue Result = getConstantValue(Op0); 00444 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end()); 00445 uint64_t Offset = 00446 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size()); 00447 00448 char* tmp = (char*) Result.PointerVal; 00449 Result = PTOGV(tmp + Offset); 00450 return Result; 00451 } 00452 case Instruction::Trunc: { 00453 GenericValue GV = getConstantValue(Op0); 00454 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 00455 GV.IntVal = GV.IntVal.trunc(BitWidth); 00456 return GV; 00457 } 00458 case Instruction::ZExt: { 00459 GenericValue GV = getConstantValue(Op0); 00460 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 00461 GV.IntVal = GV.IntVal.zext(BitWidth); 00462 return GV; 00463 } 00464 case Instruction::SExt: { 00465 GenericValue GV = getConstantValue(Op0); 00466 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 00467 GV.IntVal = GV.IntVal.sext(BitWidth); 00468 return GV; 00469 } 00470 case Instruction::FPTrunc: { 00471 // FIXME long double 00472 GenericValue GV = getConstantValue(Op0); 00473 GV.FloatVal = float(GV.DoubleVal); 00474 return GV; 00475 } 00476 case Instruction::FPExt:{ 00477 // FIXME long double 00478 GenericValue GV = getConstantValue(Op0); 00479 GV.DoubleVal = double(GV.FloatVal); 00480 return GV; 00481 } 00482 case Instruction::UIToFP: { 00483 GenericValue GV = getConstantValue(Op0); 00484 if (CE->getType() == Type::FloatTy) 00485 GV.FloatVal = float(GV.IntVal.roundToDouble()); 00486 else if (CE->getType() == Type::DoubleTy) 00487 GV.DoubleVal = GV.IntVal.roundToDouble(); 00488 else if (CE->getType() == Type::X86_FP80Ty) { 00489 const uint64_t zero[] = {0, 0}; 00490 APFloat apf = APFloat(APInt(80, 2, zero)); 00491 (void)apf.convertFromAPInt(GV.IntVal, 00492 false, 00493 APFloat::rmNearestTiesToEven); 00494 GV.IntVal = apf.bitcastToAPInt(); 00495 } 00496 return GV; 00497 } 00498 case Instruction::SIToFP: { 00499 GenericValue GV = getConstantValue(Op0); 00500 if (CE->getType() == Type::FloatTy) 00501 GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 00502 else if (CE->getType() == Type::DoubleTy) 00503 GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 00504 else if (CE->getType() == Type::X86_FP80Ty) { 00505 const uint64_t zero[] = { 0, 0}; 00506 APFloat apf = APFloat(APInt(80, 2, zero)); 00507 (void)apf.convertFromAPInt(GV.IntVal, 00508 true, 00509 APFloat::rmNearestTiesToEven); 00510 GV.IntVal = apf.bitcastToAPInt(); 00511 } 00512 return GV; 00513 } 00514 case Instruction::FPToUI: // double->APInt conversion handles sign 00515 case Instruction::FPToSI: { 00516 GenericValue GV = getConstantValue(Op0); 00517 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 00518 if (Op0->getType() == Type::FloatTy) 00519 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 00520 else if (Op0->getType() == Type::DoubleTy) 00521 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 00522 else if (Op0->getType() == Type::X86_FP80Ty) { 00523 APFloat apf = APFloat(GV.IntVal); 00524 uint64_t v; 00525 bool ignored; 00526 (void)apf.convertToInteger(&v, BitWidth, 00527 CE->getOpcode()==Instruction::FPToSI, 00528 APFloat::rmTowardZero, &ignored); 00529 GV.IntVal = v; // endian? 00530 } 00531 return GV; 00532 } 00533 case Instruction::PtrToInt: { 00534 GenericValue GV = getConstantValue(Op0); 00535 uint32_t PtrWidth = TD->getPointerSizeInBits(); 00536 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 00537 return GV; 00538 } 00539 case Instruction::IntToPtr: { 00540 GenericValue GV = getConstantValue(Op0); 00541 uint32_t PtrWidth = TD->getPointerSizeInBits(); 00542 if (PtrWidth != GV.IntVal.getBitWidth()) 00543 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 00544 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 00545 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 00546 return GV; 00547 } 00548 case Instruction::BitCast: { 00549 GenericValue GV = getConstantValue(Op0); 00550 const Type* DestTy = CE->getType(); 00551 switch (Op0->getType()->getTypeID()) { 00552 default: assert(0 && "Invalid bitcast operand"); 00553 case Type::IntegerTyID: 00554 assert(DestTy->isFloatingPoint() && "invalid bitcast"); 00555 if (DestTy == Type::FloatTy) 00556 GV.FloatVal = GV.IntVal.bitsToFloat(); 00557 else if (DestTy == Type::DoubleTy) 00558 GV.DoubleVal = GV.IntVal.bitsToDouble(); 00559 break; 00560 case Type::FloatTyID: 00561 assert(DestTy == Type::Int32Ty && "Invalid bitcast"); 00562 GV.IntVal.floatToBits(GV.FloatVal); 00563 break; 00564 case Type::DoubleTyID: 00565 assert(DestTy == Type::Int64Ty && "Invalid bitcast"); 00566 GV.IntVal.doubleToBits(GV.DoubleVal); 00567 break; 00568 case Type::PointerTyID: 00569 assert(isa<PointerType>(DestTy) && "Invalid bitcast"); 00570 break; // getConstantValue(Op0) above already converted it 00571 } 00572 return GV; 00573 } 00574 case Instruction::Add: 00575 case Instruction::Sub: 00576 case Instruction::Mul: 00577 case Instruction::UDiv: 00578 case Instruction::SDiv: 00579 case Instruction::URem: 00580 case Instruction::SRem: 00581 case Instruction::And: 00582 case Instruction::Or: 00583 case Instruction::Xor: { 00584 GenericValue LHS = getConstantValue(Op0); 00585 GenericValue RHS = getConstantValue(CE->getOperand(1)); 00586 GenericValue GV; 00587 switch (CE->getOperand(0)->getType()->getTypeID()) { 00588 default: assert(0 && "Bad add type!"); abort(); 00589 case Type::IntegerTyID: 00590 switch (CE->getOpcode()) { 00591 default: assert(0 && "Invalid integer opcode"); 00592 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 00593 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 00594 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 00595 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 00596 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 00597 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 00598 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 00599 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 00600 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 00601 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 00602 } 00603 break; 00604 case Type::FloatTyID: 00605 switch (CE->getOpcode()) { 00606 default: assert(0 && "Invalid float opcode"); abort(); 00607 case Instruction::Add: 00608 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 00609 case Instruction::Sub: 00610 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 00611 case Instruction::Mul: 00612 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 00613 case Instruction::FDiv: 00614 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 00615 case Instruction::FRem: 00616 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break; 00617 } 00618 break; 00619 case Type::DoubleTyID: 00620 switch (CE->getOpcode()) { 00621 default: assert(0 && "Invalid double opcode"); abort(); 00622 case Instruction::Add: 00623 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 00624 case Instruction::Sub: 00625 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 00626 case Instruction::Mul: 00627 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 00628 case Instruction::FDiv: 00629 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 00630 case Instruction::FRem: 00631 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 00632 } 00633 break; 00634 case Type::X86_FP80TyID: 00635 case Type::PPC_FP128TyID: 00636 case Type::FP128TyID: { 00637 APFloat apfLHS = APFloat(LHS.IntVal); 00638 switch (CE->getOpcode()) { 00639 default: assert(0 && "Invalid long double opcode"); abort(); 00640 case Instruction::Add: 00641 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 00642 GV.IntVal = apfLHS.bitcastToAPInt(); 00643 break; 00644 case Instruction::Sub: 00645 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 00646 GV.IntVal = apfLHS.bitcastToAPInt(); 00647 break; 00648 case Instruction::Mul: 00649 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 00650 GV.IntVal = apfLHS.bitcastToAPInt(); 00651 break; 00652 case Instruction::FDiv: 00653 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 00654 GV.IntVal = apfLHS.bitcastToAPInt(); 00655 break; 00656 case Instruction::FRem: 00657 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 00658 GV.IntVal = apfLHS.bitcastToAPInt(); 00659 break; 00660 } 00661 } 00662 break; 00663 } 00664 return GV; 00665 } 00666 default: 00667 break; 00668 } 00669 cerr << "ConstantExpr not handled: " << *CE << "\n"; 00670 abort(); 00671 } 00672 00673 GenericValue Result; 00674 switch (C->getType()->getTypeID()) { 00675 case Type::FloatTyID: 00676 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 00677 break; 00678 case Type::DoubleTyID: 00679 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 00680 break; 00681 case Type::X86_FP80TyID: 00682 case Type::FP128TyID: 00683 case Type::PPC_FP128TyID: 00684 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt(); 00685 break; 00686 case Type::IntegerTyID: 00687 Result.IntVal = cast<ConstantInt>(C)->getValue(); 00688 break; 00689 case Type::PointerTyID: 00690 if (isa<ConstantPointerNull>(C)) 00691 Result.PointerVal = 0; 00692 else if (const Function *F = dyn_cast<Function>(C)) 00693 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 00694 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C)) 00695 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 00696 else 00697 assert(0 && "Unknown constant pointer type!"); 00698 break; 00699 default: 00700 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n"; 00701 abort(); 00702 } 00703 return Result; 00704 } 00705 00706 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 00707 /// with the integer held in IntVal. 00708 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 00709 unsigned StoreBytes) { 00710 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 00711 uint8_t *Src = (uint8_t *)IntVal.getRawData(); 00712 00713 if (sys::isLittleEndianHost()) 00714 // Little-endian host - the source is ordered from LSB to MSB. Order the 00715 // destination from LSB to MSB: Do a straight copy. 00716 memcpy(Dst, Src, StoreBytes); 00717 else { 00718 // Big-endian host - the source is an array of 64 bit words ordered from 00719 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 00720 // from MSB to LSB: Reverse the word order, but not the bytes in a word. 00721 while (StoreBytes > sizeof(uint64_t)) { 00722 StoreBytes -= sizeof(uint64_t); 00723 // May not be aligned so use memcpy. 00724 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 00725 Src += sizeof(uint64_t); 00726 } 00727 00728 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 00729 } 00730 } 00731 00732 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr 00733 /// is the address of the memory at which to store Val, cast to GenericValue *. 00734 /// It is not a pointer to a GenericValue containing the address at which to 00735 /// store Val. 00736 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, 00737 GenericValue *Ptr, const Type *Ty) { 00738 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty); 00739 00740 switch (Ty->getTypeID()) { 00741 case Type::IntegerTyID: 00742 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes); 00743 break; 00744 case Type::FloatTyID: 00745 *((float*)Ptr) = Val.FloatVal; 00746 break; 00747 case Type::DoubleTyID: 00748 *((double*)Ptr) = Val.DoubleVal; 00749 break; 00750 case Type::X86_FP80TyID: { 00751 uint16_t *Dest = (uint16_t*)Ptr; 00752 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData(); 00753 // This is endian dependent, but it will only work on x86 anyway. 00754 Dest[0] = Src[4]; 00755 Dest[1] = Src[0]; 00756 Dest[2] = Src[1]; 00757 Dest[3] = Src[2]; 00758 Dest[4] = Src[3]; 00759 break; 00760 } 00761 case Type::PointerTyID: 00762 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts. 00763 if (StoreBytes != sizeof(PointerTy)) 00764 memset(Ptr, 0, StoreBytes); 00765 00766 *((PointerTy*)Ptr) = Val.PointerVal; 00767 break; 00768 default: 00769 cerr << "Cannot store value of type " << *Ty << "!\n"; 00770 } 00771 00772 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian()) 00773 // Host and target are different endian - reverse the stored bytes. 00774 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr); 00775 } 00776 00777 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 00778 /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 00779 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) { 00780 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 00781 uint8_t *Dst = (uint8_t *)IntVal.getRawData(); 00782 00783 if (sys::isLittleEndianHost()) 00784 // Little-endian host - the destination must be ordered from LSB to MSB. 00785 // The source is ordered from LSB to MSB: Do a straight copy. 00786 memcpy(Dst, Src, LoadBytes); 00787 else { 00788 // Big-endian - the destination is an array of 64 bit words ordered from 00789 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 00790 // ordered from MSB to LSB: Reverse the word order, but not the bytes in 00791 // a word. 00792 while (LoadBytes > sizeof(uint64_t)) { 00793 LoadBytes -= sizeof(uint64_t); 00794 // May not be aligned so use memcpy. 00795 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 00796 Dst += sizeof(uint64_t); 00797 } 00798 00799 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 00800 } 00801 } 00802 00803 /// FIXME: document 00804 /// 00805 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 00806 GenericValue *Ptr, 00807 const Type *Ty) { 00808 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty); 00809 00810 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian()) { 00811 // Host and target are different endian - reverse copy the stored 00812 // bytes into a buffer, and load from that. 00813 uint8_t *Src = (uint8_t*)Ptr; 00814 uint8_t *Buf = (uint8_t*)alloca(LoadBytes); 00815 std::reverse_copy(Src, Src + LoadBytes, Buf); 00816 Ptr = (GenericValue*)Buf; 00817 } 00818 00819 switch (Ty->getTypeID()) { 00820 case Type::IntegerTyID: 00821 // An APInt with all words initially zero. 00822 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0); 00823 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes); 00824 break; 00825 case Type::FloatTyID: 00826 Result.FloatVal = *((float*)Ptr); 00827 break; 00828 case Type::DoubleTyID: 00829 Result.DoubleVal = *((double*)Ptr); 00830 break; 00831 case Type::PointerTyID: 00832 Result.PointerVal = *((PointerTy*)Ptr); 00833 break; 00834 case Type::X86_FP80TyID: { 00835 // This is endian dependent, but it will only work on x86 anyway. 00836 // FIXME: Will not trap if loading a signaling NaN. 00837 uint16_t *p = (uint16_t*)Ptr; 00838 union { 00839 uint16_t x[8]; 00840 uint64_t y[2]; 00841 }; 00842 x[0] = p[1]; 00843 x[1] = p[2]; 00844 x[2] = p[3]; 00845 x[3] = p[4]; 00846 x[4] = p[0]; 00847 Result.IntVal = APInt(80, 2, y); 00848 break; 00849 } 00850 default: 00851 cerr << "Cannot load value of type " << *Ty << "!\n"; 00852 abort(); 00853 } 00854 } 00855 00856 // InitializeMemory - Recursive function to apply a Constant value into the 00857 // specified memory location... 00858 // 00859 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 00860 DOUT << "JIT: Initializing " << Addr << " "; 00861 DEBUG(Init->dump()); 00862 if (isa<UndefValue>(Init)) { 00863 return; 00864 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 00865 unsigned ElementSize = 00866 getTargetData()->getTypePaddedSize(CP->getType()->getElementType()); 00867 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 00868 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 00869 return; 00870 } else if (isa<ConstantAggregateZero>(Init)) { 00871 memset(Addr, 0, (size_t)getTargetData()->getTypePaddedSize(Init->getType())); 00872 return; 00873 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) { 00874 unsigned ElementSize = 00875 getTargetData()->getTypePaddedSize(CPA->getType()->getElementType()); 00876 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 00877 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 00878 return; 00879 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) { 00880 const StructLayout *SL = 00881 getTargetData()->getStructLayout(cast<StructType>(CPS->getType())); 00882 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 00883 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 00884 return; 00885 } else if (Init->getType()->isFirstClassType()) { 00886 GenericValue Val = getConstantValue(Init); 00887 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 00888 return; 00889 } 00890 00891 cerr << "Bad Type: " << *Init->getType() << "\n"; 00892 assert(0 && "Unknown constant type to initialize memory with!"); 00893 } 00894 00895 /// EmitGlobals - Emit all of the global variables to memory, storing their 00896 /// addresses into GlobalAddress. This must make sure to copy the contents of 00897 /// their initializers into the memory. 00898 /// 00899 void ExecutionEngine::emitGlobals() { 00900 00901 // Loop over all of the global variables in the program, allocating the memory 00902 // to hold them. If there is more than one module, do a prepass over globals 00903 // to figure out how the different modules should link together. 00904 // 00905 std::map<std::pair<std::string, const Type*>, 00906 const GlobalValue*> LinkedGlobalsMap; 00907 00908 if (Modules.size() != 1) { 00909 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 00910 Module &M = *Modules[m]->getModule(); 00911 for (Module::const_global_iterator I = M.global_begin(), 00912 E = M.global_end(); I != E; ++I) { 00913 const GlobalValue *GV = I; 00914 if (GV->hasLocalLinkage() || GV->isDeclaration() || 00915 GV->hasAppendingLinkage() || !GV->hasName()) 00916 continue;// Ignore external globals and globals with internal linkage. 00917 00918 const GlobalValue *&GVEntry = 00919 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 00920 00921 // If this is the first time we've seen this global, it is the canonical 00922 // version. 00923 if (!GVEntry) { 00924 GVEntry = GV; 00925 continue; 00926 } 00927 00928 // If the existing global is strong, never replace it. 00929 if (GVEntry->hasExternalLinkage() || 00930 GVEntry->hasDLLImportLinkage() || 00931 GVEntry->hasDLLExportLinkage()) 00932 continue; 00933 00934 // Otherwise, we know it's linkonce/weak, replace it if this is a strong 00935 // symbol. FIXME is this right for common? 00936 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 00937 GVEntry = GV; 00938 } 00939 } 00940 } 00941 00942 std::vector<const GlobalValue*> NonCanonicalGlobals; 00943 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 00944 Module &M = *Modules[m]->getModule(); 00945 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 00946 I != E; ++I) { 00947 // In the multi-module case, see what this global maps to. 00948 if (!LinkedGlobalsMap.empty()) { 00949 if (const GlobalValue *GVEntry = 00950 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) { 00951 // If something else is the canonical global, ignore this one. 00952 if (GVEntry != &*I) { 00953 NonCanonicalGlobals.push_back(I); 00954 continue; 00955 } 00956 } 00957 } 00958 00959 if (!I->isDeclaration()) { 00960 addGlobalMapping(I, getMemoryForGV(I)); 00961 } else { 00962 // External variable reference. Try to use the dynamic loader to 00963 // get a pointer to it. 00964 if (void *SymAddr = 00965 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str())) 00966 addGlobalMapping(I, SymAddr); 00967 else { 00968 cerr << "Could not resolve external global address: " 00969 << I->getName() << "\n"; 00970 abort(); 00971 } 00972 } 00973 } 00974 00975 // If there are multiple modules, map the non-canonical globals to their 00976 // canonical location. 00977 if (!NonCanonicalGlobals.empty()) { 00978 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 00979 const GlobalValue *GV = NonCanonicalGlobals[i]; 00980 const GlobalValue *CGV = 00981 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 00982 void *Ptr = getPointerToGlobalIfAvailable(CGV); 00983 assert(Ptr && "Canonical global wasn't codegen'd!"); 00984 addGlobalMapping(GV, Ptr); 00985 } 00986 } 00987 00988 // Now that all of the globals are set up in memory, loop through them all 00989 // and initialize their contents. 00990 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 00991 I != E; ++I) { 00992 if (!I->isDeclaration()) { 00993 if (!LinkedGlobalsMap.empty()) { 00994 if (const GlobalValue *GVEntry = 00995 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) 00996 if (GVEntry != &*I) // Not the canonical variable. 00997 continue; 00998 } 00999 EmitGlobalVariable(I); 01000 } 01001 } 01002 } 01003 } 01004 01005 // EmitGlobalVariable - This method emits the specified global variable to the 01006 // address specified in GlobalAddresses, or allocates new memory if it's not 01007 // already in the map. 01008 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 01009 void *GA = getPointerToGlobalIfAvailable(GV); 01010 01011 if (GA == 0) { 01012 // If it's not already specified, allocate memory for the global. 01013 GA = getMemoryForGV(GV); 01014 addGlobalMapping(GV, GA); 01015 } 01016 01017 // Don't initialize if it's thread local, let the client do it. 01018 if (!GV->isThreadLocal()) 01019 InitializeMemory(GV->getInitializer(), GA); 01020 01021 const Type *ElTy = GV->getType()->getElementType(); 01022 size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy); 01023 NumInitBytes += (unsigned)GVSize; 01024 ++NumGlobals; 01025 }