ExecutionEngine.cpp revision b83eb6447ba155342598f0fabe1f08f5baa9164a
1//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the common interface used by the various execution engine 11// subclasses. 12// 13//===----------------------------------------------------------------------===// 14 15#define DEBUG_TYPE "jit" 16#include "llvm/Constants.h" 17#include "llvm/DerivedTypes.h" 18#include "llvm/Module.h" 19#include "llvm/ModuleProvider.h" 20#include "llvm/ADT/Statistic.h" 21#include "llvm/ExecutionEngine/ExecutionEngine.h" 22#include "llvm/ExecutionEngine/GenericValue.h" 23#include "llvm/Support/Debug.h" 24#include "llvm/Support/MutexGuard.h" 25#include "llvm/System/DynamicLibrary.h" 26#include "llvm/Target/TargetData.h" 27#include <iostream> 28using namespace llvm; 29 30namespace { 31 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized"); 32 Statistic<> NumGlobals ("lli", "Number of global vars initialized"); 33} 34 35ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0; 36ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0; 37 38ExecutionEngine::ExecutionEngine(ModuleProvider *P) { 39 Modules.push_back(P); 40 assert(P && "ModuleProvider is null?"); 41} 42 43ExecutionEngine::ExecutionEngine(Module *M) { 44 assert(M && "Module is null?"); 45 Modules.push_back(new ExistingModuleProvider(M)); 46} 47 48ExecutionEngine::~ExecutionEngine() { 49 for (unsigned i = 0, e = Modules.size(); i != e; ++i) 50 delete Modules[i]; 51} 52 53/// FindFunctionNamed - Search all of the active modules to find the one that 54/// defines FnName. This is very slow operation and shouldn't be used for 55/// general code. 56Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 57 for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 58 if (Function *F = Modules[i]->getModule()->getNamedFunction(FnName)) 59 return F; 60 } 61 return 0; 62} 63 64 65/// addGlobalMapping - Tell the execution engine that the specified global is 66/// at the specified location. This is used internally as functions are JIT'd 67/// and as global variables are laid out in memory. It can and should also be 68/// used by clients of the EE that want to have an LLVM global overlay 69/// existing data in memory. 70void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 71 MutexGuard locked(lock); 72 73 void *&CurVal = state.getGlobalAddressMap(locked)[GV]; 74 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!"); 75 CurVal = Addr; 76 77 // If we are using the reverse mapping, add it too 78 if (!state.getGlobalAddressReverseMap(locked).empty()) { 79 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr]; 80 assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 81 V = GV; 82 } 83} 84 85/// clearAllGlobalMappings - Clear all global mappings and start over again 86/// use in dynamic compilation scenarios when you want to move globals 87void ExecutionEngine::clearAllGlobalMappings() { 88 MutexGuard locked(lock); 89 90 state.getGlobalAddressMap(locked).clear(); 91 state.getGlobalAddressReverseMap(locked).clear(); 92} 93 94/// updateGlobalMapping - Replace an existing mapping for GV with a new 95/// address. This updates both maps as required. If "Addr" is null, the 96/// entry for the global is removed from the mappings. 97void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 98 MutexGuard locked(lock); 99 100 // Deleting from the mapping? 101 if (Addr == 0) { 102 state.getGlobalAddressMap(locked).erase(GV); 103 if (!state.getGlobalAddressReverseMap(locked).empty()) 104 state.getGlobalAddressReverseMap(locked).erase(Addr); 105 return; 106 } 107 108 void *&CurVal = state.getGlobalAddressMap(locked)[GV]; 109 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty()) 110 state.getGlobalAddressReverseMap(locked).erase(CurVal); 111 CurVal = Addr; 112 113 // If we are using the reverse mapping, add it too 114 if (!state.getGlobalAddressReverseMap(locked).empty()) { 115 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr]; 116 assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 117 V = GV; 118 } 119} 120 121/// getPointerToGlobalIfAvailable - This returns the address of the specified 122/// global value if it is has already been codegen'd, otherwise it returns null. 123/// 124void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 125 MutexGuard locked(lock); 126 127 std::map<const GlobalValue*, void*>::iterator I = 128 state.getGlobalAddressMap(locked).find(GV); 129 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0; 130} 131 132/// getGlobalValueAtAddress - Return the LLVM global value object that starts 133/// at the specified address. 134/// 135const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 136 MutexGuard locked(lock); 137 138 // If we haven't computed the reverse mapping yet, do so first. 139 if (state.getGlobalAddressReverseMap(locked).empty()) { 140 for (std::map<const GlobalValue*, void *>::iterator 141 I = state.getGlobalAddressMap(locked).begin(), 142 E = state.getGlobalAddressMap(locked).end(); I != E; ++I) 143 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, 144 I->first)); 145 } 146 147 std::map<void *, const GlobalValue*>::iterator I = 148 state.getGlobalAddressReverseMap(locked).find(Addr); 149 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0; 150} 151 152// CreateArgv - Turn a vector of strings into a nice argv style array of 153// pointers to null terminated strings. 154// 155static void *CreateArgv(ExecutionEngine *EE, 156 const std::vector<std::string> &InputArgv) { 157 unsigned PtrSize = EE->getTargetData()->getPointerSize(); 158 char *Result = new char[(InputArgv.size()+1)*PtrSize]; 159 160 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n"); 161 const Type *SBytePtr = PointerType::get(Type::SByteTy); 162 163 for (unsigned i = 0; i != InputArgv.size(); ++i) { 164 unsigned Size = InputArgv[i].size()+1; 165 char *Dest = new char[Size]; 166 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n"); 167 168 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 169 Dest[Size-1] = 0; 170 171 // Endian safe: Result[i] = (PointerTy)Dest; 172 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize), 173 SBytePtr); 174 } 175 176 // Null terminate it 177 EE->StoreValueToMemory(PTOGV(0), 178 (GenericValue*)(Result+InputArgv.size()*PtrSize), 179 SBytePtr); 180 return Result; 181} 182 183 184/// runStaticConstructorsDestructors - This method is used to execute all of 185/// the static constructors or destructors for a program, depending on the 186/// value of isDtors. 187void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 188 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 189 190 // Execute global ctors/dtors for each module in the program. 191 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 192 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name); 193 194 // If this global has internal linkage, or if it has a use, then it must be 195 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 196 // this is the case, don't execute any of the global ctors, __main will do 197 // it. 198 if (!GV || GV->isExternal() || GV->hasInternalLinkage()) continue; 199 200 // Should be an array of '{ int, void ()* }' structs. The first value is 201 // the init priority, which we ignore. 202 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 203 if (!InitList) continue; 204 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 205 if (ConstantStruct *CS = 206 dyn_cast<ConstantStruct>(InitList->getOperand(i))) { 207 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs. 208 209 Constant *FP = CS->getOperand(1); 210 if (FP->isNullValue()) 211 break; // Found a null terminator, exit. 212 213 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 214 if (CE->getOpcode() == Instruction::Cast) 215 FP = CE->getOperand(0); 216 if (Function *F = dyn_cast<Function>(FP)) { 217 // Execute the ctor/dtor function! 218 runFunction(F, std::vector<GenericValue>()); 219 } 220 } 221 } 222} 223 224/// runFunctionAsMain - This is a helper function which wraps runFunction to 225/// handle the common task of starting up main with the specified argc, argv, 226/// and envp parameters. 227int ExecutionEngine::runFunctionAsMain(Function *Fn, 228 const std::vector<std::string> &argv, 229 const char * const * envp) { 230 std::vector<GenericValue> GVArgs; 231 GenericValue GVArgc; 232 GVArgc.IntVal = argv.size(); 233 unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 234 if (NumArgs) { 235 GVArgs.push_back(GVArgc); // Arg #0 = argc. 236 if (NumArgs > 1) { 237 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv. 238 assert(((char **)GVTOP(GVArgs[1]))[0] && 239 "argv[0] was null after CreateArgv"); 240 if (NumArgs > 2) { 241 std::vector<std::string> EnvVars; 242 for (unsigned i = 0; envp[i]; ++i) 243 EnvVars.push_back(envp[i]); 244 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp. 245 } 246 } 247 } 248 return runFunction(Fn, GVArgs).IntVal; 249} 250 251/// If possible, create a JIT, unless the caller specifically requests an 252/// Interpreter or there's an error. If even an Interpreter cannot be created, 253/// NULL is returned. 254/// 255ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP, 256 bool ForceInterpreter) { 257 ExecutionEngine *EE = 0; 258 259 // Unless the interpreter was explicitly selected, try making a JIT. 260 if (!ForceInterpreter && JITCtor) 261 EE = JITCtor(MP); 262 263 // If we can't make a JIT, make an interpreter instead. 264 if (EE == 0 && InterpCtor) 265 EE = InterpCtor(MP); 266 267 if (EE) { 268 // Make sure we can resolve symbols in the program as well. The zero arg 269 // to the function tells DynamicLibrary to load the program, not a library. 270 try { 271 sys::DynamicLibrary::LoadLibraryPermanently(0); 272 } catch (...) { 273 } 274 } 275 276 return EE; 277} 278 279/// getPointerToGlobal - This returns the address of the specified global 280/// value. This may involve code generation if it's a function. 281/// 282void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 283 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 284 return getPointerToFunction(F); 285 286 MutexGuard locked(lock); 287 void *p = state.getGlobalAddressMap(locked)[GV]; 288 if (p) 289 return p; 290 291 // Global variable might have been added since interpreter started. 292 if (GlobalVariable *GVar = 293 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 294 EmitGlobalVariable(GVar); 295 else 296 assert("Global hasn't had an address allocated yet!"); 297 return state.getGlobalAddressMap(locked)[GV]; 298} 299 300/// FIXME: document 301/// 302GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 303 GenericValue Result; 304 if (isa<UndefValue>(C)) return Result; 305 306 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) { 307 switch (CE->getOpcode()) { 308 case Instruction::GetElementPtr: { 309 Result = getConstantValue(CE->getOperand(0)); 310 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end()); 311 uint64_t Offset = 312 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes); 313 314 if (getTargetData()->getPointerSize() == 4) 315 Result.IntVal += Offset; 316 else 317 Result.LongVal += Offset; 318 return Result; 319 } 320 case Instruction::Cast: { 321 // We only need to handle a few cases here. Almost all casts will 322 // automatically fold, just the ones involving pointers won't. 323 // 324 Constant *Op = CE->getOperand(0); 325 GenericValue GV = getConstantValue(Op); 326 327 // Handle cast of pointer to pointer... 328 if (Op->getType()->getTypeID() == C->getType()->getTypeID()) 329 return GV; 330 331 // Handle a cast of pointer to any integral type... 332 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral()) 333 return GV; 334 335 // Handle cast of integer to a pointer... 336 if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral()) 337 switch (Op->getType()->getTypeID()) { 338 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal); 339 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal); 340 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal); 341 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal); 342 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal); 343 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal); 344 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal); 345 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal); 346 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal); 347 default: assert(0 && "Unknown integral type!"); 348 } 349 break; 350 } 351 352 case Instruction::Add: 353 switch (CE->getOperand(0)->getType()->getTypeID()) { 354 default: assert(0 && "Bad add type!"); abort(); 355 case Type::LongTyID: 356 case Type::ULongTyID: 357 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal + 358 getConstantValue(CE->getOperand(1)).LongVal; 359 break; 360 case Type::IntTyID: 361 case Type::UIntTyID: 362 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal + 363 getConstantValue(CE->getOperand(1)).IntVal; 364 break; 365 case Type::ShortTyID: 366 case Type::UShortTyID: 367 Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal + 368 getConstantValue(CE->getOperand(1)).ShortVal; 369 break; 370 case Type::SByteTyID: 371 case Type::UByteTyID: 372 Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal + 373 getConstantValue(CE->getOperand(1)).SByteVal; 374 break; 375 case Type::FloatTyID: 376 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal + 377 getConstantValue(CE->getOperand(1)).FloatVal; 378 break; 379 case Type::DoubleTyID: 380 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal + 381 getConstantValue(CE->getOperand(1)).DoubleVal; 382 break; 383 } 384 return Result; 385 default: 386 break; 387 } 388 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n"; 389 abort(); 390 } 391 392 switch (C->getType()->getTypeID()) { 393#define GET_CONST_VAL(TY, CTY, CLASS, GETMETH) \ 394 case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->GETMETH(); break 395 GET_CONST_VAL(Bool , bool , ConstantBool, getValue); 396 GET_CONST_VAL(UByte , unsigned char , ConstantInt, getZExtValue); 397 GET_CONST_VAL(SByte , signed char , ConstantInt, getSExtValue); 398 GET_CONST_VAL(UShort , unsigned short, ConstantInt, getZExtValue); 399 GET_CONST_VAL(Short , signed short , ConstantInt, getSExtValue); 400 GET_CONST_VAL(UInt , unsigned int , ConstantInt, getZExtValue); 401 GET_CONST_VAL(Int , signed int , ConstantInt, getSExtValue); 402 GET_CONST_VAL(ULong , uint64_t , ConstantInt, getZExtValue); 403 GET_CONST_VAL(Long , int64_t , ConstantInt, getSExtValue); 404 GET_CONST_VAL(Float , float , ConstantFP, getValue); 405 GET_CONST_VAL(Double , double , ConstantFP, getValue); 406#undef GET_CONST_VAL 407 case Type::PointerTyID: 408 if (isa<ConstantPointerNull>(C)) 409 Result.PointerVal = 0; 410 else if (const Function *F = dyn_cast<Function>(C)) 411 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 412 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C)) 413 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 414 else 415 assert(0 && "Unknown constant pointer type!"); 416 break; 417 default: 418 std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n"; 419 abort(); 420 } 421 return Result; 422} 423 424/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr 425/// is the address of the memory at which to store Val, cast to GenericValue *. 426/// It is not a pointer to a GenericValue containing the address at which to 427/// store Val. 428/// 429void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr, 430 const Type *Ty) { 431 if (getTargetData()->isLittleEndian()) { 432 switch (Ty->getTypeID()) { 433 case Type::BoolTyID: 434 case Type::UByteTyID: 435 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break; 436 case Type::UShortTyID: 437 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255; 438 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255; 439 break; 440 Store4BytesLittleEndian: 441 case Type::FloatTyID: 442 case Type::UIntTyID: 443 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255; 444 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255; 445 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255; 446 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255; 447 break; 448 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4) 449 goto Store4BytesLittleEndian; 450 case Type::DoubleTyID: 451 case Type::ULongTyID: 452 case Type::LongTyID: 453 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal ); 454 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 8); 455 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16); 456 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24); 457 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32); 458 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40); 459 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48); 460 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56); 461 break; 462 default: 463 std::cout << "Cannot store value of type " << *Ty << "!\n"; 464 } 465 } else { 466 switch (Ty->getTypeID()) { 467 case Type::BoolTyID: 468 case Type::UByteTyID: 469 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break; 470 case Type::UShortTyID: 471 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255; 472 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255; 473 break; 474 Store4BytesBigEndian: 475 case Type::FloatTyID: 476 case Type::UIntTyID: 477 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255; 478 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255; 479 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255; 480 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255; 481 break; 482 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4) 483 goto Store4BytesBigEndian; 484 case Type::DoubleTyID: 485 case Type::ULongTyID: 486 case Type::LongTyID: 487 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal ); 488 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 8); 489 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16); 490 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24); 491 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32); 492 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40); 493 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48); 494 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56); 495 break; 496 default: 497 std::cout << "Cannot store value of type " << *Ty << "!\n"; 498 } 499 } 500} 501 502/// FIXME: document 503/// 504GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr, 505 const Type *Ty) { 506 GenericValue Result; 507 if (getTargetData()->isLittleEndian()) { 508 switch (Ty->getTypeID()) { 509 case Type::BoolTyID: 510 case Type::UByteTyID: 511 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break; 512 case Type::UShortTyID: 513 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] | 514 ((unsigned)Ptr->Untyped[1] << 8); 515 break; 516 Load4BytesLittleEndian: 517 case Type::FloatTyID: 518 case Type::UIntTyID: 519 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] | 520 ((unsigned)Ptr->Untyped[1] << 8) | 521 ((unsigned)Ptr->Untyped[2] << 16) | 522 ((unsigned)Ptr->Untyped[3] << 24); 523 break; 524 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4) 525 goto Load4BytesLittleEndian; 526 case Type::DoubleTyID: 527 case Type::ULongTyID: 528 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] | 529 ((uint64_t)Ptr->Untyped[1] << 8) | 530 ((uint64_t)Ptr->Untyped[2] << 16) | 531 ((uint64_t)Ptr->Untyped[3] << 24) | 532 ((uint64_t)Ptr->Untyped[4] << 32) | 533 ((uint64_t)Ptr->Untyped[5] << 40) | 534 ((uint64_t)Ptr->Untyped[6] << 48) | 535 ((uint64_t)Ptr->Untyped[7] << 56); 536 break; 537 default: 538 std::cout << "Cannot load value of type " << *Ty << "!\n"; 539 abort(); 540 } 541 } else { 542 switch (Ty->getTypeID()) { 543 case Type::BoolTyID: 544 case Type::UByteTyID: 545 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break; 546 case Type::UShortTyID: 547 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] | 548 ((unsigned)Ptr->Untyped[0] << 8); 549 break; 550 Load4BytesBigEndian: 551 case Type::FloatTyID: 552 case Type::UIntTyID: 553 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] | 554 ((unsigned)Ptr->Untyped[2] << 8) | 555 ((unsigned)Ptr->Untyped[1] << 16) | 556 ((unsigned)Ptr->Untyped[0] << 24); 557 break; 558 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4) 559 goto Load4BytesBigEndian; 560 case Type::DoubleTyID: 561 case Type::ULongTyID: 562 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] | 563 ((uint64_t)Ptr->Untyped[6] << 8) | 564 ((uint64_t)Ptr->Untyped[5] << 16) | 565 ((uint64_t)Ptr->Untyped[4] << 24) | 566 ((uint64_t)Ptr->Untyped[3] << 32) | 567 ((uint64_t)Ptr->Untyped[2] << 40) | 568 ((uint64_t)Ptr->Untyped[1] << 48) | 569 ((uint64_t)Ptr->Untyped[0] << 56); 570 break; 571 default: 572 std::cout << "Cannot load value of type " << *Ty << "!\n"; 573 abort(); 574 } 575 } 576 return Result; 577} 578 579// InitializeMemory - Recursive function to apply a Constant value into the 580// specified memory location... 581// 582void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 583 if (isa<UndefValue>(Init)) { 584 return; 585 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) { 586 unsigned ElementSize = 587 getTargetData()->getTypeSize(CP->getType()->getElementType()); 588 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 589 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 590 return; 591 } else if (Init->getType()->isFirstClassType()) { 592 GenericValue Val = getConstantValue(Init); 593 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 594 return; 595 } else if (isa<ConstantAggregateZero>(Init)) { 596 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType())); 597 return; 598 } 599 600 switch (Init->getType()->getTypeID()) { 601 case Type::ArrayTyID: { 602 const ConstantArray *CPA = cast<ConstantArray>(Init); 603 unsigned ElementSize = 604 getTargetData()->getTypeSize(CPA->getType()->getElementType()); 605 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 606 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 607 return; 608 } 609 610 case Type::StructTyID: { 611 const ConstantStruct *CPS = cast<ConstantStruct>(Init); 612 const StructLayout *SL = 613 getTargetData()->getStructLayout(cast<StructType>(CPS->getType())); 614 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 615 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]); 616 return; 617 } 618 619 default: 620 std::cerr << "Bad Type: " << *Init->getType() << "\n"; 621 assert(0 && "Unknown constant type to initialize memory with!"); 622 } 623} 624 625/// EmitGlobals - Emit all of the global variables to memory, storing their 626/// addresses into GlobalAddress. This must make sure to copy the contents of 627/// their initializers into the memory. 628/// 629void ExecutionEngine::emitGlobals() { 630 const TargetData *TD = getTargetData(); 631 632 // Loop over all of the global variables in the program, allocating the memory 633 // to hold them. If there is more than one module, do a prepass over globals 634 // to figure out how the different modules should link together. 635 // 636 std::map<std::pair<std::string, const Type*>, 637 const GlobalValue*> LinkedGlobalsMap; 638 639 if (Modules.size() != 1) { 640 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 641 Module &M = *Modules[m]->getModule(); 642 for (Module::const_global_iterator I = M.global_begin(), 643 E = M.global_end(); I != E; ++I) { 644 const GlobalValue *GV = I; 645 if (GV->hasInternalLinkage() || GV->isExternal() || 646 GV->hasAppendingLinkage() || !GV->hasName()) 647 continue;// Ignore external globals and globals with internal linkage. 648 649 const GlobalValue *&GVEntry = 650 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 651 652 // If this is the first time we've seen this global, it is the canonical 653 // version. 654 if (!GVEntry) { 655 GVEntry = GV; 656 continue; 657 } 658 659 // If the existing global is strong, never replace it. 660 if (GVEntry->hasExternalLinkage() || 661 GVEntry->hasDLLImportLinkage() || 662 GVEntry->hasDLLExportLinkage()) 663 continue; 664 665 // Otherwise, we know it's linkonce/weak, replace it if this is a strong 666 // symbol. 667 if (GV->hasExternalLinkage()) 668 GVEntry = GV; 669 } 670 } 671 } 672 673 std::vector<const GlobalValue*> NonCanonicalGlobals; 674 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 675 Module &M = *Modules[m]->getModule(); 676 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 677 I != E; ++I) { 678 // In the multi-module case, see what this global maps to. 679 if (!LinkedGlobalsMap.empty()) { 680 if (const GlobalValue *GVEntry = 681 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) { 682 // If something else is the canonical global, ignore this one. 683 if (GVEntry != &*I) { 684 NonCanonicalGlobals.push_back(I); 685 continue; 686 } 687 } 688 } 689 690 if (!I->isExternal()) { 691 // Get the type of the global. 692 const Type *Ty = I->getType()->getElementType(); 693 694 // Allocate some memory for it! 695 unsigned Size = TD->getTypeSize(Ty); 696 addGlobalMapping(I, new char[Size]); 697 } else { 698 // External variable reference. Try to use the dynamic loader to 699 // get a pointer to it. 700 if (void *SymAddr = 701 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str())) 702 addGlobalMapping(I, SymAddr); 703 else { 704 std::cerr << "Could not resolve external global address: " 705 << I->getName() << "\n"; 706 abort(); 707 } 708 } 709 } 710 711 // If there are multiple modules, map the non-canonical globals to their 712 // canonical location. 713 if (!NonCanonicalGlobals.empty()) { 714 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 715 const GlobalValue *GV = NonCanonicalGlobals[i]; 716 const GlobalValue *CGV = 717 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 718 void *Ptr = getPointerToGlobalIfAvailable(CGV); 719 assert(Ptr && "Canonical global wasn't codegen'd!"); 720 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV)); 721 } 722 } 723 724 // Now that all of the globals are set up in memory, loop through them all and 725 // initialize their contents. 726 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 727 I != E; ++I) { 728 if (!I->isExternal()) { 729 if (!LinkedGlobalsMap.empty()) { 730 if (const GlobalValue *GVEntry = 731 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) 732 if (GVEntry != &*I) // Not the canonical variable. 733 continue; 734 } 735 EmitGlobalVariable(I); 736 } 737 } 738 } 739} 740 741// EmitGlobalVariable - This method emits the specified global variable to the 742// address specified in GlobalAddresses, or allocates new memory if it's not 743// already in the map. 744void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 745 void *GA = getPointerToGlobalIfAvailable(GV); 746 DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n"); 747 748 const Type *ElTy = GV->getType()->getElementType(); 749 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy); 750 if (GA == 0) { 751 // If it's not already specified, allocate memory for the global. 752 GA = new char[GVSize]; 753 addGlobalMapping(GV, GA); 754 } 755 756 InitializeMemory(GV->getInitializer(), GA); 757 NumInitBytes += (unsigned)GVSize; 758 ++NumGlobals; 759} 760