1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the common interface used by the various execution engine 11 // subclasses. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ExecutionEngine/ExecutionEngine.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/ExecutionEngine/GenericValue.h" 19 #include "llvm/ExecutionEngine/JITMemoryManager.h" 20 #include "llvm/ExecutionEngine/ObjectCache.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/IR/Operator.h" 26 #include "llvm/IR/ValueHandle.h" 27 #include "llvm/Object/Archive.h" 28 #include "llvm/Object/ObjectFile.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/DynamicLibrary.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/Host.h" 33 #include "llvm/Support/MutexGuard.h" 34 #include "llvm/Support/TargetRegistry.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetMachine.h" 37 #include <cmath> 38 #include <cstring> 39 using namespace llvm; 40 41 #define DEBUG_TYPE "jit" 42 43 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 44 STATISTIC(NumGlobals , "Number of global vars initialized"); 45 46 // Pin the vtable to this file. 47 void ObjectCache::anchor() {} 48 void ObjectBuffer::anchor() {} 49 void ObjectBufferStream::anchor() {} 50 51 ExecutionEngine *(*ExecutionEngine::JITCtor)( 52 std::unique_ptr<Module> M, 53 std::string *ErrorStr, 54 JITMemoryManager *JMM, 55 bool GVsWithCode, 56 TargetMachine *TM) = nullptr; 57 ExecutionEngine *(*ExecutionEngine::MCJITCtor)( 58 std::unique_ptr<Module >M, 59 std::string *ErrorStr, 60 RTDyldMemoryManager *MCJMM, 61 TargetMachine *TM) = nullptr; 62 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M, 63 std::string *ErrorStr) =nullptr; 64 65 ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M) 66 : EEState(*this), 67 LazyFunctionCreator(nullptr) { 68 CompilingLazily = false; 69 GVCompilationDisabled = false; 70 SymbolSearchingDisabled = false; 71 72 // IR module verification is enabled by default in debug builds, and disabled 73 // by default in release builds. 74 #ifndef NDEBUG 75 VerifyModules = true; 76 #else 77 VerifyModules = false; 78 #endif 79 80 assert(M && "Module is null?"); 81 Modules.push_back(std::move(M)); 82 } 83 84 ExecutionEngine::~ExecutionEngine() { 85 clearAllGlobalMappings(); 86 } 87 88 namespace { 89 /// \brief Helper class which uses a value handler to automatically deletes the 90 /// memory block when the GlobalVariable is destroyed. 91 class GVMemoryBlock : public CallbackVH { 92 GVMemoryBlock(const GlobalVariable *GV) 93 : CallbackVH(const_cast<GlobalVariable*>(GV)) {} 94 95 public: 96 /// \brief Returns the address the GlobalVariable should be written into. The 97 /// GVMemoryBlock object prefixes that. 98 static char *Create(const GlobalVariable *GV, const DataLayout& TD) { 99 Type *ElTy = GV->getType()->getElementType(); 100 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy); 101 void *RawMemory = ::operator new( 102 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock), 103 TD.getPreferredAlignment(GV)) 104 + GVSize); 105 new(RawMemory) GVMemoryBlock(GV); 106 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock); 107 } 108 109 void deleted() override { 110 // We allocated with operator new and with some extra memory hanging off the 111 // end, so don't just delete this. I'm not sure if this is actually 112 // required. 113 this->~GVMemoryBlock(); 114 ::operator delete(this); 115 } 116 }; 117 } // anonymous namespace 118 119 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) { 120 return GVMemoryBlock::Create(GV, *getDataLayout()); 121 } 122 123 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) { 124 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile."); 125 } 126 127 void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) { 128 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive."); 129 } 130 131 bool ExecutionEngine::removeModule(Module *M) { 132 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) { 133 Module *Found = I->get(); 134 if (Found == M) { 135 I->release(); 136 Modules.erase(I); 137 clearGlobalMappingsFromModule(M); 138 return true; 139 } 140 } 141 return false; 142 } 143 144 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 145 for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 146 if (Function *F = Modules[i]->getFunction(FnName)) 147 return F; 148 } 149 return nullptr; 150 } 151 152 153 void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) { 154 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap); 155 void *OldVal; 156 157 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the 158 // GlobalAddressMap. 159 if (I == GlobalAddressMap.end()) 160 OldVal = nullptr; 161 else { 162 OldVal = I->second; 163 GlobalAddressMap.erase(I); 164 } 165 166 GlobalAddressReverseMap.erase(OldVal); 167 return OldVal; 168 } 169 170 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 171 MutexGuard locked(lock); 172 173 DEBUG(dbgs() << "JIT: Map \'" << GV->getName() 174 << "\' to [" << Addr << "]\n";); 175 void *&CurVal = EEState.getGlobalAddressMap()[GV]; 176 assert((!CurVal || !Addr) && "GlobalMapping already established!"); 177 CurVal = Addr; 178 179 // If we are using the reverse mapping, add it too. 180 if (!EEState.getGlobalAddressReverseMap().empty()) { 181 AssertingVH<const GlobalValue> &V = 182 EEState.getGlobalAddressReverseMap()[Addr]; 183 assert((!V || !GV) && "GlobalMapping already established!"); 184 V = GV; 185 } 186 } 187 188 void ExecutionEngine::clearAllGlobalMappings() { 189 MutexGuard locked(lock); 190 191 EEState.getGlobalAddressMap().clear(); 192 EEState.getGlobalAddressReverseMap().clear(); 193 } 194 195 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) { 196 MutexGuard locked(lock); 197 198 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) 199 EEState.RemoveMapping(FI); 200 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 201 GI != GE; ++GI) 202 EEState.RemoveMapping(GI); 203 } 204 205 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 206 MutexGuard locked(lock); 207 208 ExecutionEngineState::GlobalAddressMapTy &Map = 209 EEState.getGlobalAddressMap(); 210 211 // Deleting from the mapping? 212 if (!Addr) 213 return EEState.RemoveMapping(GV); 214 215 void *&CurVal = Map[GV]; 216 void *OldVal = CurVal; 217 218 if (CurVal && !EEState.getGlobalAddressReverseMap().empty()) 219 EEState.getGlobalAddressReverseMap().erase(CurVal); 220 CurVal = Addr; 221 222 // If we are using the reverse mapping, add it too. 223 if (!EEState.getGlobalAddressReverseMap().empty()) { 224 AssertingVH<const GlobalValue> &V = 225 EEState.getGlobalAddressReverseMap()[Addr]; 226 assert((!V || !GV) && "GlobalMapping already established!"); 227 V = GV; 228 } 229 return OldVal; 230 } 231 232 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 233 MutexGuard locked(lock); 234 235 ExecutionEngineState::GlobalAddressMapTy::iterator I = 236 EEState.getGlobalAddressMap().find(GV); 237 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr; 238 } 239 240 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 241 MutexGuard locked(lock); 242 243 // If we haven't computed the reverse mapping yet, do so first. 244 if (EEState.getGlobalAddressReverseMap().empty()) { 245 for (ExecutionEngineState::GlobalAddressMapTy::iterator 246 I = EEState.getGlobalAddressMap().begin(), 247 E = EEState.getGlobalAddressMap().end(); I != E; ++I) 248 EEState.getGlobalAddressReverseMap().insert(std::make_pair( 249 I->second, I->first)); 250 } 251 252 std::map<void *, AssertingVH<const GlobalValue> >::iterator I = 253 EEState.getGlobalAddressReverseMap().find(Addr); 254 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr; 255 } 256 257 namespace { 258 class ArgvArray { 259 char *Array; 260 std::vector<char*> Values; 261 public: 262 ArgvArray() : Array(nullptr) {} 263 ~ArgvArray() { clear(); } 264 void clear() { 265 delete[] Array; 266 Array = nullptr; 267 for (size_t I = 0, E = Values.size(); I != E; ++I) { 268 delete[] Values[I]; 269 } 270 Values.clear(); 271 } 272 /// Turn a vector of strings into a nice argv style array of pointers to null 273 /// terminated strings. 274 void *reset(LLVMContext &C, ExecutionEngine *EE, 275 const std::vector<std::string> &InputArgv); 276 }; 277 } // anonymous namespace 278 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE, 279 const std::vector<std::string> &InputArgv) { 280 clear(); // Free the old contents. 281 unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 282 Array = new char[(InputArgv.size()+1)*PtrSize]; 283 284 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n"); 285 Type *SBytePtr = Type::getInt8PtrTy(C); 286 287 for (unsigned i = 0; i != InputArgv.size(); ++i) { 288 unsigned Size = InputArgv[i].size()+1; 289 char *Dest = new char[Size]; 290 Values.push_back(Dest); 291 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n"); 292 293 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 294 Dest[Size-1] = 0; 295 296 // Endian safe: Array[i] = (PointerTy)Dest; 297 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize), 298 SBytePtr); 299 } 300 301 // Null terminate it 302 EE->StoreValueToMemory(PTOGV(nullptr), 303 (GenericValue*)(Array+InputArgv.size()*PtrSize), 304 SBytePtr); 305 return Array; 306 } 307 308 void ExecutionEngine::runStaticConstructorsDestructors(Module &module, 309 bool isDtors) { 310 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 311 GlobalVariable *GV = module.getNamedGlobal(Name); 312 313 // If this global has internal linkage, or if it has a use, then it must be 314 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 315 // this is the case, don't execute any of the global ctors, __main will do 316 // it. 317 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return; 318 319 // Should be an array of '{ i32, void ()* }' structs. The first value is 320 // the init priority, which we ignore. 321 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 322 if (!InitList) 323 return; 324 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 325 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i)); 326 if (!CS) continue; 327 328 Constant *FP = CS->getOperand(1); 329 if (FP->isNullValue()) 330 continue; // Found a sentinal value, ignore. 331 332 // Strip off constant expression casts. 333 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 334 if (CE->isCast()) 335 FP = CE->getOperand(0); 336 337 // Execute the ctor/dtor function! 338 if (Function *F = dyn_cast<Function>(FP)) 339 runFunction(F, std::vector<GenericValue>()); 340 341 // FIXME: It is marginally lame that we just do nothing here if we see an 342 // entry we don't recognize. It might not be unreasonable for the verifier 343 // to not even allow this and just assert here. 344 } 345 } 346 347 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 348 // Execute global ctors/dtors for each module in the program. 349 for (std::unique_ptr<Module> &M : Modules) 350 runStaticConstructorsDestructors(*M, isDtors); 351 } 352 353 #ifndef NDEBUG 354 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null. 355 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) { 356 unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 357 for (unsigned i = 0; i < PtrSize; ++i) 358 if (*(i + (uint8_t*)Loc)) 359 return false; 360 return true; 361 } 362 #endif 363 364 int ExecutionEngine::runFunctionAsMain(Function *Fn, 365 const std::vector<std::string> &argv, 366 const char * const * envp) { 367 std::vector<GenericValue> GVArgs; 368 GenericValue GVArgc; 369 GVArgc.IntVal = APInt(32, argv.size()); 370 371 // Check main() type 372 unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 373 FunctionType *FTy = Fn->getFunctionType(); 374 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo(); 375 376 // Check the argument types. 377 if (NumArgs > 3) 378 report_fatal_error("Invalid number of arguments of main() supplied"); 379 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty) 380 report_fatal_error("Invalid type for third argument of main() supplied"); 381 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty) 382 report_fatal_error("Invalid type for second argument of main() supplied"); 383 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32)) 384 report_fatal_error("Invalid type for first argument of main() supplied"); 385 if (!FTy->getReturnType()->isIntegerTy() && 386 !FTy->getReturnType()->isVoidTy()) 387 report_fatal_error("Invalid return type of main() supplied"); 388 389 ArgvArray CArgv; 390 ArgvArray CEnv; 391 if (NumArgs) { 392 GVArgs.push_back(GVArgc); // Arg #0 = argc. 393 if (NumArgs > 1) { 394 // Arg #1 = argv. 395 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv))); 396 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) && 397 "argv[0] was null after CreateArgv"); 398 if (NumArgs > 2) { 399 std::vector<std::string> EnvVars; 400 for (unsigned i = 0; envp[i]; ++i) 401 EnvVars.push_back(envp[i]); 402 // Arg #2 = envp. 403 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars))); 404 } 405 } 406 } 407 408 return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 409 } 410 411 void EngineBuilder::InitEngine() { 412 WhichEngine = EngineKind::Either; 413 ErrorStr = nullptr; 414 OptLevel = CodeGenOpt::Default; 415 MCJMM = nullptr; 416 JMM = nullptr; 417 Options = TargetOptions(); 418 AllocateGVsWithCode = false; 419 RelocModel = Reloc::Default; 420 CMModel = CodeModel::JITDefault; 421 UseMCJIT = false; 422 423 // IR module verification is enabled by default in debug builds, and disabled 424 // by default in release builds. 425 #ifndef NDEBUG 426 VerifyModules = true; 427 #else 428 VerifyModules = false; 429 #endif 430 } 431 432 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) { 433 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership. 434 435 // Make sure we can resolve symbols in the program as well. The zero arg 436 // to the function tells DynamicLibrary to load the program, not a library. 437 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr)) 438 return nullptr; 439 440 assert(!(JMM && MCJMM)); 441 442 // If the user specified a memory manager but didn't specify which engine to 443 // create, we assume they only want the JIT, and we fail if they only want 444 // the interpreter. 445 if (JMM || MCJMM) { 446 if (WhichEngine & EngineKind::JIT) 447 WhichEngine = EngineKind::JIT; 448 else { 449 if (ErrorStr) 450 *ErrorStr = "Cannot create an interpreter with a memory manager."; 451 return nullptr; 452 } 453 } 454 455 if (MCJMM && ! UseMCJIT) { 456 if (ErrorStr) 457 *ErrorStr = 458 "Cannot create a legacy JIT with a runtime dyld memory " 459 "manager."; 460 return nullptr; 461 } 462 463 // Unless the interpreter was explicitly selected or the JIT is not linked, 464 // try making a JIT. 465 if ((WhichEngine & EngineKind::JIT) && TheTM) { 466 Triple TT(M->getTargetTriple()); 467 if (!TM->getTarget().hasJIT()) { 468 errs() << "WARNING: This target JIT is not designed for the host" 469 << " you are running. If bad things happen, please choose" 470 << " a different -march switch.\n"; 471 } 472 473 ExecutionEngine *EE = nullptr; 474 if (UseMCJIT && ExecutionEngine::MCJITCtor) 475 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, 476 MCJMM ? MCJMM : JMM, TheTM.release()); 477 else if (ExecutionEngine::JITCtor) 478 EE = ExecutionEngine::JITCtor(std::move(M), ErrorStr, JMM, 479 AllocateGVsWithCode, TheTM.release()); 480 481 if (EE) { 482 EE->setVerifyModules(VerifyModules); 483 return EE; 484 } 485 } 486 487 // If we can't make a JIT and we didn't request one specifically, try making 488 // an interpreter instead. 489 if (WhichEngine & EngineKind::Interpreter) { 490 if (ExecutionEngine::InterpCtor) 491 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr); 492 if (ErrorStr) 493 *ErrorStr = "Interpreter has not been linked in."; 494 return nullptr; 495 } 496 497 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor && 498 !ExecutionEngine::MCJITCtor) { 499 if (ErrorStr) 500 *ErrorStr = "JIT has not been linked in."; 501 } 502 503 return nullptr; 504 } 505 506 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 507 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 508 return getPointerToFunction(F); 509 510 MutexGuard locked(lock); 511 if (void *P = EEState.getGlobalAddressMap()[GV]) 512 return P; 513 514 // Global variable might have been added since interpreter started. 515 if (GlobalVariable *GVar = 516 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 517 EmitGlobalVariable(GVar); 518 else 519 llvm_unreachable("Global hasn't had an address allocated yet!"); 520 521 return EEState.getGlobalAddressMap()[GV]; 522 } 523 524 /// \brief Converts a Constant* into a GenericValue, including handling of 525 /// ConstantExpr values. 526 GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 527 // If its undefined, return the garbage. 528 if (isa<UndefValue>(C)) { 529 GenericValue Result; 530 switch (C->getType()->getTypeID()) { 531 default: 532 break; 533 case Type::IntegerTyID: 534 case Type::X86_FP80TyID: 535 case Type::FP128TyID: 536 case Type::PPC_FP128TyID: 537 // Although the value is undefined, we still have to construct an APInt 538 // with the correct bit width. 539 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0); 540 break; 541 case Type::StructTyID: { 542 // if the whole struct is 'undef' just reserve memory for the value. 543 if(StructType *STy = dyn_cast<StructType>(C->getType())) { 544 unsigned int elemNum = STy->getNumElements(); 545 Result.AggregateVal.resize(elemNum); 546 for (unsigned int i = 0; i < elemNum; ++i) { 547 Type *ElemTy = STy->getElementType(i); 548 if (ElemTy->isIntegerTy()) 549 Result.AggregateVal[i].IntVal = 550 APInt(ElemTy->getPrimitiveSizeInBits(), 0); 551 else if (ElemTy->isAggregateType()) { 552 const Constant *ElemUndef = UndefValue::get(ElemTy); 553 Result.AggregateVal[i] = getConstantValue(ElemUndef); 554 } 555 } 556 } 557 } 558 break; 559 case Type::VectorTyID: 560 // if the whole vector is 'undef' just reserve memory for the value. 561 const VectorType* VTy = dyn_cast<VectorType>(C->getType()); 562 const Type *ElemTy = VTy->getElementType(); 563 unsigned int elemNum = VTy->getNumElements(); 564 Result.AggregateVal.resize(elemNum); 565 if (ElemTy->isIntegerTy()) 566 for (unsigned int i = 0; i < elemNum; ++i) 567 Result.AggregateVal[i].IntVal = 568 APInt(ElemTy->getPrimitiveSizeInBits(), 0); 569 break; 570 } 571 return Result; 572 } 573 574 // Otherwise, if the value is a ConstantExpr... 575 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 576 Constant *Op0 = CE->getOperand(0); 577 switch (CE->getOpcode()) { 578 case Instruction::GetElementPtr: { 579 // Compute the index 580 GenericValue Result = getConstantValue(Op0); 581 APInt Offset(DL->getPointerSizeInBits(), 0); 582 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset); 583 584 char* tmp = (char*) Result.PointerVal; 585 Result = PTOGV(tmp + Offset.getSExtValue()); 586 return Result; 587 } 588 case Instruction::Trunc: { 589 GenericValue GV = getConstantValue(Op0); 590 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 591 GV.IntVal = GV.IntVal.trunc(BitWidth); 592 return GV; 593 } 594 case Instruction::ZExt: { 595 GenericValue GV = getConstantValue(Op0); 596 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 597 GV.IntVal = GV.IntVal.zext(BitWidth); 598 return GV; 599 } 600 case Instruction::SExt: { 601 GenericValue GV = getConstantValue(Op0); 602 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 603 GV.IntVal = GV.IntVal.sext(BitWidth); 604 return GV; 605 } 606 case Instruction::FPTrunc: { 607 // FIXME long double 608 GenericValue GV = getConstantValue(Op0); 609 GV.FloatVal = float(GV.DoubleVal); 610 return GV; 611 } 612 case Instruction::FPExt:{ 613 // FIXME long double 614 GenericValue GV = getConstantValue(Op0); 615 GV.DoubleVal = double(GV.FloatVal); 616 return GV; 617 } 618 case Instruction::UIToFP: { 619 GenericValue GV = getConstantValue(Op0); 620 if (CE->getType()->isFloatTy()) 621 GV.FloatVal = float(GV.IntVal.roundToDouble()); 622 else if (CE->getType()->isDoubleTy()) 623 GV.DoubleVal = GV.IntVal.roundToDouble(); 624 else if (CE->getType()->isX86_FP80Ty()) { 625 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 626 (void)apf.convertFromAPInt(GV.IntVal, 627 false, 628 APFloat::rmNearestTiesToEven); 629 GV.IntVal = apf.bitcastToAPInt(); 630 } 631 return GV; 632 } 633 case Instruction::SIToFP: { 634 GenericValue GV = getConstantValue(Op0); 635 if (CE->getType()->isFloatTy()) 636 GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 637 else if (CE->getType()->isDoubleTy()) 638 GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 639 else if (CE->getType()->isX86_FP80Ty()) { 640 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 641 (void)apf.convertFromAPInt(GV.IntVal, 642 true, 643 APFloat::rmNearestTiesToEven); 644 GV.IntVal = apf.bitcastToAPInt(); 645 } 646 return GV; 647 } 648 case Instruction::FPToUI: // double->APInt conversion handles sign 649 case Instruction::FPToSI: { 650 GenericValue GV = getConstantValue(Op0); 651 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 652 if (Op0->getType()->isFloatTy()) 653 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 654 else if (Op0->getType()->isDoubleTy()) 655 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 656 else if (Op0->getType()->isX86_FP80Ty()) { 657 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal); 658 uint64_t v; 659 bool ignored; 660 (void)apf.convertToInteger(&v, BitWidth, 661 CE->getOpcode()==Instruction::FPToSI, 662 APFloat::rmTowardZero, &ignored); 663 GV.IntVal = v; // endian? 664 } 665 return GV; 666 } 667 case Instruction::PtrToInt: { 668 GenericValue GV = getConstantValue(Op0); 669 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType()); 670 assert(PtrWidth <= 64 && "Bad pointer width"); 671 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 672 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType()); 673 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth); 674 return GV; 675 } 676 case Instruction::IntToPtr: { 677 GenericValue GV = getConstantValue(Op0); 678 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType()); 679 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 680 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 681 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 682 return GV; 683 } 684 case Instruction::BitCast: { 685 GenericValue GV = getConstantValue(Op0); 686 Type* DestTy = CE->getType(); 687 switch (Op0->getType()->getTypeID()) { 688 default: llvm_unreachable("Invalid bitcast operand"); 689 case Type::IntegerTyID: 690 assert(DestTy->isFloatingPointTy() && "invalid bitcast"); 691 if (DestTy->isFloatTy()) 692 GV.FloatVal = GV.IntVal.bitsToFloat(); 693 else if (DestTy->isDoubleTy()) 694 GV.DoubleVal = GV.IntVal.bitsToDouble(); 695 break; 696 case Type::FloatTyID: 697 assert(DestTy->isIntegerTy(32) && "Invalid bitcast"); 698 GV.IntVal = APInt::floatToBits(GV.FloatVal); 699 break; 700 case Type::DoubleTyID: 701 assert(DestTy->isIntegerTy(64) && "Invalid bitcast"); 702 GV.IntVal = APInt::doubleToBits(GV.DoubleVal); 703 break; 704 case Type::PointerTyID: 705 assert(DestTy->isPointerTy() && "Invalid bitcast"); 706 break; // getConstantValue(Op0) above already converted it 707 } 708 return GV; 709 } 710 case Instruction::Add: 711 case Instruction::FAdd: 712 case Instruction::Sub: 713 case Instruction::FSub: 714 case Instruction::Mul: 715 case Instruction::FMul: 716 case Instruction::UDiv: 717 case Instruction::SDiv: 718 case Instruction::URem: 719 case Instruction::SRem: 720 case Instruction::And: 721 case Instruction::Or: 722 case Instruction::Xor: { 723 GenericValue LHS = getConstantValue(Op0); 724 GenericValue RHS = getConstantValue(CE->getOperand(1)); 725 GenericValue GV; 726 switch (CE->getOperand(0)->getType()->getTypeID()) { 727 default: llvm_unreachable("Bad add type!"); 728 case Type::IntegerTyID: 729 switch (CE->getOpcode()) { 730 default: llvm_unreachable("Invalid integer opcode"); 731 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 732 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 733 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 734 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 735 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 736 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 737 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 738 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 739 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 740 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 741 } 742 break; 743 case Type::FloatTyID: 744 switch (CE->getOpcode()) { 745 default: llvm_unreachable("Invalid float opcode"); 746 case Instruction::FAdd: 747 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 748 case Instruction::FSub: 749 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 750 case Instruction::FMul: 751 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 752 case Instruction::FDiv: 753 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 754 case Instruction::FRem: 755 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break; 756 } 757 break; 758 case Type::DoubleTyID: 759 switch (CE->getOpcode()) { 760 default: llvm_unreachable("Invalid double opcode"); 761 case Instruction::FAdd: 762 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 763 case Instruction::FSub: 764 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 765 case Instruction::FMul: 766 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 767 case Instruction::FDiv: 768 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 769 case Instruction::FRem: 770 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 771 } 772 break; 773 case Type::X86_FP80TyID: 774 case Type::PPC_FP128TyID: 775 case Type::FP128TyID: { 776 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics(); 777 APFloat apfLHS = APFloat(Sem, LHS.IntVal); 778 switch (CE->getOpcode()) { 779 default: llvm_unreachable("Invalid long double opcode"); 780 case Instruction::FAdd: 781 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven); 782 GV.IntVal = apfLHS.bitcastToAPInt(); 783 break; 784 case Instruction::FSub: 785 apfLHS.subtract(APFloat(Sem, RHS.IntVal), 786 APFloat::rmNearestTiesToEven); 787 GV.IntVal = apfLHS.bitcastToAPInt(); 788 break; 789 case Instruction::FMul: 790 apfLHS.multiply(APFloat(Sem, RHS.IntVal), 791 APFloat::rmNearestTiesToEven); 792 GV.IntVal = apfLHS.bitcastToAPInt(); 793 break; 794 case Instruction::FDiv: 795 apfLHS.divide(APFloat(Sem, RHS.IntVal), 796 APFloat::rmNearestTiesToEven); 797 GV.IntVal = apfLHS.bitcastToAPInt(); 798 break; 799 case Instruction::FRem: 800 apfLHS.mod(APFloat(Sem, RHS.IntVal), 801 APFloat::rmNearestTiesToEven); 802 GV.IntVal = apfLHS.bitcastToAPInt(); 803 break; 804 } 805 } 806 break; 807 } 808 return GV; 809 } 810 default: 811 break; 812 } 813 814 SmallString<256> Msg; 815 raw_svector_ostream OS(Msg); 816 OS << "ConstantExpr not handled: " << *CE; 817 report_fatal_error(OS.str()); 818 } 819 820 // Otherwise, we have a simple constant. 821 GenericValue Result; 822 switch (C->getType()->getTypeID()) { 823 case Type::FloatTyID: 824 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 825 break; 826 case Type::DoubleTyID: 827 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 828 break; 829 case Type::X86_FP80TyID: 830 case Type::FP128TyID: 831 case Type::PPC_FP128TyID: 832 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt(); 833 break; 834 case Type::IntegerTyID: 835 Result.IntVal = cast<ConstantInt>(C)->getValue(); 836 break; 837 case Type::PointerTyID: 838 if (isa<ConstantPointerNull>(C)) 839 Result.PointerVal = nullptr; 840 else if (const Function *F = dyn_cast<Function>(C)) 841 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 842 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) 843 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 844 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 845 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>( 846 BA->getBasicBlock()))); 847 else 848 llvm_unreachable("Unknown constant pointer type!"); 849 break; 850 case Type::VectorTyID: { 851 unsigned elemNum; 852 Type* ElemTy; 853 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C); 854 const ConstantVector *CV = dyn_cast<ConstantVector>(C); 855 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C); 856 857 if (CDV) { 858 elemNum = CDV->getNumElements(); 859 ElemTy = CDV->getElementType(); 860 } else if (CV || CAZ) { 861 VectorType* VTy = dyn_cast<VectorType>(C->getType()); 862 elemNum = VTy->getNumElements(); 863 ElemTy = VTy->getElementType(); 864 } else { 865 llvm_unreachable("Unknown constant vector type!"); 866 } 867 868 Result.AggregateVal.resize(elemNum); 869 // Check if vector holds floats. 870 if(ElemTy->isFloatTy()) { 871 if (CAZ) { 872 GenericValue floatZero; 873 floatZero.FloatVal = 0.f; 874 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 875 floatZero); 876 break; 877 } 878 if(CV) { 879 for (unsigned i = 0; i < elemNum; ++i) 880 if (!isa<UndefValue>(CV->getOperand(i))) 881 Result.AggregateVal[i].FloatVal = cast<ConstantFP>( 882 CV->getOperand(i))->getValueAPF().convertToFloat(); 883 break; 884 } 885 if(CDV) 886 for (unsigned i = 0; i < elemNum; ++i) 887 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i); 888 889 break; 890 } 891 // Check if vector holds doubles. 892 if (ElemTy->isDoubleTy()) { 893 if (CAZ) { 894 GenericValue doubleZero; 895 doubleZero.DoubleVal = 0.0; 896 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 897 doubleZero); 898 break; 899 } 900 if(CV) { 901 for (unsigned i = 0; i < elemNum; ++i) 902 if (!isa<UndefValue>(CV->getOperand(i))) 903 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>( 904 CV->getOperand(i))->getValueAPF().convertToDouble(); 905 break; 906 } 907 if(CDV) 908 for (unsigned i = 0; i < elemNum; ++i) 909 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i); 910 911 break; 912 } 913 // Check if vector holds integers. 914 if (ElemTy->isIntegerTy()) { 915 if (CAZ) { 916 GenericValue intZero; 917 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull); 918 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 919 intZero); 920 break; 921 } 922 if(CV) { 923 for (unsigned i = 0; i < elemNum; ++i) 924 if (!isa<UndefValue>(CV->getOperand(i))) 925 Result.AggregateVal[i].IntVal = cast<ConstantInt>( 926 CV->getOperand(i))->getValue(); 927 else { 928 Result.AggregateVal[i].IntVal = 929 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0); 930 } 931 break; 932 } 933 if(CDV) 934 for (unsigned i = 0; i < elemNum; ++i) 935 Result.AggregateVal[i].IntVal = APInt( 936 CDV->getElementType()->getPrimitiveSizeInBits(), 937 CDV->getElementAsInteger(i)); 938 939 break; 940 } 941 llvm_unreachable("Unknown constant pointer type!"); 942 } 943 break; 944 945 default: 946 SmallString<256> Msg; 947 raw_svector_ostream OS(Msg); 948 OS << "ERROR: Constant unimplemented for type: " << *C->getType(); 949 report_fatal_error(OS.str()); 950 } 951 952 return Result; 953 } 954 955 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 956 /// with the integer held in IntVal. 957 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 958 unsigned StoreBytes) { 959 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 960 const uint8_t *Src = (const uint8_t *)IntVal.getRawData(); 961 962 if (sys::IsLittleEndianHost) { 963 // Little-endian host - the source is ordered from LSB to MSB. Order the 964 // destination from LSB to MSB: Do a straight copy. 965 memcpy(Dst, Src, StoreBytes); 966 } else { 967 // Big-endian host - the source is an array of 64 bit words ordered from 968 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 969 // from MSB to LSB: Reverse the word order, but not the bytes in a word. 970 while (StoreBytes > sizeof(uint64_t)) { 971 StoreBytes -= sizeof(uint64_t); 972 // May not be aligned so use memcpy. 973 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 974 Src += sizeof(uint64_t); 975 } 976 977 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 978 } 979 } 980 981 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, 982 GenericValue *Ptr, Type *Ty) { 983 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty); 984 985 switch (Ty->getTypeID()) { 986 default: 987 dbgs() << "Cannot store value of type " << *Ty << "!\n"; 988 break; 989 case Type::IntegerTyID: 990 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes); 991 break; 992 case Type::FloatTyID: 993 *((float*)Ptr) = Val.FloatVal; 994 break; 995 case Type::DoubleTyID: 996 *((double*)Ptr) = Val.DoubleVal; 997 break; 998 case Type::X86_FP80TyID: 999 memcpy(Ptr, Val.IntVal.getRawData(), 10); 1000 break; 1001 case Type::PointerTyID: 1002 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts. 1003 if (StoreBytes != sizeof(PointerTy)) 1004 memset(&(Ptr->PointerVal), 0, StoreBytes); 1005 1006 *((PointerTy*)Ptr) = Val.PointerVal; 1007 break; 1008 case Type::VectorTyID: 1009 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) { 1010 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy()) 1011 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal; 1012 if (cast<VectorType>(Ty)->getElementType()->isFloatTy()) 1013 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal; 1014 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) { 1015 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8; 1016 StoreIntToMemory(Val.AggregateVal[i].IntVal, 1017 (uint8_t*)Ptr + numOfBytes*i, numOfBytes); 1018 } 1019 } 1020 break; 1021 } 1022 1023 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian()) 1024 // Host and target are different endian - reverse the stored bytes. 1025 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr); 1026 } 1027 1028 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 1029 /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 1030 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) { 1031 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 1032 uint8_t *Dst = reinterpret_cast<uint8_t *>( 1033 const_cast<uint64_t *>(IntVal.getRawData())); 1034 1035 if (sys::IsLittleEndianHost) 1036 // Little-endian host - the destination must be ordered from LSB to MSB. 1037 // The source is ordered from LSB to MSB: Do a straight copy. 1038 memcpy(Dst, Src, LoadBytes); 1039 else { 1040 // Big-endian - the destination is an array of 64 bit words ordered from 1041 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 1042 // ordered from MSB to LSB: Reverse the word order, but not the bytes in 1043 // a word. 1044 while (LoadBytes > sizeof(uint64_t)) { 1045 LoadBytes -= sizeof(uint64_t); 1046 // May not be aligned so use memcpy. 1047 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 1048 Dst += sizeof(uint64_t); 1049 } 1050 1051 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 1052 } 1053 } 1054 1055 /// FIXME: document 1056 /// 1057 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 1058 GenericValue *Ptr, 1059 Type *Ty) { 1060 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty); 1061 1062 switch (Ty->getTypeID()) { 1063 case Type::IntegerTyID: 1064 // An APInt with all words initially zero. 1065 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0); 1066 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes); 1067 break; 1068 case Type::FloatTyID: 1069 Result.FloatVal = *((float*)Ptr); 1070 break; 1071 case Type::DoubleTyID: 1072 Result.DoubleVal = *((double*)Ptr); 1073 break; 1074 case Type::PointerTyID: 1075 Result.PointerVal = *((PointerTy*)Ptr); 1076 break; 1077 case Type::X86_FP80TyID: { 1078 // This is endian dependent, but it will only work on x86 anyway. 1079 // FIXME: Will not trap if loading a signaling NaN. 1080 uint64_t y[2]; 1081 memcpy(y, Ptr, 10); 1082 Result.IntVal = APInt(80, y); 1083 break; 1084 } 1085 case Type::VectorTyID: { 1086 const VectorType *VT = cast<VectorType>(Ty); 1087 const Type *ElemT = VT->getElementType(); 1088 const unsigned numElems = VT->getNumElements(); 1089 if (ElemT->isFloatTy()) { 1090 Result.AggregateVal.resize(numElems); 1091 for (unsigned i = 0; i < numElems; ++i) 1092 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i); 1093 } 1094 if (ElemT->isDoubleTy()) { 1095 Result.AggregateVal.resize(numElems); 1096 for (unsigned i = 0; i < numElems; ++i) 1097 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i); 1098 } 1099 if (ElemT->isIntegerTy()) { 1100 GenericValue intZero; 1101 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth(); 1102 intZero.IntVal = APInt(elemBitWidth, 0); 1103 Result.AggregateVal.resize(numElems, intZero); 1104 for (unsigned i = 0; i < numElems; ++i) 1105 LoadIntFromMemory(Result.AggregateVal[i].IntVal, 1106 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8); 1107 } 1108 break; 1109 } 1110 default: 1111 SmallString<256> Msg; 1112 raw_svector_ostream OS(Msg); 1113 OS << "Cannot load value of type " << *Ty << "!"; 1114 report_fatal_error(OS.str()); 1115 } 1116 } 1117 1118 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 1119 DEBUG(dbgs() << "JIT: Initializing " << Addr << " "); 1120 DEBUG(Init->dump()); 1121 if (isa<UndefValue>(Init)) 1122 return; 1123 1124 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 1125 unsigned ElementSize = 1126 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType()); 1127 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 1128 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 1129 return; 1130 } 1131 1132 if (isa<ConstantAggregateZero>(Init)) { 1133 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType())); 1134 return; 1135 } 1136 1137 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) { 1138 unsigned ElementSize = 1139 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType()); 1140 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 1141 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 1142 return; 1143 } 1144 1145 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) { 1146 const StructLayout *SL = 1147 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType())); 1148 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 1149 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 1150 return; 1151 } 1152 1153 if (const ConstantDataSequential *CDS = 1154 dyn_cast<ConstantDataSequential>(Init)) { 1155 // CDS is already laid out in host memory order. 1156 StringRef Data = CDS->getRawDataValues(); 1157 memcpy(Addr, Data.data(), Data.size()); 1158 return; 1159 } 1160 1161 if (Init->getType()->isFirstClassType()) { 1162 GenericValue Val = getConstantValue(Init); 1163 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 1164 return; 1165 } 1166 1167 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n"); 1168 llvm_unreachable("Unknown constant type to initialize memory with!"); 1169 } 1170 1171 /// EmitGlobals - Emit all of the global variables to memory, storing their 1172 /// addresses into GlobalAddress. This must make sure to copy the contents of 1173 /// their initializers into the memory. 1174 void ExecutionEngine::emitGlobals() { 1175 // Loop over all of the global variables in the program, allocating the memory 1176 // to hold them. If there is more than one module, do a prepass over globals 1177 // to figure out how the different modules should link together. 1178 std::map<std::pair<std::string, Type*>, 1179 const GlobalValue*> LinkedGlobalsMap; 1180 1181 if (Modules.size() != 1) { 1182 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1183 Module &M = *Modules[m]; 1184 for (const auto &GV : M.globals()) { 1185 if (GV.hasLocalLinkage() || GV.isDeclaration() || 1186 GV.hasAppendingLinkage() || !GV.hasName()) 1187 continue;// Ignore external globals and globals with internal linkage. 1188 1189 const GlobalValue *&GVEntry = 1190 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]; 1191 1192 // If this is the first time we've seen this global, it is the canonical 1193 // version. 1194 if (!GVEntry) { 1195 GVEntry = &GV; 1196 continue; 1197 } 1198 1199 // If the existing global is strong, never replace it. 1200 if (GVEntry->hasExternalLinkage()) 1201 continue; 1202 1203 // Otherwise, we know it's linkonce/weak, replace it if this is a strong 1204 // symbol. FIXME is this right for common? 1205 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 1206 GVEntry = &GV; 1207 } 1208 } 1209 } 1210 1211 std::vector<const GlobalValue*> NonCanonicalGlobals; 1212 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1213 Module &M = *Modules[m]; 1214 for (const auto &GV : M.globals()) { 1215 // In the multi-module case, see what this global maps to. 1216 if (!LinkedGlobalsMap.empty()) { 1217 if (const GlobalValue *GVEntry = 1218 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) { 1219 // If something else is the canonical global, ignore this one. 1220 if (GVEntry != &GV) { 1221 NonCanonicalGlobals.push_back(&GV); 1222 continue; 1223 } 1224 } 1225 } 1226 1227 if (!GV.isDeclaration()) { 1228 addGlobalMapping(&GV, getMemoryForGV(&GV)); 1229 } else { 1230 // External variable reference. Try to use the dynamic loader to 1231 // get a pointer to it. 1232 if (void *SymAddr = 1233 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName())) 1234 addGlobalMapping(&GV, SymAddr); 1235 else { 1236 report_fatal_error("Could not resolve external global address: " 1237 +GV.getName()); 1238 } 1239 } 1240 } 1241 1242 // If there are multiple modules, map the non-canonical globals to their 1243 // canonical location. 1244 if (!NonCanonicalGlobals.empty()) { 1245 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 1246 const GlobalValue *GV = NonCanonicalGlobals[i]; 1247 const GlobalValue *CGV = 1248 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 1249 void *Ptr = getPointerToGlobalIfAvailable(CGV); 1250 assert(Ptr && "Canonical global wasn't codegen'd!"); 1251 addGlobalMapping(GV, Ptr); 1252 } 1253 } 1254 1255 // Now that all of the globals are set up in memory, loop through them all 1256 // and initialize their contents. 1257 for (const auto &GV : M.globals()) { 1258 if (!GV.isDeclaration()) { 1259 if (!LinkedGlobalsMap.empty()) { 1260 if (const GlobalValue *GVEntry = 1261 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) 1262 if (GVEntry != &GV) // Not the canonical variable. 1263 continue; 1264 } 1265 EmitGlobalVariable(&GV); 1266 } 1267 } 1268 } 1269 } 1270 1271 // EmitGlobalVariable - This method emits the specified global variable to the 1272 // address specified in GlobalAddresses, or allocates new memory if it's not 1273 // already in the map. 1274 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 1275 void *GA = getPointerToGlobalIfAvailable(GV); 1276 1277 if (!GA) { 1278 // If it's not already specified, allocate memory for the global. 1279 GA = getMemoryForGV(GV); 1280 1281 // If we failed to allocate memory for this global, return. 1282 if (!GA) return; 1283 1284 addGlobalMapping(GV, GA); 1285 } 1286 1287 // Don't initialize if it's thread local, let the client do it. 1288 if (!GV->isThreadLocal()) 1289 InitializeMemory(GV->getInitializer(), GA); 1290 1291 Type *ElTy = GV->getType()->getElementType(); 1292 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy); 1293 NumInitBytes += (unsigned)GVSize; 1294 ++NumGlobals; 1295 } 1296 1297 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE) 1298 : EE(EE), GlobalAddressMap(this) { 1299 } 1300 1301 sys::Mutex * 1302 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) { 1303 return &EES->EE.lock; 1304 } 1305 1306 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES, 1307 const GlobalValue *Old) { 1308 void *OldVal = EES->GlobalAddressMap.lookup(Old); 1309 EES->GlobalAddressReverseMap.erase(OldVal); 1310 } 1311 1312 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *, 1313 const GlobalValue *, 1314 const GlobalValue *) { 1315 llvm_unreachable("The ExecutionEngine doesn't know how to handle a" 1316 " RAUW on a value it has a global mapping for."); 1317 } 1318