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/ExecutionEngine/ExecutionEngine.h" 00017 #include "llvm/ExecutionEngine/JITMemoryManager.h" 00018 #include "llvm/ADT/SmallString.h" 00019 #include "llvm/ADT/Statistic.h" 00020 #include "llvm/ExecutionEngine/GenericValue.h" 00021 #include "llvm/IR/Constants.h" 00022 #include "llvm/IR/DataLayout.h" 00023 #include "llvm/IR/DerivedTypes.h" 00024 #include "llvm/IR/Module.h" 00025 #include "llvm/IR/Operator.h" 00026 #include "llvm/Support/Debug.h" 00027 #include "llvm/Support/DynamicLibrary.h" 00028 #include "llvm/Support/ErrorHandling.h" 00029 #include "llvm/Support/Host.h" 00030 #include "llvm/Support/MutexGuard.h" 00031 #include "llvm/Support/TargetRegistry.h" 00032 #include "llvm/Support/ValueHandle.h" 00033 #include "llvm/Support/raw_ostream.h" 00034 #include "llvm/Target/TargetMachine.h" 00035 #include <cmath> 00036 #include <cstring> 00037 using namespace llvm; 00038 00039 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 00040 STATISTIC(NumGlobals , "Number of global vars initialized"); 00041 00042 ExecutionEngine *(*ExecutionEngine::JITCtor)( 00043 Module *M, 00044 std::string *ErrorStr, 00045 JITMemoryManager *JMM, 00046 bool GVsWithCode, 00047 TargetMachine *TM) = 0; 00048 ExecutionEngine *(*ExecutionEngine::MCJITCtor)( 00049 Module *M, 00050 std::string *ErrorStr, 00051 RTDyldMemoryManager *MCJMM, 00052 bool GVsWithCode, 00053 TargetMachine *TM) = 0; 00054 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M, 00055 std::string *ErrorStr) = 0; 00056 00057 ExecutionEngine::ExecutionEngine(Module *M) 00058 : EEState(*this), 00059 LazyFunctionCreator(0), 00060 ExceptionTableRegister(0), 00061 ExceptionTableDeregister(0) { 00062 CompilingLazily = false; 00063 GVCompilationDisabled = false; 00064 SymbolSearchingDisabled = false; 00065 Modules.push_back(M); 00066 assert(M && "Module is null?"); 00067 } 00068 00069 ExecutionEngine::~ExecutionEngine() { 00070 clearAllGlobalMappings(); 00071 for (unsigned i = 0, e = Modules.size(); i != e; ++i) 00072 delete Modules[i]; 00073 } 00074 00075 void ExecutionEngine::DeregisterAllTables() { 00076 if (ExceptionTableDeregister) { 00077 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin(); 00078 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end(); 00079 for (; it != ite; ++it) 00080 ExceptionTableDeregister(it->second); 00081 AllExceptionTables.clear(); 00082 } 00083 } 00084 00085 namespace { 00086 /// \brief Helper class which uses a value handler to automatically deletes the 00087 /// memory block when the GlobalVariable is destroyed. 00088 class GVMemoryBlock : public CallbackVH { 00089 GVMemoryBlock(const GlobalVariable *GV) 00090 : CallbackVH(const_cast<GlobalVariable*>(GV)) {} 00091 00092 public: 00093 /// \brief Returns the address the GlobalVariable should be written into. The 00094 /// GVMemoryBlock object prefixes that. 00095 static char *Create(const GlobalVariable *GV, const DataLayout& TD) { 00096 Type *ElTy = GV->getType()->getElementType(); 00097 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy); 00098 void *RawMemory = ::operator new( 00099 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock), 00100 TD.getPreferredAlignment(GV)) 00101 + GVSize); 00102 new(RawMemory) GVMemoryBlock(GV); 00103 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock); 00104 } 00105 00106 virtual void deleted() { 00107 // We allocated with operator new and with some extra memory hanging off the 00108 // end, so don't just delete this. I'm not sure if this is actually 00109 // required. 00110 this->~GVMemoryBlock(); 00111 ::operator delete(this); 00112 } 00113 }; 00114 } // anonymous namespace 00115 00116 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) { 00117 return GVMemoryBlock::Create(GV, *getDataLayout()); 00118 } 00119 00120 bool ExecutionEngine::removeModule(Module *M) { 00121 for(SmallVector<Module *, 1>::iterator I = Modules.begin(), 00122 E = Modules.end(); I != E; ++I) { 00123 Module *Found = *I; 00124 if (Found == M) { 00125 Modules.erase(I); 00126 clearGlobalMappingsFromModule(M); 00127 return true; 00128 } 00129 } 00130 return false; 00131 } 00132 00133 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 00134 for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 00135 if (Function *F = Modules[i]->getFunction(FnName)) 00136 return F; 00137 } 00138 return 0; 00139 } 00140 00141 00142 void *ExecutionEngineState::RemoveMapping(const MutexGuard &, 00143 const GlobalValue *ToUnmap) { 00144 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap); 00145 void *OldVal; 00146 00147 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the 00148 // GlobalAddressMap. 00149 if (I == GlobalAddressMap.end()) 00150 OldVal = 0; 00151 else { 00152 OldVal = I->second; 00153 GlobalAddressMap.erase(I); 00154 } 00155 00156 GlobalAddressReverseMap.erase(OldVal); 00157 return OldVal; 00158 } 00159 00160 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 00161 MutexGuard locked(lock); 00162 00163 DEBUG(dbgs() << "JIT: Map \'" << GV->getName() 00164 << "\' to [" << Addr << "]\n";); 00165 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV]; 00166 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!"); 00167 CurVal = Addr; 00168 00169 // If we are using the reverse mapping, add it too. 00170 if (!EEState.getGlobalAddressReverseMap(locked).empty()) { 00171 AssertingVH<const GlobalValue> &V = 00172 EEState.getGlobalAddressReverseMap(locked)[Addr]; 00173 assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 00174 V = GV; 00175 } 00176 } 00177 00178 void ExecutionEngine::clearAllGlobalMappings() { 00179 MutexGuard locked(lock); 00180 00181 EEState.getGlobalAddressMap(locked).clear(); 00182 EEState.getGlobalAddressReverseMap(locked).clear(); 00183 } 00184 00185 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) { 00186 MutexGuard locked(lock); 00187 00188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) 00189 EEState.RemoveMapping(locked, FI); 00190 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 00191 GI != GE; ++GI) 00192 EEState.RemoveMapping(locked, GI); 00193 } 00194 00195 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 00196 MutexGuard locked(lock); 00197 00198 ExecutionEngineState::GlobalAddressMapTy &Map = 00199 EEState.getGlobalAddressMap(locked); 00200 00201 // Deleting from the mapping? 00202 if (Addr == 0) 00203 return EEState.RemoveMapping(locked, GV); 00204 00205 void *&CurVal = Map[GV]; 00206 void *OldVal = CurVal; 00207 00208 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty()) 00209 EEState.getGlobalAddressReverseMap(locked).erase(CurVal); 00210 CurVal = Addr; 00211 00212 // If we are using the reverse mapping, add it too. 00213 if (!EEState.getGlobalAddressReverseMap(locked).empty()) { 00214 AssertingVH<const GlobalValue> &V = 00215 EEState.getGlobalAddressReverseMap(locked)[Addr]; 00216 assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 00217 V = GV; 00218 } 00219 return OldVal; 00220 } 00221 00222 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 00223 MutexGuard locked(lock); 00224 00225 ExecutionEngineState::GlobalAddressMapTy::iterator I = 00226 EEState.getGlobalAddressMap(locked).find(GV); 00227 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0; 00228 } 00229 00230 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 00231 MutexGuard locked(lock); 00232 00233 // If we haven't computed the reverse mapping yet, do so first. 00234 if (EEState.getGlobalAddressReverseMap(locked).empty()) { 00235 for (ExecutionEngineState::GlobalAddressMapTy::iterator 00236 I = EEState.getGlobalAddressMap(locked).begin(), 00237 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I) 00238 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair( 00239 I->second, I->first)); 00240 } 00241 00242 std::map<void *, AssertingVH<const GlobalValue> >::iterator I = 00243 EEState.getGlobalAddressReverseMap(locked).find(Addr); 00244 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0; 00245 } 00246 00247 namespace { 00248 class ArgvArray { 00249 char *Array; 00250 std::vector<char*> Values; 00251 public: 00252 ArgvArray() : Array(NULL) {} 00253 ~ArgvArray() { clear(); } 00254 void clear() { 00255 delete[] Array; 00256 Array = NULL; 00257 for (size_t I = 0, E = Values.size(); I != E; ++I) { 00258 delete[] Values[I]; 00259 } 00260 Values.clear(); 00261 } 00262 /// Turn a vector of strings into a nice argv style array of pointers to null 00263 /// terminated strings. 00264 void *reset(LLVMContext &C, ExecutionEngine *EE, 00265 const std::vector<std::string> &InputArgv); 00266 }; 00267 } // anonymous namespace 00268 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE, 00269 const std::vector<std::string> &InputArgv) { 00270 clear(); // Free the old contents. 00271 unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 00272 Array = new char[(InputArgv.size()+1)*PtrSize]; 00273 00274 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n"); 00275 Type *SBytePtr = Type::getInt8PtrTy(C); 00276 00277 for (unsigned i = 0; i != InputArgv.size(); ++i) { 00278 unsigned Size = InputArgv[i].size()+1; 00279 char *Dest = new char[Size]; 00280 Values.push_back(Dest); 00281 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n"); 00282 00283 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 00284 Dest[Size-1] = 0; 00285 00286 // Endian safe: Array[i] = (PointerTy)Dest; 00287 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize), 00288 SBytePtr); 00289 } 00290 00291 // Null terminate it 00292 EE->StoreValueToMemory(PTOGV(0), 00293 (GenericValue*)(Array+InputArgv.size()*PtrSize), 00294 SBytePtr); 00295 return Array; 00296 } 00297 00298 void ExecutionEngine::runStaticConstructorsDestructors(Module *module, 00299 bool isDtors) { 00300 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 00301 GlobalVariable *GV = module->getNamedGlobal(Name); 00302 00303 // If this global has internal linkage, or if it has a use, then it must be 00304 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 00305 // this is the case, don't execute any of the global ctors, __main will do 00306 // it. 00307 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return; 00308 00309 // Should be an array of '{ i32, void ()* }' structs. The first value is 00310 // the init priority, which we ignore. 00311 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 00312 if (InitList == 0) 00313 return; 00314 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 00315 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i)); 00316 if (CS == 0) continue; 00317 00318 Constant *FP = CS->getOperand(1); 00319 if (FP->isNullValue()) 00320 continue; // Found a sentinal value, ignore. 00321 00322 // Strip off constant expression casts. 00323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 00324 if (CE->isCast()) 00325 FP = CE->getOperand(0); 00326 00327 // Execute the ctor/dtor function! 00328 if (Function *F = dyn_cast<Function>(FP)) 00329 runFunction(F, std::vector<GenericValue>()); 00330 00331 // FIXME: It is marginally lame that we just do nothing here if we see an 00332 // entry we don't recognize. It might not be unreasonable for the verifier 00333 // to not even allow this and just assert here. 00334 } 00335 } 00336 00337 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 00338 // Execute global ctors/dtors for each module in the program. 00339 for (unsigned i = 0, e = Modules.size(); i != e; ++i) 00340 runStaticConstructorsDestructors(Modules[i], isDtors); 00341 } 00342 00343 #ifndef NDEBUG 00344 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null. 00345 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) { 00346 unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 00347 for (unsigned i = 0; i < PtrSize; ++i) 00348 if (*(i + (uint8_t*)Loc)) 00349 return false; 00350 return true; 00351 } 00352 #endif 00353 00354 int ExecutionEngine::runFunctionAsMain(Function *Fn, 00355 const std::vector<std::string> &argv, 00356 const char * const * envp) { 00357 std::vector<GenericValue> GVArgs; 00358 GenericValue GVArgc; 00359 GVArgc.IntVal = APInt(32, argv.size()); 00360 00361 // Check main() type 00362 unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 00363 FunctionType *FTy = Fn->getFunctionType(); 00364 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo(); 00365 00366 // Check the argument types. 00367 if (NumArgs > 3) 00368 report_fatal_error("Invalid number of arguments of main() supplied"); 00369 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty) 00370 report_fatal_error("Invalid type for third argument of main() supplied"); 00371 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty) 00372 report_fatal_error("Invalid type for second argument of main() supplied"); 00373 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32)) 00374 report_fatal_error("Invalid type for first argument of main() supplied"); 00375 if (!FTy->getReturnType()->isIntegerTy() && 00376 !FTy->getReturnType()->isVoidTy()) 00377 report_fatal_error("Invalid return type of main() supplied"); 00378 00379 ArgvArray CArgv; 00380 ArgvArray CEnv; 00381 if (NumArgs) { 00382 GVArgs.push_back(GVArgc); // Arg #0 = argc. 00383 if (NumArgs > 1) { 00384 // Arg #1 = argv. 00385 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv))); 00386 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) && 00387 "argv[0] was null after CreateArgv"); 00388 if (NumArgs > 2) { 00389 std::vector<std::string> EnvVars; 00390 for (unsigned i = 0; envp[i]; ++i) 00391 EnvVars.push_back(envp[i]); 00392 // Arg #2 = envp. 00393 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars))); 00394 } 00395 } 00396 } 00397 00398 return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 00399 } 00400 00401 ExecutionEngine *ExecutionEngine::create(Module *M, 00402 bool ForceInterpreter, 00403 std::string *ErrorStr, 00404 CodeGenOpt::Level OptLevel, 00405 bool GVsWithCode) { 00406 EngineBuilder EB = EngineBuilder(M) 00407 .setEngineKind(ForceInterpreter 00408 ? EngineKind::Interpreter 00409 : EngineKind::JIT) 00410 .setErrorStr(ErrorStr) 00411 .setOptLevel(OptLevel) 00412 .setAllocateGVsWithCode(GVsWithCode); 00413 00414 return EB.create(); 00415 } 00416 00417 /// createJIT - This is the factory method for creating a JIT for the current 00418 /// machine, it does not fall back to the interpreter. This takes ownership 00419 /// of the module. 00420 ExecutionEngine *ExecutionEngine::createJIT(Module *M, 00421 std::string *ErrorStr, 00422 JITMemoryManager *JMM, 00423 CodeGenOpt::Level OL, 00424 bool GVsWithCode, 00425 Reloc::Model RM, 00426 CodeModel::Model CMM) { 00427 if (ExecutionEngine::JITCtor == 0) { 00428 if (ErrorStr) 00429 *ErrorStr = "JIT has not been linked in."; 00430 return 0; 00431 } 00432 00433 // Use the defaults for extra parameters. Users can use EngineBuilder to 00434 // set them. 00435 EngineBuilder EB(M); 00436 EB.setEngineKind(EngineKind::JIT); 00437 EB.setErrorStr(ErrorStr); 00438 EB.setRelocationModel(RM); 00439 EB.setCodeModel(CMM); 00440 EB.setAllocateGVsWithCode(GVsWithCode); 00441 EB.setOptLevel(OL); 00442 EB.setJITMemoryManager(JMM); 00443 00444 // TODO: permit custom TargetOptions here 00445 TargetMachine *TM = EB.selectTarget(); 00446 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0; 00447 00448 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM); 00449 } 00450 00451 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) { 00452 OwningPtr<TargetMachine> TheTM(TM); // Take ownership. 00453 00454 // Make sure we can resolve symbols in the program as well. The zero arg 00455 // to the function tells DynamicLibrary to load the program, not a library. 00456 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) 00457 return 0; 00458 00459 assert(!(JMM && MCJMM)); 00460 00461 // If the user specified a memory manager but didn't specify which engine to 00462 // create, we assume they only want the JIT, and we fail if they only want 00463 // the interpreter. 00464 if (JMM || MCJMM) { 00465 if (WhichEngine & EngineKind::JIT) 00466 WhichEngine = EngineKind::JIT; 00467 else { 00468 if (ErrorStr) 00469 *ErrorStr = "Cannot create an interpreter with a memory manager."; 00470 return 0; 00471 } 00472 } 00473 00474 if (MCJMM && ! UseMCJIT) { 00475 if (ErrorStr) 00476 *ErrorStr = 00477 "Cannot create a legacy JIT with a runtime dyld memory " 00478 "manager."; 00479 return 0; 00480 } 00481 00482 // Unless the interpreter was explicitly selected or the JIT is not linked, 00483 // try making a JIT. 00484 if ((WhichEngine & EngineKind::JIT) && TheTM) { 00485 Triple TT(M->getTargetTriple()); 00486 if (!TM->getTarget().hasJIT()) { 00487 errs() << "WARNING: This target JIT is not designed for the host" 00488 << " you are running. If bad things happen, please choose" 00489 << " a different -march switch.\n"; 00490 } 00491 00492 if (UseMCJIT && ExecutionEngine::MCJITCtor) { 00493 ExecutionEngine *EE = 00494 ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM, 00495 AllocateGVsWithCode, TheTM.take()); 00496 if (EE) return EE; 00497 } else if (ExecutionEngine::JITCtor) { 00498 ExecutionEngine *EE = 00499 ExecutionEngine::JITCtor(M, ErrorStr, JMM, 00500 AllocateGVsWithCode, TheTM.take()); 00501 if (EE) return EE; 00502 } 00503 } 00504 00505 // If we can't make a JIT and we didn't request one specifically, try making 00506 // an interpreter instead. 00507 if (WhichEngine & EngineKind::Interpreter) { 00508 if (ExecutionEngine::InterpCtor) 00509 return ExecutionEngine::InterpCtor(M, ErrorStr); 00510 if (ErrorStr) 00511 *ErrorStr = "Interpreter has not been linked in."; 00512 return 0; 00513 } 00514 00515 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 && 00516 ExecutionEngine::MCJITCtor == 0) { 00517 if (ErrorStr) 00518 *ErrorStr = "JIT has not been linked in."; 00519 } 00520 00521 return 0; 00522 } 00523 00524 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 00525 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 00526 return getPointerToFunction(F); 00527 00528 MutexGuard locked(lock); 00529 if (void *P = EEState.getGlobalAddressMap(locked)[GV]) 00530 return P; 00531 00532 // Global variable might have been added since interpreter started. 00533 if (GlobalVariable *GVar = 00534 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 00535 EmitGlobalVariable(GVar); 00536 else 00537 llvm_unreachable("Global hasn't had an address allocated yet!"); 00538 00539 return EEState.getGlobalAddressMap(locked)[GV]; 00540 } 00541 00542 /// \brief Converts a Constant* into a GenericValue, including handling of 00543 /// ConstantExpr values. 00544 GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 00545 // If its undefined, return the garbage. 00546 if (isa<UndefValue>(C)) { 00547 GenericValue Result; 00548 switch (C->getType()->getTypeID()) { 00549 default: 00550 break; 00551 case Type::IntegerTyID: 00552 case Type::X86_FP80TyID: 00553 case Type::FP128TyID: 00554 case Type::PPC_FP128TyID: 00555 // Although the value is undefined, we still have to construct an APInt 00556 // with the correct bit width. 00557 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0); 00558 break; 00559 case Type::VectorTyID: 00560 // if the whole vector is 'undef' just reserve memory for the value. 00561 const VectorType* VTy = dyn_cast<VectorType>(C->getType()); 00562 const Type *ElemTy = VTy->getElementType(); 00563 unsigned int elemNum = VTy->getNumElements(); 00564 Result.AggregateVal.resize(elemNum); 00565 if (ElemTy->isIntegerTy()) 00566 for (unsigned int i = 0; i < elemNum; ++i) 00567 Result.AggregateVal[i].IntVal = 00568 APInt(ElemTy->getPrimitiveSizeInBits(), 0); 00569 break; 00570 } 00571 return Result; 00572 } 00573 00574 // Otherwise, if the value is a ConstantExpr... 00575 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 00576 Constant *Op0 = CE->getOperand(0); 00577 switch (CE->getOpcode()) { 00578 case Instruction::GetElementPtr: { 00579 // Compute the index 00580 GenericValue Result = getConstantValue(Op0); 00581 APInt Offset(TD->getPointerSizeInBits(), 0); 00582 cast<GEPOperator>(CE)->accumulateConstantOffset(*TD, Offset); 00583 00584 char* tmp = (char*) Result.PointerVal; 00585 Result = PTOGV(tmp + Offset.getSExtValue()); 00586 return Result; 00587 } 00588 case Instruction::Trunc: { 00589 GenericValue GV = getConstantValue(Op0); 00590 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 00591 GV.IntVal = GV.IntVal.trunc(BitWidth); 00592 return GV; 00593 } 00594 case Instruction::ZExt: { 00595 GenericValue GV = getConstantValue(Op0); 00596 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 00597 GV.IntVal = GV.IntVal.zext(BitWidth); 00598 return GV; 00599 } 00600 case Instruction::SExt: { 00601 GenericValue GV = getConstantValue(Op0); 00602 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 00603 GV.IntVal = GV.IntVal.sext(BitWidth); 00604 return GV; 00605 } 00606 case Instruction::FPTrunc: { 00607 // FIXME long double 00608 GenericValue GV = getConstantValue(Op0); 00609 GV.FloatVal = float(GV.DoubleVal); 00610 return GV; 00611 } 00612 case Instruction::FPExt:{ 00613 // FIXME long double 00614 GenericValue GV = getConstantValue(Op0); 00615 GV.DoubleVal = double(GV.FloatVal); 00616 return GV; 00617 } 00618 case Instruction::UIToFP: { 00619 GenericValue GV = getConstantValue(Op0); 00620 if (CE->getType()->isFloatTy()) 00621 GV.FloatVal = float(GV.IntVal.roundToDouble()); 00622 else if (CE->getType()->isDoubleTy()) 00623 GV.DoubleVal = GV.IntVal.roundToDouble(); 00624 else if (CE->getType()->isX86_FP80Ty()) { 00625 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 00626 (void)apf.convertFromAPInt(GV.IntVal, 00627 false, 00628 APFloat::rmNearestTiesToEven); 00629 GV.IntVal = apf.bitcastToAPInt(); 00630 } 00631 return GV; 00632 } 00633 case Instruction::SIToFP: { 00634 GenericValue GV = getConstantValue(Op0); 00635 if (CE->getType()->isFloatTy()) 00636 GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 00637 else if (CE->getType()->isDoubleTy()) 00638 GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 00639 else if (CE->getType()->isX86_FP80Ty()) { 00640 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 00641 (void)apf.convertFromAPInt(GV.IntVal, 00642 true, 00643 APFloat::rmNearestTiesToEven); 00644 GV.IntVal = apf.bitcastToAPInt(); 00645 } 00646 return GV; 00647 } 00648 case Instruction::FPToUI: // double->APInt conversion handles sign 00649 case Instruction::FPToSI: { 00650 GenericValue GV = getConstantValue(Op0); 00651 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 00652 if (Op0->getType()->isFloatTy()) 00653 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 00654 else if (Op0->getType()->isDoubleTy()) 00655 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 00656 else if (Op0->getType()->isX86_FP80Ty()) { 00657 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal); 00658 uint64_t v; 00659 bool ignored; 00660 (void)apf.convertToInteger(&v, BitWidth, 00661 CE->getOpcode()==Instruction::FPToSI, 00662 APFloat::rmTowardZero, &ignored); 00663 GV.IntVal = v; // endian? 00664 } 00665 return GV; 00666 } 00667 case Instruction::PtrToInt: { 00668 GenericValue GV = getConstantValue(Op0); 00669 uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType()); 00670 assert(PtrWidth <= 64 && "Bad pointer width"); 00671 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 00672 uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType()); 00673 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth); 00674 return GV; 00675 } 00676 case Instruction::IntToPtr: { 00677 GenericValue GV = getConstantValue(Op0); 00678 uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType()); 00679 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 00680 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 00681 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 00682 return GV; 00683 } 00684 case Instruction::BitCast: { 00685 GenericValue GV = getConstantValue(Op0); 00686 Type* DestTy = CE->getType(); 00687 switch (Op0->getType()->getTypeID()) { 00688 default: llvm_unreachable("Invalid bitcast operand"); 00689 case Type::IntegerTyID: 00690 assert(DestTy->isFloatingPointTy() && "invalid bitcast"); 00691 if (DestTy->isFloatTy()) 00692 GV.FloatVal = GV.IntVal.bitsToFloat(); 00693 else if (DestTy->isDoubleTy()) 00694 GV.DoubleVal = GV.IntVal.bitsToDouble(); 00695 break; 00696 case Type::FloatTyID: 00697 assert(DestTy->isIntegerTy(32) && "Invalid bitcast"); 00698 GV.IntVal = APInt::floatToBits(GV.FloatVal); 00699 break; 00700 case Type::DoubleTyID: 00701 assert(DestTy->isIntegerTy(64) && "Invalid bitcast"); 00702 GV.IntVal = APInt::doubleToBits(GV.DoubleVal); 00703 break; 00704 case Type::PointerTyID: 00705 assert(DestTy->isPointerTy() && "Invalid bitcast"); 00706 break; // getConstantValue(Op0) above already converted it 00707 } 00708 return GV; 00709 } 00710 case Instruction::Add: 00711 case Instruction::FAdd: 00712 case Instruction::Sub: 00713 case Instruction::FSub: 00714 case Instruction::Mul: 00715 case Instruction::FMul: 00716 case Instruction::UDiv: 00717 case Instruction::SDiv: 00718 case Instruction::URem: 00719 case Instruction::SRem: 00720 case Instruction::And: 00721 case Instruction::Or: 00722 case Instruction::Xor: { 00723 GenericValue LHS = getConstantValue(Op0); 00724 GenericValue RHS = getConstantValue(CE->getOperand(1)); 00725 GenericValue GV; 00726 switch (CE->getOperand(0)->getType()->getTypeID()) { 00727 default: llvm_unreachable("Bad add type!"); 00728 case Type::IntegerTyID: 00729 switch (CE->getOpcode()) { 00730 default: llvm_unreachable("Invalid integer opcode"); 00731 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 00732 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 00733 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 00734 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 00735 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 00736 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 00737 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 00738 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 00739 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 00740 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 00741 } 00742 break; 00743 case Type::FloatTyID: 00744 switch (CE->getOpcode()) { 00745 default: llvm_unreachable("Invalid float opcode"); 00746 case Instruction::FAdd: 00747 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 00748 case Instruction::FSub: 00749 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 00750 case Instruction::FMul: 00751 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 00752 case Instruction::FDiv: 00753 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 00754 case Instruction::FRem: 00755 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break; 00756 } 00757 break; 00758 case Type::DoubleTyID: 00759 switch (CE->getOpcode()) { 00760 default: llvm_unreachable("Invalid double opcode"); 00761 case Instruction::FAdd: 00762 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 00763 case Instruction::FSub: 00764 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 00765 case Instruction::FMul: 00766 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 00767 case Instruction::FDiv: 00768 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 00769 case Instruction::FRem: 00770 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 00771 } 00772 break; 00773 case Type::X86_FP80TyID: 00774 case Type::PPC_FP128TyID: 00775 case Type::FP128TyID: { 00776 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics(); 00777 APFloat apfLHS = APFloat(Sem, LHS.IntVal); 00778 switch (CE->getOpcode()) { 00779 default: llvm_unreachable("Invalid long double opcode"); 00780 case Instruction::FAdd: 00781 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven); 00782 GV.IntVal = apfLHS.bitcastToAPInt(); 00783 break; 00784 case Instruction::FSub: 00785 apfLHS.subtract(APFloat(Sem, RHS.IntVal), 00786 APFloat::rmNearestTiesToEven); 00787 GV.IntVal = apfLHS.bitcastToAPInt(); 00788 break; 00789 case Instruction::FMul: 00790 apfLHS.multiply(APFloat(Sem, RHS.IntVal), 00791 APFloat::rmNearestTiesToEven); 00792 GV.IntVal = apfLHS.bitcastToAPInt(); 00793 break; 00794 case Instruction::FDiv: 00795 apfLHS.divide(APFloat(Sem, RHS.IntVal), 00796 APFloat::rmNearestTiesToEven); 00797 GV.IntVal = apfLHS.bitcastToAPInt(); 00798 break; 00799 case Instruction::FRem: 00800 apfLHS.mod(APFloat(Sem, RHS.IntVal), 00801 APFloat::rmNearestTiesToEven); 00802 GV.IntVal = apfLHS.bitcastToAPInt(); 00803 break; 00804 } 00805 } 00806 break; 00807 } 00808 return GV; 00809 } 00810 default: 00811 break; 00812 } 00813 00814 SmallString<256> Msg; 00815 raw_svector_ostream OS(Msg); 00816 OS << "ConstantExpr not handled: " << *CE; 00817 report_fatal_error(OS.str()); 00818 } 00819 00820 // Otherwise, we have a simple constant. 00821 GenericValue Result; 00822 switch (C->getType()->getTypeID()) { 00823 case Type::FloatTyID: 00824 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 00825 break; 00826 case Type::DoubleTyID: 00827 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 00828 break; 00829 case Type::X86_FP80TyID: 00830 case Type::FP128TyID: 00831 case Type::PPC_FP128TyID: 00832 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt(); 00833 break; 00834 case Type::IntegerTyID: 00835 Result.IntVal = cast<ConstantInt>(C)->getValue(); 00836 break; 00837 case Type::PointerTyID: 00838 if (isa<ConstantPointerNull>(C)) 00839 Result.PointerVal = 0; 00840 else if (const Function *F = dyn_cast<Function>(C)) 00841 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 00842 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) 00843 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 00844 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 00845 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>( 00846 BA->getBasicBlock()))); 00847 else 00848 llvm_unreachable("Unknown constant pointer type!"); 00849 break; 00850 case Type::VectorTyID: { 00851 unsigned elemNum; 00852 Type* ElemTy; 00853 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C); 00854 const ConstantVector *CV = dyn_cast<ConstantVector>(C); 00855 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C); 00856 00857 if (CDV) { 00858 elemNum = CDV->getNumElements(); 00859 ElemTy = CDV->getElementType(); 00860 } else if (CV || CAZ) { 00861 VectorType* VTy = dyn_cast<VectorType>(C->getType()); 00862 elemNum = VTy->getNumElements(); 00863 ElemTy = VTy->getElementType(); 00864 } else { 00865 llvm_unreachable("Unknown constant vector type!"); 00866 } 00867 00868 Result.AggregateVal.resize(elemNum); 00869 // Check if vector holds floats. 00870 if(ElemTy->isFloatTy()) { 00871 if (CAZ) { 00872 GenericValue floatZero; 00873 floatZero.FloatVal = 0.f; 00874 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 00875 floatZero); 00876 break; 00877 } 00878 if(CV) { 00879 for (unsigned i = 0; i < elemNum; ++i) 00880 if (!isa<UndefValue>(CV->getOperand(i))) 00881 Result.AggregateVal[i].FloatVal = cast<ConstantFP>( 00882 CV->getOperand(i))->getValueAPF().convertToFloat(); 00883 break; 00884 } 00885 if(CDV) 00886 for (unsigned i = 0; i < elemNum; ++i) 00887 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i); 00888 00889 break; 00890 } 00891 // Check if vector holds doubles. 00892 if (ElemTy->isDoubleTy()) { 00893 if (CAZ) { 00894 GenericValue doubleZero; 00895 doubleZero.DoubleVal = 0.0; 00896 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 00897 doubleZero); 00898 break; 00899 } 00900 if(CV) { 00901 for (unsigned i = 0; i < elemNum; ++i) 00902 if (!isa<UndefValue>(CV->getOperand(i))) 00903 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>( 00904 CV->getOperand(i))->getValueAPF().convertToDouble(); 00905 break; 00906 } 00907 if(CDV) 00908 for (unsigned i = 0; i < elemNum; ++i) 00909 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i); 00910 00911 break; 00912 } 00913 // Check if vector holds integers. 00914 if (ElemTy->isIntegerTy()) { 00915 if (CAZ) { 00916 GenericValue intZero; 00917 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull); 00918 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 00919 intZero); 00920 break; 00921 } 00922 if(CV) { 00923 for (unsigned i = 0; i < elemNum; ++i) 00924 if (!isa<UndefValue>(CV->getOperand(i))) 00925 Result.AggregateVal[i].IntVal = cast<ConstantInt>( 00926 CV->getOperand(i))->getValue(); 00927 else { 00928 Result.AggregateVal[i].IntVal = 00929 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0); 00930 } 00931 break; 00932 } 00933 if(CDV) 00934 for (unsigned i = 0; i < elemNum; ++i) 00935 Result.AggregateVal[i].IntVal = APInt( 00936 CDV->getElementType()->getPrimitiveSizeInBits(), 00937 CDV->getElementAsInteger(i)); 00938 00939 break; 00940 } 00941 llvm_unreachable("Unknown constant pointer type!"); 00942 } 00943 break; 00944 00945 default: 00946 SmallString<256> Msg; 00947 raw_svector_ostream OS(Msg); 00948 OS << "ERROR: Constant unimplemented for type: " << *C->getType(); 00949 report_fatal_error(OS.str()); 00950 } 00951 00952 return Result; 00953 } 00954 00955 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 00956 /// with the integer held in IntVal. 00957 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 00958 unsigned StoreBytes) { 00959 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 00960 const uint8_t *Src = (const uint8_t *)IntVal.getRawData(); 00961 00962 if (sys::IsLittleEndianHost) { 00963 // Little-endian host - the source is ordered from LSB to MSB. Order the 00964 // destination from LSB to MSB: Do a straight copy. 00965 memcpy(Dst, Src, StoreBytes); 00966 } else { 00967 // Big-endian host - the source is an array of 64 bit words ordered from 00968 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 00969 // from MSB to LSB: Reverse the word order, but not the bytes in a word. 00970 while (StoreBytes > sizeof(uint64_t)) { 00971 StoreBytes -= sizeof(uint64_t); 00972 // May not be aligned so use memcpy. 00973 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 00974 Src += sizeof(uint64_t); 00975 } 00976 00977 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 00978 } 00979 } 00980 00981 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, 00982 GenericValue *Ptr, Type *Ty) { 00983 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty); 00984 00985 switch (Ty->getTypeID()) { 00986 default: 00987 dbgs() << "Cannot store value of type " << *Ty << "!\n"; 00988 break; 00989 case Type::IntegerTyID: 00990 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes); 00991 break; 00992 case Type::FloatTyID: 00993 *((float*)Ptr) = Val.FloatVal; 00994 break; 00995 case Type::DoubleTyID: 00996 *((double*)Ptr) = Val.DoubleVal; 00997 break; 00998 case Type::X86_FP80TyID: 00999 memcpy(Ptr, Val.IntVal.getRawData(), 10); 01000 break; 01001 case Type::PointerTyID: 01002 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts. 01003 if (StoreBytes != sizeof(PointerTy)) 01004 memset(&(Ptr->PointerVal), 0, StoreBytes); 01005 01006 *((PointerTy*)Ptr) = Val.PointerVal; 01007 break; 01008 case Type::VectorTyID: 01009 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) { 01010 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy()) 01011 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal; 01012 if (cast<VectorType>(Ty)->getElementType()->isFloatTy()) 01013 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal; 01014 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) { 01015 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8; 01016 StoreIntToMemory(Val.AggregateVal[i].IntVal, 01017 (uint8_t*)Ptr + numOfBytes*i, numOfBytes); 01018 } 01019 } 01020 break; 01021 } 01022 01023 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian()) 01024 // Host and target are different endian - reverse the stored bytes. 01025 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr); 01026 } 01027 01028 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 01029 /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 01030 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) { 01031 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 01032 uint8_t *Dst = reinterpret_cast<uint8_t *>( 01033 const_cast<uint64_t *>(IntVal.getRawData())); 01034 01035 if (sys::IsLittleEndianHost) 01036 // Little-endian host - the destination must be ordered from LSB to MSB. 01037 // The source is ordered from LSB to MSB: Do a straight copy. 01038 memcpy(Dst, Src, LoadBytes); 01039 else { 01040 // Big-endian - the destination is an array of 64 bit words ordered from 01041 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 01042 // ordered from MSB to LSB: Reverse the word order, but not the bytes in 01043 // a word. 01044 while (LoadBytes > sizeof(uint64_t)) { 01045 LoadBytes -= sizeof(uint64_t); 01046 // May not be aligned so use memcpy. 01047 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 01048 Dst += sizeof(uint64_t); 01049 } 01050 01051 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 01052 } 01053 } 01054 01055 /// FIXME: document 01056 /// 01057 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 01058 GenericValue *Ptr, 01059 Type *Ty) { 01060 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty); 01061 01062 switch (Ty->getTypeID()) { 01063 case Type::IntegerTyID: 01064 // An APInt with all words initially zero. 01065 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0); 01066 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes); 01067 break; 01068 case Type::FloatTyID: 01069 Result.FloatVal = *((float*)Ptr); 01070 break; 01071 case Type::DoubleTyID: 01072 Result.DoubleVal = *((double*)Ptr); 01073 break; 01074 case Type::PointerTyID: 01075 Result.PointerVal = *((PointerTy*)Ptr); 01076 break; 01077 case Type::X86_FP80TyID: { 01078 // This is endian dependent, but it will only work on x86 anyway. 01079 // FIXME: Will not trap if loading a signaling NaN. 01080 uint64_t y[2]; 01081 memcpy(y, Ptr, 10); 01082 Result.IntVal = APInt(80, y); 01083 break; 01084 } 01085 case Type::VectorTyID: { 01086 const VectorType *VT = cast<VectorType>(Ty); 01087 const Type *ElemT = VT->getElementType(); 01088 const unsigned numElems = VT->getNumElements(); 01089 if (ElemT->isFloatTy()) { 01090 Result.AggregateVal.resize(numElems); 01091 for (unsigned i = 0; i < numElems; ++i) 01092 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i); 01093 } 01094 if (ElemT->isDoubleTy()) { 01095 Result.AggregateVal.resize(numElems); 01096 for (unsigned i = 0; i < numElems; ++i) 01097 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i); 01098 } 01099 if (ElemT->isIntegerTy()) { 01100 GenericValue intZero; 01101 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth(); 01102 intZero.IntVal = APInt(elemBitWidth, 0); 01103 Result.AggregateVal.resize(numElems, intZero); 01104 for (unsigned i = 0; i < numElems; ++i) 01105 LoadIntFromMemory(Result.AggregateVal[i].IntVal, 01106 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8); 01107 } 01108 break; 01109 } 01110 default: 01111 SmallString<256> Msg; 01112 raw_svector_ostream OS(Msg); 01113 OS << "Cannot load value of type " << *Ty << "!"; 01114 report_fatal_error(OS.str()); 01115 } 01116 } 01117 01118 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 01119 DEBUG(dbgs() << "JIT: Initializing " << Addr << " "); 01120 DEBUG(Init->dump()); 01121 if (isa<UndefValue>(Init)) 01122 return; 01123 01124 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 01125 unsigned ElementSize = 01126 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType()); 01127 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 01128 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 01129 return; 01130 } 01131 01132 if (isa<ConstantAggregateZero>(Init)) { 01133 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType())); 01134 return; 01135 } 01136 01137 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) { 01138 unsigned ElementSize = 01139 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType()); 01140 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 01141 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 01142 return; 01143 } 01144 01145 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) { 01146 const StructLayout *SL = 01147 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType())); 01148 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 01149 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 01150 return; 01151 } 01152 01153 if (const ConstantDataSequential *CDS = 01154 dyn_cast<ConstantDataSequential>(Init)) { 01155 // CDS is already laid out in host memory order. 01156 StringRef Data = CDS->getRawDataValues(); 01157 memcpy(Addr, Data.data(), Data.size()); 01158 return; 01159 } 01160 01161 if (Init->getType()->isFirstClassType()) { 01162 GenericValue Val = getConstantValue(Init); 01163 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 01164 return; 01165 } 01166 01167 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n"); 01168 llvm_unreachable("Unknown constant type to initialize memory with!"); 01169 } 01170 01171 /// EmitGlobals - Emit all of the global variables to memory, storing their 01172 /// addresses into GlobalAddress. This must make sure to copy the contents of 01173 /// their initializers into the memory. 01174 void ExecutionEngine::emitGlobals() { 01175 // Loop over all of the global variables in the program, allocating the memory 01176 // to hold them. If there is more than one module, do a prepass over globals 01177 // to figure out how the different modules should link together. 01178 std::map<std::pair<std::string, Type*>, 01179 const GlobalValue*> LinkedGlobalsMap; 01180 01181 if (Modules.size() != 1) { 01182 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 01183 Module &M = *Modules[m]; 01184 for (Module::const_global_iterator I = M.global_begin(), 01185 E = M.global_end(); I != E; ++I) { 01186 const GlobalValue *GV = I; 01187 if (GV->hasLocalLinkage() || GV->isDeclaration() || 01188 GV->hasAppendingLinkage() || !GV->hasName()) 01189 continue;// Ignore external globals and globals with internal linkage. 01190 01191 const GlobalValue *&GVEntry = 01192 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 01193 01194 // If this is the first time we've seen this global, it is the canonical 01195 // version. 01196 if (!GVEntry) { 01197 GVEntry = GV; 01198 continue; 01199 } 01200 01201 // If the existing global is strong, never replace it. 01202 if (GVEntry->hasExternalLinkage() || 01203 GVEntry->hasDLLImportLinkage() || 01204 GVEntry->hasDLLExportLinkage()) 01205 continue; 01206 01207 // Otherwise, we know it's linkonce/weak, replace it if this is a strong 01208 // symbol. FIXME is this right for common? 01209 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 01210 GVEntry = GV; 01211 } 01212 } 01213 } 01214 01215 std::vector<const GlobalValue*> NonCanonicalGlobals; 01216 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 01217 Module &M = *Modules[m]; 01218 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 01219 I != E; ++I) { 01220 // In the multi-module case, see what this global maps to. 01221 if (!LinkedGlobalsMap.empty()) { 01222 if (const GlobalValue *GVEntry = 01223 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) { 01224 // If something else is the canonical global, ignore this one. 01225 if (GVEntry != &*I) { 01226 NonCanonicalGlobals.push_back(I); 01227 continue; 01228 } 01229 } 01230 } 01231 01232 if (!I->isDeclaration()) { 01233 addGlobalMapping(I, getMemoryForGV(I)); 01234 } else { 01235 // External variable reference. Try to use the dynamic loader to 01236 // get a pointer to it. 01237 if (void *SymAddr = 01238 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName())) 01239 addGlobalMapping(I, SymAddr); 01240 else { 01241 report_fatal_error("Could not resolve external global address: " 01242 +I->getName()); 01243 } 01244 } 01245 } 01246 01247 // If there are multiple modules, map the non-canonical globals to their 01248 // canonical location. 01249 if (!NonCanonicalGlobals.empty()) { 01250 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 01251 const GlobalValue *GV = NonCanonicalGlobals[i]; 01252 const GlobalValue *CGV = 01253 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 01254 void *Ptr = getPointerToGlobalIfAvailable(CGV); 01255 assert(Ptr && "Canonical global wasn't codegen'd!"); 01256 addGlobalMapping(GV, Ptr); 01257 } 01258 } 01259 01260 // Now that all of the globals are set up in memory, loop through them all 01261 // and initialize their contents. 01262 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 01263 I != E; ++I) { 01264 if (!I->isDeclaration()) { 01265 if (!LinkedGlobalsMap.empty()) { 01266 if (const GlobalValue *GVEntry = 01267 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) 01268 if (GVEntry != &*I) // Not the canonical variable. 01269 continue; 01270 } 01271 EmitGlobalVariable(I); 01272 } 01273 } 01274 } 01275 } 01276 01277 // EmitGlobalVariable - This method emits the specified global variable to the 01278 // address specified in GlobalAddresses, or allocates new memory if it's not 01279 // already in the map. 01280 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 01281 void *GA = getPointerToGlobalIfAvailable(GV); 01282 01283 if (GA == 0) { 01284 // If it's not already specified, allocate memory for the global. 01285 GA = getMemoryForGV(GV); 01286 addGlobalMapping(GV, GA); 01287 } 01288 01289 // Don't initialize if it's thread local, let the client do it. 01290 if (!GV->isThreadLocal()) 01291 InitializeMemory(GV->getInitializer(), GA); 01292 01293 Type *ElTy = GV->getType()->getElementType(); 01294 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy); 01295 NumInitBytes += (unsigned)GVSize; 01296 ++NumGlobals; 01297 } 01298 01299 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE) 01300 : EE(EE), GlobalAddressMap(this) { 01301 } 01302 01303 sys::Mutex * 01304 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) { 01305 return &EES->EE.lock; 01306 } 01307 01308 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES, 01309 const GlobalValue *Old) { 01310 void *OldVal = EES->GlobalAddressMap.lookup(Old); 01311 EES->GlobalAddressReverseMap.erase(OldVal); 01312 } 01313 01314 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *, 01315 const GlobalValue *, 01316 const GlobalValue *) { 01317 llvm_unreachable("The ExecutionEngine doesn't know how to handle a" 01318 " RAUW on a value it has a global mapping for."); 01319 }