1857c21b4SMisha Brukman //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===// 2996fe010SChris Lattner // 3482202a6SJohn Criswell // The LLVM Compiler Infrastructure 4482202a6SJohn Criswell // 5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source 6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details. 7482202a6SJohn Criswell // 8482202a6SJohn Criswell //===----------------------------------------------------------------------===// 9482202a6SJohn Criswell // 10996fe010SChris Lattner // This file defines the common interface used by the various execution engine 11996fe010SChris Lattner // subclasses. 12996fe010SChris Lattner // 13996fe010SChris Lattner //===----------------------------------------------------------------------===// 14996fe010SChris Lattner 15ee937c80SChris Lattner #define DEBUG_TYPE "jit" 166bf87df5SJeffrey Yasskin #include "llvm/ExecutionEngine/ExecutionEngine.h" 179bc53e84SFilip Pizlo #include "llvm/ExecutionEngine/JITMemoryManager.h" 18868e3f09SDaniel Dunbar #include "llvm/ADT/SmallString.h" 19390d78b3SChris Lattner #include "llvm/ADT/Statistic.h" 20ed0881b2SChandler Carruth #include "llvm/ExecutionEngine/GenericValue.h" 219fb823bbSChandler Carruth #include "llvm/IR/Constants.h" 229fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h" 239fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h" 249fb823bbSChandler Carruth #include "llvm/IR/Module.h" 259fb823bbSChandler Carruth #include "llvm/IR/Operator.h" 267c16caa3SReid Spencer #include "llvm/Support/Debug.h" 27ed0881b2SChandler Carruth #include "llvm/Support/DynamicLibrary.h" 286c2d233eSTorok Edwin #include "llvm/Support/ErrorHandling.h" 29ed0881b2SChandler Carruth #include "llvm/Support/Host.h" 306d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h" 31ed0881b2SChandler Carruth #include "llvm/Support/TargetRegistry.h" 326bf87df5SJeffrey Yasskin #include "llvm/Support/ValueHandle.h" 33ccb29cd2STorok Edwin #include "llvm/Support/raw_ostream.h" 348418fdcdSDylan Noblesmith #include "llvm/Target/TargetMachine.h" 35579f0713SAnton Korobeynikov #include <cmath> 36579f0713SAnton Korobeynikov #include <cstring> 3729681deeSChris Lattner using namespace llvm; 38996fe010SChris Lattner 39c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 40c346ecd7SChris Lattner STATISTIC(NumGlobals , "Number of global vars initialized"); 41996fe010SChris Lattner 4231faefffSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::JITCtor)( 4331faefffSJeffrey Yasskin Module *M, 44fc8a2d5aSReid Kleckner std::string *ErrorStr, 45fc8a2d5aSReid Kleckner JITMemoryManager *JMM, 46700d08e1SEric Christopher bool GVsWithCode, 478418fdcdSDylan Noblesmith TargetMachine *TM) = 0; 4870ff8b05SDaniel Dunbar ExecutionEngine *(*ExecutionEngine::MCJITCtor)( 4970ff8b05SDaniel Dunbar Module *M, 5070ff8b05SDaniel Dunbar std::string *ErrorStr, 519bc53e84SFilip Pizlo RTDyldMemoryManager *MCJMM, 5270ff8b05SDaniel Dunbar bool GVsWithCode, 538418fdcdSDylan Noblesmith TargetMachine *TM) = 0; 54091217beSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M, 55fc8a2d5aSReid Kleckner std::string *ErrorStr) = 0; 562d52c1b8SChris Lattner 57091217beSJeffrey Yasskin ExecutionEngine::ExecutionEngine(Module *M) 58f98e981cSJeffrey Yasskin : EEState(*this), 59*7ef22b84SRafael Espindola LazyFunctionCreator(0) { 604567db45SJeffrey Yasskin CompilingLazily = false; 61cdc0060eSEvan Cheng GVCompilationDisabled = false; 6284a9055eSEvan Cheng SymbolSearchingDisabled = false; 63091217beSJeffrey Yasskin Modules.push_back(M); 64091217beSJeffrey Yasskin assert(M && "Module is null?"); 65260b0c88SMisha Brukman } 66260b0c88SMisha Brukman 6792f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() { 68603682adSReid Spencer clearAllGlobalMappings(); 690621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) 700621caefSChris Lattner delete Modules[i]; 7192f8b30dSBrian Gaeke } 7292f8b30dSBrian Gaeke 73a4044332SJeffrey Yasskin namespace { 74868e3f09SDaniel Dunbar /// \brief Helper class which uses a value handler to automatically deletes the 75868e3f09SDaniel Dunbar /// memory block when the GlobalVariable is destroyed. 76a4044332SJeffrey Yasskin class GVMemoryBlock : public CallbackVH { 77a4044332SJeffrey Yasskin GVMemoryBlock(const GlobalVariable *GV) 78a4044332SJeffrey Yasskin : CallbackVH(const_cast<GlobalVariable*>(GV)) {} 79a4044332SJeffrey Yasskin 80a4044332SJeffrey Yasskin public: 81868e3f09SDaniel Dunbar /// \brief Returns the address the GlobalVariable should be written into. The 82868e3f09SDaniel Dunbar /// GVMemoryBlock object prefixes that. 83cdfe20b9SMicah Villmow static char *Create(const GlobalVariable *GV, const DataLayout& TD) { 84229907cdSChris Lattner Type *ElTy = GV->getType()->getElementType(); 85a4044332SJeffrey Yasskin size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy); 86a4044332SJeffrey Yasskin void *RawMemory = ::operator new( 87cdfe20b9SMicah Villmow DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock), 88a4044332SJeffrey Yasskin TD.getPreferredAlignment(GV)) 89a4044332SJeffrey Yasskin + GVSize); 90a4044332SJeffrey Yasskin new(RawMemory) GVMemoryBlock(GV); 91a4044332SJeffrey Yasskin return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock); 92a4044332SJeffrey Yasskin } 93a4044332SJeffrey Yasskin 94a4044332SJeffrey Yasskin virtual void deleted() { 95a4044332SJeffrey Yasskin // We allocated with operator new and with some extra memory hanging off the 96a4044332SJeffrey Yasskin // end, so don't just delete this. I'm not sure if this is actually 97a4044332SJeffrey Yasskin // required. 98a4044332SJeffrey Yasskin this->~GVMemoryBlock(); 99a4044332SJeffrey Yasskin ::operator delete(this); 100a4044332SJeffrey Yasskin } 101a4044332SJeffrey Yasskin }; 102a4044332SJeffrey Yasskin } // anonymous namespace 103a4044332SJeffrey Yasskin 104a4044332SJeffrey Yasskin char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) { 105cdfe20b9SMicah Villmow return GVMemoryBlock::Create(GV, *getDataLayout()); 1065457ce9aSNicolas Geoffray } 1075457ce9aSNicolas Geoffray 108091217beSJeffrey Yasskin bool ExecutionEngine::removeModule(Module *M) { 109af0dea13SCraig Topper for(SmallVectorImpl<Module *>::iterator I = Modules.begin(), 110324fe890SDevang Patel E = Modules.end(); I != E; ++I) { 111091217beSJeffrey Yasskin Module *Found = *I; 112091217beSJeffrey Yasskin if (Found == M) { 113324fe890SDevang Patel Modules.erase(I); 114091217beSJeffrey Yasskin clearGlobalMappingsFromModule(M); 115091217beSJeffrey Yasskin return true; 116324fe890SDevang Patel } 117324fe890SDevang Patel } 118091217beSJeffrey Yasskin return false; 119617001d8SNate Begeman } 120617001d8SNate Begeman 1210621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 1220621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 123091217beSJeffrey Yasskin if (Function *F = Modules[i]->getFunction(FnName)) 1240621caefSChris Lattner return F; 1250621caefSChris Lattner } 1260621caefSChris Lattner return 0; 1270621caefSChris Lattner } 1280621caefSChris Lattner 1290621caefSChris Lattner 130868e3f09SDaniel Dunbar void *ExecutionEngineState::RemoveMapping(const MutexGuard &, 131868e3f09SDaniel Dunbar const GlobalValue *ToUnmap) { 132d0fc8f80SJeffrey Yasskin GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap); 133307c053fSJeffrey Yasskin void *OldVal; 134868e3f09SDaniel Dunbar 135868e3f09SDaniel Dunbar // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the 136868e3f09SDaniel Dunbar // GlobalAddressMap. 137307c053fSJeffrey Yasskin if (I == GlobalAddressMap.end()) 138307c053fSJeffrey Yasskin OldVal = 0; 139307c053fSJeffrey Yasskin else { 140307c053fSJeffrey Yasskin OldVal = I->second; 141307c053fSJeffrey Yasskin GlobalAddressMap.erase(I); 142307c053fSJeffrey Yasskin } 143307c053fSJeffrey Yasskin 144307c053fSJeffrey Yasskin GlobalAddressReverseMap.erase(OldVal); 145307c053fSJeffrey Yasskin return OldVal; 146307c053fSJeffrey Yasskin } 147307c053fSJeffrey Yasskin 1486d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 1496d8dd189SChris Lattner MutexGuard locked(lock); 1506d8dd189SChris Lattner 1510967d2dfSDavid Greene DEBUG(dbgs() << "JIT: Map \'" << GV->getName() 1529813b0b0SDaniel Dunbar << "\' to [" << Addr << "]\n";); 153d0fc8f80SJeffrey Yasskin void *&CurVal = EEState.getGlobalAddressMap(locked)[GV]; 1546d8dd189SChris Lattner assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!"); 1556d8dd189SChris Lattner CurVal = Addr; 1566d8dd189SChris Lattner 157868e3f09SDaniel Dunbar // If we are using the reverse mapping, add it too. 158f98e981cSJeffrey Yasskin if (!EEState.getGlobalAddressReverseMap(locked).empty()) { 1596bf87df5SJeffrey Yasskin AssertingVH<const GlobalValue> &V = 160f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked)[Addr]; 1616d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 1626d8dd189SChris Lattner V = GV; 1636d8dd189SChris Lattner } 1646d8dd189SChris Lattner } 1656d8dd189SChris Lattner 1666d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() { 1676d8dd189SChris Lattner MutexGuard locked(lock); 1686d8dd189SChris Lattner 169f98e981cSJeffrey Yasskin EEState.getGlobalAddressMap(locked).clear(); 170f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked).clear(); 1716d8dd189SChris Lattner } 1726d8dd189SChris Lattner 1738f83fc4dSNate Begeman void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) { 1748f83fc4dSNate Begeman MutexGuard locked(lock); 1758f83fc4dSNate Begeman 176868e3f09SDaniel Dunbar for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) 177f98e981cSJeffrey Yasskin EEState.RemoveMapping(locked, FI); 1788f83fc4dSNate Begeman for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 179868e3f09SDaniel Dunbar GI != GE; ++GI) 180f98e981cSJeffrey Yasskin EEState.RemoveMapping(locked, GI); 1818f83fc4dSNate Begeman } 1828f83fc4dSNate Begeman 183ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 1846d8dd189SChris Lattner MutexGuard locked(lock); 1856d8dd189SChris Lattner 186d0fc8f80SJeffrey Yasskin ExecutionEngineState::GlobalAddressMapTy &Map = 187f98e981cSJeffrey Yasskin EEState.getGlobalAddressMap(locked); 188ee181730SChris Lattner 1896d8dd189SChris Lattner // Deleting from the mapping? 190868e3f09SDaniel Dunbar if (Addr == 0) 191f98e981cSJeffrey Yasskin return EEState.RemoveMapping(locked, GV); 192ee181730SChris Lattner 193d0fc8f80SJeffrey Yasskin void *&CurVal = Map[GV]; 194ee181730SChris Lattner void *OldVal = CurVal; 195ee181730SChris Lattner 196f98e981cSJeffrey Yasskin if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty()) 197f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked).erase(CurVal); 1986d8dd189SChris Lattner CurVal = Addr; 1996d8dd189SChris Lattner 200868e3f09SDaniel Dunbar // If we are using the reverse mapping, add it too. 201f98e981cSJeffrey Yasskin if (!EEState.getGlobalAddressReverseMap(locked).empty()) { 2026bf87df5SJeffrey Yasskin AssertingVH<const GlobalValue> &V = 203f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked)[Addr]; 2046d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 2056d8dd189SChris Lattner V = GV; 2066d8dd189SChris Lattner } 207ee181730SChris Lattner return OldVal; 2086d8dd189SChris Lattner } 2096d8dd189SChris Lattner 2106d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 2116d8dd189SChris Lattner MutexGuard locked(lock); 2126d8dd189SChris Lattner 213d0fc8f80SJeffrey Yasskin ExecutionEngineState::GlobalAddressMapTy::iterator I = 214d0fc8f80SJeffrey Yasskin EEState.getGlobalAddressMap(locked).find(GV); 215f98e981cSJeffrey Yasskin return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0; 2166d8dd189SChris Lattner } 2176d8dd189SChris Lattner 218748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 21979876f52SReid Spencer MutexGuard locked(lock); 22079876f52SReid Spencer 221748e8579SChris Lattner // If we haven't computed the reverse mapping yet, do so first. 222f98e981cSJeffrey Yasskin if (EEState.getGlobalAddressReverseMap(locked).empty()) { 223d0fc8f80SJeffrey Yasskin for (ExecutionEngineState::GlobalAddressMapTy::iterator 224f98e981cSJeffrey Yasskin I = EEState.getGlobalAddressMap(locked).begin(), 225f98e981cSJeffrey Yasskin E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I) 226e4f47434SDaniel Dunbar EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair( 227e4f47434SDaniel Dunbar I->second, I->first)); 228748e8579SChris Lattner } 229748e8579SChris Lattner 2306bf87df5SJeffrey Yasskin std::map<void *, AssertingVH<const GlobalValue> >::iterator I = 231f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked).find(Addr); 232f98e981cSJeffrey Yasskin return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0; 233748e8579SChris Lattner } 2345a0d4829SChris Lattner 235bfd38abbSJeffrey Yasskin namespace { 236bfd38abbSJeffrey Yasskin class ArgvArray { 237bfd38abbSJeffrey Yasskin char *Array; 238bfd38abbSJeffrey Yasskin std::vector<char*> Values; 239bfd38abbSJeffrey Yasskin public: 240bfd38abbSJeffrey Yasskin ArgvArray() : Array(NULL) {} 241bfd38abbSJeffrey Yasskin ~ArgvArray() { clear(); } 242bfd38abbSJeffrey Yasskin void clear() { 243bfd38abbSJeffrey Yasskin delete[] Array; 244bfd38abbSJeffrey Yasskin Array = NULL; 245bfd38abbSJeffrey Yasskin for (size_t I = 0, E = Values.size(); I != E; ++I) { 246bfd38abbSJeffrey Yasskin delete[] Values[I]; 247bfd38abbSJeffrey Yasskin } 248bfd38abbSJeffrey Yasskin Values.clear(); 249bfd38abbSJeffrey Yasskin } 250bfd38abbSJeffrey Yasskin /// Turn a vector of strings into a nice argv style array of pointers to null 251bfd38abbSJeffrey Yasskin /// terminated strings. 252bfd38abbSJeffrey Yasskin void *reset(LLVMContext &C, ExecutionEngine *EE, 253bfd38abbSJeffrey Yasskin const std::vector<std::string> &InputArgv); 254bfd38abbSJeffrey Yasskin }; 255bfd38abbSJeffrey Yasskin } // anonymous namespace 256bfd38abbSJeffrey Yasskin void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE, 2575a0d4829SChris Lattner const std::vector<std::string> &InputArgv) { 258bfd38abbSJeffrey Yasskin clear(); // Free the old contents. 2595da3f051SChandler Carruth unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 260bfd38abbSJeffrey Yasskin Array = new char[(InputArgv.size()+1)*PtrSize]; 2615a0d4829SChris Lattner 262bfd38abbSJeffrey Yasskin DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n"); 263229907cdSChris Lattner Type *SBytePtr = Type::getInt8PtrTy(C); 2645a0d4829SChris Lattner 2655a0d4829SChris Lattner for (unsigned i = 0; i != InputArgv.size(); ++i) { 2665a0d4829SChris Lattner unsigned Size = InputArgv[i].size()+1; 2675a0d4829SChris Lattner char *Dest = new char[Size]; 268bfd38abbSJeffrey Yasskin Values.push_back(Dest); 2690967d2dfSDavid Greene DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n"); 2705a0d4829SChris Lattner 2715a0d4829SChris Lattner std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 2725a0d4829SChris Lattner Dest[Size-1] = 0; 2735a0d4829SChris Lattner 274bfd38abbSJeffrey Yasskin // Endian safe: Array[i] = (PointerTy)Dest; 275bfd38abbSJeffrey Yasskin EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize), 2765a0d4829SChris Lattner SBytePtr); 2775a0d4829SChris Lattner } 2785a0d4829SChris Lattner 2795a0d4829SChris Lattner // Null terminate it 2805a0d4829SChris Lattner EE->StoreValueToMemory(PTOGV(0), 281bfd38abbSJeffrey Yasskin (GenericValue*)(Array+InputArgv.size()*PtrSize), 2825a0d4829SChris Lattner SBytePtr); 283bfd38abbSJeffrey Yasskin return Array; 2845a0d4829SChris Lattner } 2855a0d4829SChris Lattner 28641fa2bd1SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(Module *module, 28741fa2bd1SChris Lattner bool isDtors) { 288faae50b6SChris Lattner const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 2891a9a0b7bSEvan Cheng GlobalVariable *GV = module->getNamedGlobal(Name); 290fe36eaebSChris Lattner 291fe36eaebSChris Lattner // If this global has internal linkage, or if it has a use, then it must be 292fe36eaebSChris Lattner // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 2930621caefSChris Lattner // this is the case, don't execute any of the global ctors, __main will do 2940621caefSChris Lattner // it. 2956de96a1bSRafael Espindola if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return; 296faae50b6SChris Lattner 2970cbfcb2bSNick Lewycky // Should be an array of '{ i32, void ()* }' structs. The first value is 2980621caefSChris Lattner // the init priority, which we ignore. 29900245f42SChris Lattner ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 30000245f42SChris Lattner if (InitList == 0) 3010f857898SNick Lewycky return; 302868e3f09SDaniel Dunbar for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 30300245f42SChris Lattner ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i)); 30400245f42SChris Lattner if (CS == 0) continue; 305faae50b6SChris Lattner 306faae50b6SChris Lattner Constant *FP = CS->getOperand(1); 307faae50b6SChris Lattner if (FP->isNullValue()) 3080f857898SNick Lewycky continue; // Found a sentinal value, ignore. 309faae50b6SChris Lattner 310868e3f09SDaniel Dunbar // Strip off constant expression casts. 311faae50b6SChris Lattner if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 3126c38f0bbSReid Spencer if (CE->isCast()) 313faae50b6SChris Lattner FP = CE->getOperand(0); 314868e3f09SDaniel Dunbar 315faae50b6SChris Lattner // Execute the ctor/dtor function! 316868e3f09SDaniel Dunbar if (Function *F = dyn_cast<Function>(FP)) 317faae50b6SChris Lattner runFunction(F, std::vector<GenericValue>()); 318868e3f09SDaniel Dunbar 319868e3f09SDaniel Dunbar // FIXME: It is marginally lame that we just do nothing here if we see an 320868e3f09SDaniel Dunbar // entry we don't recognize. It might not be unreasonable for the verifier 321868e3f09SDaniel Dunbar // to not even allow this and just assert here. 322faae50b6SChris Lattner } 323faae50b6SChris Lattner } 3241a9a0b7bSEvan Cheng 3251a9a0b7bSEvan Cheng void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 3261a9a0b7bSEvan Cheng // Execute global ctors/dtors for each module in the program. 327868e3f09SDaniel Dunbar for (unsigned i = 0, e = Modules.size(); i != e; ++i) 328868e3f09SDaniel Dunbar runStaticConstructorsDestructors(Modules[i], isDtors); 3290621caefSChris Lattner } 330faae50b6SChris Lattner 331cf3e3017SDan Gohman #ifndef NDEBUG 3321202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null. 3331202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) { 3345da3f051SChandler Carruth unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 3351202d1b1SDuncan Sands for (unsigned i = 0; i < PtrSize; ++i) 3361202d1b1SDuncan Sands if (*(i + (uint8_t*)Loc)) 3371202d1b1SDuncan Sands return false; 3381202d1b1SDuncan Sands return true; 3391202d1b1SDuncan Sands } 340cf3e3017SDan Gohman #endif 3411202d1b1SDuncan Sands 3425a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn, 3435a0d4829SChris Lattner const std::vector<std::string> &argv, 3445a0d4829SChris Lattner const char * const * envp) { 3455a0d4829SChris Lattner std::vector<GenericValue> GVArgs; 3465a0d4829SChris Lattner GenericValue GVArgc; 34787aa65f4SReid Spencer GVArgc.IntVal = APInt(32, argv.size()); 3488c32c111SAnton Korobeynikov 3498c32c111SAnton Korobeynikov // Check main() type 350b1cad0b3SChris Lattner unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 351229907cdSChris Lattner FunctionType *FTy = Fn->getFunctionType(); 352229907cdSChris Lattner Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo(); 353868e3f09SDaniel Dunbar 354868e3f09SDaniel Dunbar // Check the argument types. 355868e3f09SDaniel Dunbar if (NumArgs > 3) 3562104b8d3SChris Lattner report_fatal_error("Invalid number of arguments of main() supplied"); 357868e3f09SDaniel Dunbar if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty) 358868e3f09SDaniel Dunbar report_fatal_error("Invalid type for third argument of main() supplied"); 359868e3f09SDaniel Dunbar if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty) 360868e3f09SDaniel Dunbar report_fatal_error("Invalid type for second argument of main() supplied"); 361868e3f09SDaniel Dunbar if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32)) 362868e3f09SDaniel Dunbar report_fatal_error("Invalid type for first argument of main() supplied"); 363868e3f09SDaniel Dunbar if (!FTy->getReturnType()->isIntegerTy() && 364868e3f09SDaniel Dunbar !FTy->getReturnType()->isVoidTy()) 365868e3f09SDaniel Dunbar report_fatal_error("Invalid return type of main() supplied"); 3668c32c111SAnton Korobeynikov 367bfd38abbSJeffrey Yasskin ArgvArray CArgv; 368bfd38abbSJeffrey Yasskin ArgvArray CEnv; 369b1cad0b3SChris Lattner if (NumArgs) { 3705a0d4829SChris Lattner GVArgs.push_back(GVArgc); // Arg #0 = argc. 371b1cad0b3SChris Lattner if (NumArgs > 1) { 37255f1c09eSOwen Anderson // Arg #1 = argv. 373bfd38abbSJeffrey Yasskin GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv))); 3741202d1b1SDuncan Sands assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) && 375b1cad0b3SChris Lattner "argv[0] was null after CreateArgv"); 376b1cad0b3SChris Lattner if (NumArgs > 2) { 3775a0d4829SChris Lattner std::vector<std::string> EnvVars; 3785a0d4829SChris Lattner for (unsigned i = 0; envp[i]; ++i) 3795a0d4829SChris Lattner EnvVars.push_back(envp[i]); 38055f1c09eSOwen Anderson // Arg #2 = envp. 381bfd38abbSJeffrey Yasskin GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars))); 382b1cad0b3SChris Lattner } 383b1cad0b3SChris Lattner } 384b1cad0b3SChris Lattner } 385868e3f09SDaniel Dunbar 38687aa65f4SReid Spencer return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 3875a0d4829SChris Lattner } 3885a0d4829SChris Lattner 389091217beSJeffrey Yasskin ExecutionEngine *ExecutionEngine::create(Module *M, 390603682adSReid Spencer bool ForceInterpreter, 3917ff05bf5SEvan Cheng std::string *ErrorStr, 39270415d97SJeffrey Yasskin CodeGenOpt::Level OptLevel, 39370415d97SJeffrey Yasskin bool GVsWithCode) { 394add6f1d2SOwen Anderson EngineBuilder EB = EngineBuilder(M) 395fc8a2d5aSReid Kleckner .setEngineKind(ForceInterpreter 396fc8a2d5aSReid Kleckner ? EngineKind::Interpreter 397fc8a2d5aSReid Kleckner : EngineKind::JIT) 398fc8a2d5aSReid Kleckner .setErrorStr(ErrorStr) 399fc8a2d5aSReid Kleckner .setOptLevel(OptLevel) 400add6f1d2SOwen Anderson .setAllocateGVsWithCode(GVsWithCode); 401add6f1d2SOwen Anderson 402add6f1d2SOwen Anderson return EB.create(); 403fc8a2d5aSReid Kleckner } 4044bd3bd5bSBrian Gaeke 4050bd34fbdSDylan Noblesmith /// createJIT - This is the factory method for creating a JIT for the current 4060bd34fbdSDylan Noblesmith /// machine, it does not fall back to the interpreter. This takes ownership 4070bd34fbdSDylan Noblesmith /// of the module. 4080bd34fbdSDylan Noblesmith ExecutionEngine *ExecutionEngine::createJIT(Module *M, 4090bd34fbdSDylan Noblesmith std::string *ErrorStr, 4100bd34fbdSDylan Noblesmith JITMemoryManager *JMM, 41119a58df9SDylan Noblesmith CodeGenOpt::Level OL, 4120bd34fbdSDylan Noblesmith bool GVsWithCode, 4132129f596SEvan Cheng Reloc::Model RM, 4140bd34fbdSDylan Noblesmith CodeModel::Model CMM) { 4150bd34fbdSDylan Noblesmith if (ExecutionEngine::JITCtor == 0) { 4160bd34fbdSDylan Noblesmith if (ErrorStr) 4170bd34fbdSDylan Noblesmith *ErrorStr = "JIT has not been linked in."; 4180bd34fbdSDylan Noblesmith return 0; 4190bd34fbdSDylan Noblesmith } 4200bd34fbdSDylan Noblesmith 4210bd34fbdSDylan Noblesmith // Use the defaults for extra parameters. Users can use EngineBuilder to 4220bd34fbdSDylan Noblesmith // set them. 423add6f1d2SOwen Anderson EngineBuilder EB(M); 424add6f1d2SOwen Anderson EB.setEngineKind(EngineKind::JIT); 425add6f1d2SOwen Anderson EB.setErrorStr(ErrorStr); 426add6f1d2SOwen Anderson EB.setRelocationModel(RM); 427add6f1d2SOwen Anderson EB.setCodeModel(CMM); 428add6f1d2SOwen Anderson EB.setAllocateGVsWithCode(GVsWithCode); 429add6f1d2SOwen Anderson EB.setOptLevel(OL); 430add6f1d2SOwen Anderson EB.setJITMemoryManager(JMM); 4310bd34fbdSDylan Noblesmith 432dff24786SPeter Collingbourne // TODO: permit custom TargetOptions here 433add6f1d2SOwen Anderson TargetMachine *TM = EB.selectTarget(); 4340bd34fbdSDylan Noblesmith if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0; 4350bd34fbdSDylan Noblesmith 4367f26246aSDylan Noblesmith return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM); 4370bd34fbdSDylan Noblesmith } 4380bd34fbdSDylan Noblesmith 439add6f1d2SOwen Anderson ExecutionEngine *EngineBuilder::create(TargetMachine *TM) { 44025a3d816SBenjamin Kramer OwningPtr<TargetMachine> TheTM(TM); // Take ownership. 44125a3d816SBenjamin Kramer 442a53414fdSNick Lewycky // Make sure we can resolve symbols in the program as well. The zero arg 443a53414fdSNick Lewycky // to the function tells DynamicLibrary to load the program, not a library. 444a53414fdSNick Lewycky if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) 445a53414fdSNick Lewycky return 0; 446a53414fdSNick Lewycky 4479bc53e84SFilip Pizlo assert(!(JMM && MCJMM)); 4489bc53e84SFilip Pizlo 449fc8a2d5aSReid Kleckner // If the user specified a memory manager but didn't specify which engine to 450fc8a2d5aSReid Kleckner // create, we assume they only want the JIT, and we fail if they only want 451fc8a2d5aSReid Kleckner // the interpreter. 4529bc53e84SFilip Pizlo if (JMM || MCJMM) { 45341fa2bd1SChris Lattner if (WhichEngine & EngineKind::JIT) 454fc8a2d5aSReid Kleckner WhichEngine = EngineKind::JIT; 45541fa2bd1SChris Lattner else { 4568bcc6445SChris Lattner if (ErrorStr) 457fc8a2d5aSReid Kleckner *ErrorStr = "Cannot create an interpreter with a memory manager."; 45841fa2bd1SChris Lattner return 0; 459fc8a2d5aSReid Kleckner } 4604bd3bd5bSBrian Gaeke } 4614bd3bd5bSBrian Gaeke 4629bc53e84SFilip Pizlo if (MCJMM && ! UseMCJIT) { 4639bc53e84SFilip Pizlo if (ErrorStr) 4649bc53e84SFilip Pizlo *ErrorStr = 4659bc53e84SFilip Pizlo "Cannot create a legacy JIT with a runtime dyld memory " 4669bc53e84SFilip Pizlo "manager."; 4679bc53e84SFilip Pizlo return 0; 4689bc53e84SFilip Pizlo } 4699bc53e84SFilip Pizlo 470fc8a2d5aSReid Kleckner // Unless the interpreter was explicitly selected or the JIT is not linked, 471fc8a2d5aSReid Kleckner // try making a JIT. 47225a3d816SBenjamin Kramer if ((WhichEngine & EngineKind::JIT) && TheTM) { 4737f26246aSDylan Noblesmith Triple TT(M->getTargetTriple()); 4747f26246aSDylan Noblesmith if (!TM->getTarget().hasJIT()) { 4757f26246aSDylan Noblesmith errs() << "WARNING: This target JIT is not designed for the host" 4767f26246aSDylan Noblesmith << " you are running. If bad things happen, please choose" 4777f26246aSDylan Noblesmith << " a different -march switch.\n"; 4787f26246aSDylan Noblesmith } 4797f26246aSDylan Noblesmith 48070ff8b05SDaniel Dunbar if (UseMCJIT && ExecutionEngine::MCJITCtor) { 48170ff8b05SDaniel Dunbar ExecutionEngine *EE = 4829bc53e84SFilip Pizlo ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM, 48325a3d816SBenjamin Kramer AllocateGVsWithCode, TheTM.take()); 48470ff8b05SDaniel Dunbar if (EE) return EE; 48570ff8b05SDaniel Dunbar } else if (ExecutionEngine::JITCtor) { 48641fa2bd1SChris Lattner ExecutionEngine *EE = 4877f26246aSDylan Noblesmith ExecutionEngine::JITCtor(M, ErrorStr, JMM, 48825a3d816SBenjamin Kramer AllocateGVsWithCode, TheTM.take()); 48941fa2bd1SChris Lattner if (EE) return EE; 49041fa2bd1SChris Lattner } 491fc8a2d5aSReid Kleckner } 492fc8a2d5aSReid Kleckner 493fc8a2d5aSReid Kleckner // If we can't make a JIT and we didn't request one specifically, try making 494fc8a2d5aSReid Kleckner // an interpreter instead. 49541fa2bd1SChris Lattner if (WhichEngine & EngineKind::Interpreter) { 49641fa2bd1SChris Lattner if (ExecutionEngine::InterpCtor) 497091217beSJeffrey Yasskin return ExecutionEngine::InterpCtor(M, ErrorStr); 4988bcc6445SChris Lattner if (ErrorStr) 49941fa2bd1SChris Lattner *ErrorStr = "Interpreter has not been linked in."; 50041fa2bd1SChris Lattner return 0; 501fc8a2d5aSReid Kleckner } 502fc8a2d5aSReid Kleckner 503bea6753fSJim Grosbach if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 && 504bea6753fSJim Grosbach ExecutionEngine::MCJITCtor == 0) { 5058bcc6445SChris Lattner if (ErrorStr) 5068bcc6445SChris Lattner *ErrorStr = "JIT has not been linked in."; 5078bcc6445SChris Lattner } 508868e3f09SDaniel Dunbar 50941fa2bd1SChris Lattner return 0; 510b5163bb9SChris Lattner } 511b5163bb9SChris Lattner 512996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 5131678e859SBrian Gaeke if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 514996fe010SChris Lattner return getPointerToFunction(F); 515996fe010SChris Lattner 51679876f52SReid Spencer MutexGuard locked(lock); 517868e3f09SDaniel Dunbar if (void *P = EEState.getGlobalAddressMap(locked)[GV]) 518868e3f09SDaniel Dunbar return P; 51969e84901SJeff Cohen 52069e84901SJeff Cohen // Global variable might have been added since interpreter started. 52169e84901SJeff Cohen if (GlobalVariable *GVar = 52269e84901SJeff Cohen const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 52369e84901SJeff Cohen EmitGlobalVariable(GVar); 52469e84901SJeff Cohen else 525fbcc663cSTorok Edwin llvm_unreachable("Global hasn't had an address allocated yet!"); 526868e3f09SDaniel Dunbar 527d0fc8f80SJeffrey Yasskin return EEState.getGlobalAddressMap(locked)[GV]; 528996fe010SChris Lattner } 529996fe010SChris Lattner 530868e3f09SDaniel Dunbar /// \brief Converts a Constant* into a GenericValue, including handling of 531868e3f09SDaniel Dunbar /// ConstantExpr values. 532996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 5336c38f0bbSReid Spencer // If its undefined, return the garbage. 534bcbdbfb3SJay Foad if (isa<UndefValue>(C)) { 535bcbdbfb3SJay Foad GenericValue Result; 536bcbdbfb3SJay Foad switch (C->getType()->getTypeID()) { 537be79a7acSNadav Rotem default: 538be79a7acSNadav Rotem break; 539bcbdbfb3SJay Foad case Type::IntegerTyID: 540bcbdbfb3SJay Foad case Type::X86_FP80TyID: 541bcbdbfb3SJay Foad case Type::FP128TyID: 542bcbdbfb3SJay Foad case Type::PPC_FP128TyID: 543bcbdbfb3SJay Foad // Although the value is undefined, we still have to construct an APInt 544bcbdbfb3SJay Foad // with the correct bit width. 545bcbdbfb3SJay Foad Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0); 546bcbdbfb3SJay Foad break; 5478e97f016SElena Demikhovsky case Type::StructTyID: { 5488e97f016SElena Demikhovsky // if the whole struct is 'undef' just reserve memory for the value. 5498e97f016SElena Demikhovsky if(StructType *STy = dyn_cast<StructType>(C->getType())) { 5508e97f016SElena Demikhovsky unsigned int elemNum = STy->getNumElements(); 5518e97f016SElena Demikhovsky Result.AggregateVal.resize(elemNum); 5528e97f016SElena Demikhovsky for (unsigned int i = 0; i < elemNum; ++i) { 5538e97f016SElena Demikhovsky Type *ElemTy = STy->getElementType(i); 5548e97f016SElena Demikhovsky if (ElemTy->isIntegerTy()) 5558e97f016SElena Demikhovsky Result.AggregateVal[i].IntVal = 5568e97f016SElena Demikhovsky APInt(ElemTy->getPrimitiveSizeInBits(), 0); 5578e97f016SElena Demikhovsky else if (ElemTy->isAggregateType()) { 5588e97f016SElena Demikhovsky const Constant *ElemUndef = UndefValue::get(ElemTy); 5598e97f016SElena Demikhovsky Result.AggregateVal[i] = getConstantValue(ElemUndef); 5608e97f016SElena Demikhovsky } 5618e97f016SElena Demikhovsky } 5628e97f016SElena Demikhovsky } 5638e97f016SElena Demikhovsky } 5648e97f016SElena Demikhovsky break; 565be79a7acSNadav Rotem case Type::VectorTyID: 566be79a7acSNadav Rotem // if the whole vector is 'undef' just reserve memory for the value. 567be79a7acSNadav Rotem const VectorType* VTy = dyn_cast<VectorType>(C->getType()); 568be79a7acSNadav Rotem const Type *ElemTy = VTy->getElementType(); 569be79a7acSNadav Rotem unsigned int elemNum = VTy->getNumElements(); 570be79a7acSNadav Rotem Result.AggregateVal.resize(elemNum); 571be79a7acSNadav Rotem if (ElemTy->isIntegerTy()) 572be79a7acSNadav Rotem for (unsigned int i = 0; i < elemNum; ++i) 573be79a7acSNadav Rotem Result.AggregateVal[i].IntVal = 574be79a7acSNadav Rotem APInt(ElemTy->getPrimitiveSizeInBits(), 0); 575bcbdbfb3SJay Foad break; 576bcbdbfb3SJay Foad } 577bcbdbfb3SJay Foad return Result; 578bcbdbfb3SJay Foad } 5799de0d14dSChris Lattner 580868e3f09SDaniel Dunbar // Otherwise, if the value is a ConstantExpr... 5816c38f0bbSReid Spencer if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 5824fd528f2SReid Spencer Constant *Op0 = CE->getOperand(0); 5839de0d14dSChris Lattner switch (CE->getOpcode()) { 5849de0d14dSChris Lattner case Instruction::GetElementPtr: { 5856c38f0bbSReid Spencer // Compute the index 5864fd528f2SReid Spencer GenericValue Result = getConstantValue(Op0); 587b6ad9822SNuno Lopes APInt Offset(TD->getPointerSizeInBits(), 0); 588b6ad9822SNuno Lopes cast<GEPOperator>(CE)->accumulateConstantOffset(*TD, Offset); 5899de0d14dSChris Lattner 59087aa65f4SReid Spencer char* tmp = (char*) Result.PointerVal; 591b6ad9822SNuno Lopes Result = PTOGV(tmp + Offset.getSExtValue()); 5929de0d14dSChris Lattner return Result; 5939de0d14dSChris Lattner } 5944fd528f2SReid Spencer case Instruction::Trunc: { 5954fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5964fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 5974fd528f2SReid Spencer GV.IntVal = GV.IntVal.trunc(BitWidth); 5984fd528f2SReid Spencer return GV; 5994fd528f2SReid Spencer } 6004fd528f2SReid Spencer case Instruction::ZExt: { 6014fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6024fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 6034fd528f2SReid Spencer GV.IntVal = GV.IntVal.zext(BitWidth); 6044fd528f2SReid Spencer return GV; 6054fd528f2SReid Spencer } 6064fd528f2SReid Spencer case Instruction::SExt: { 6074fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6084fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 6094fd528f2SReid Spencer GV.IntVal = GV.IntVal.sext(BitWidth); 6104fd528f2SReid Spencer return GV; 6114fd528f2SReid Spencer } 6124fd528f2SReid Spencer case Instruction::FPTrunc: { 613a1336cf5SDale Johannesen // FIXME long double 6144fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6154fd528f2SReid Spencer GV.FloatVal = float(GV.DoubleVal); 6164fd528f2SReid Spencer return GV; 6174fd528f2SReid Spencer } 6184fd528f2SReid Spencer case Instruction::FPExt:{ 619a1336cf5SDale Johannesen // FIXME long double 6204fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6214fd528f2SReid Spencer GV.DoubleVal = double(GV.FloatVal); 6224fd528f2SReid Spencer return GV; 6234fd528f2SReid Spencer } 6244fd528f2SReid Spencer case Instruction::UIToFP: { 6254fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 626fdd87907SChris Lattner if (CE->getType()->isFloatTy()) 6274fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.roundToDouble()); 628fdd87907SChris Lattner else if (CE->getType()->isDoubleTy()) 6294fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.roundToDouble(); 630fdd87907SChris Lattner else if (CE->getType()->isX86_FP80Ty()) { 63131920b0aSBenjamin Kramer APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 632ca24fd90SDan Gohman (void)apf.convertFromAPInt(GV.IntVal, 633ca24fd90SDan Gohman false, 6349150652bSDale Johannesen APFloat::rmNearestTiesToEven); 63554306fe4SDale Johannesen GV.IntVal = apf.bitcastToAPInt(); 636a1336cf5SDale Johannesen } 6374fd528f2SReid Spencer return GV; 6384fd528f2SReid Spencer } 6394fd528f2SReid Spencer case Instruction::SIToFP: { 6404fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 641fdd87907SChris Lattner if (CE->getType()->isFloatTy()) 6424fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 643fdd87907SChris Lattner else if (CE->getType()->isDoubleTy()) 6444fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 645fdd87907SChris Lattner else if (CE->getType()->isX86_FP80Ty()) { 64631920b0aSBenjamin Kramer APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 647ca24fd90SDan Gohman (void)apf.convertFromAPInt(GV.IntVal, 648ca24fd90SDan Gohman true, 6499150652bSDale Johannesen APFloat::rmNearestTiesToEven); 65054306fe4SDale Johannesen GV.IntVal = apf.bitcastToAPInt(); 651a1336cf5SDale Johannesen } 6524fd528f2SReid Spencer return GV; 6534fd528f2SReid Spencer } 6544fd528f2SReid Spencer case Instruction::FPToUI: // double->APInt conversion handles sign 6554fd528f2SReid Spencer case Instruction::FPToSI: { 6564fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6574fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 658fdd87907SChris Lattner if (Op0->getType()->isFloatTy()) 6594fd528f2SReid Spencer GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 660fdd87907SChris Lattner else if (Op0->getType()->isDoubleTy()) 6614fd528f2SReid Spencer GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 662fdd87907SChris Lattner else if (Op0->getType()->isX86_FP80Ty()) { 66329178a34STim Northover APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal); 664a1336cf5SDale Johannesen uint64_t v; 6654f0bd68cSDale Johannesen bool ignored; 666a1336cf5SDale Johannesen (void)apf.convertToInteger(&v, BitWidth, 667a1336cf5SDale Johannesen CE->getOpcode()==Instruction::FPToSI, 6684f0bd68cSDale Johannesen APFloat::rmTowardZero, &ignored); 669a1336cf5SDale Johannesen GV.IntVal = v; // endian? 670a1336cf5SDale Johannesen } 6714fd528f2SReid Spencer return GV; 6724fd528f2SReid Spencer } 6736c38f0bbSReid Spencer case Instruction::PtrToInt: { 6744fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 675fc1f2cd3SEli Friedman uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType()); 676fc1f2cd3SEli Friedman assert(PtrWidth <= 64 && "Bad pointer width"); 6774fd528f2SReid Spencer GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 678fc1f2cd3SEli Friedman uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType()); 679fc1f2cd3SEli Friedman GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth); 6804fd528f2SReid Spencer return GV; 6814fd528f2SReid Spencer } 6824fd528f2SReid Spencer case Instruction::IntToPtr: { 6834fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 684bf3eeb2dSMicah Villmow uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType()); 6854fd528f2SReid Spencer GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 6864fd528f2SReid Spencer assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 6874fd528f2SReid Spencer GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 6886c38f0bbSReid Spencer return GV; 6896c38f0bbSReid Spencer } 6906c38f0bbSReid Spencer case Instruction::BitCast: { 6914fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 692229907cdSChris Lattner Type* DestTy = CE->getType(); 6934fd528f2SReid Spencer switch (Op0->getType()->getTypeID()) { 694fbcc663cSTorok Edwin default: llvm_unreachable("Invalid bitcast operand"); 6954fd528f2SReid Spencer case Type::IntegerTyID: 6969dff9becSDuncan Sands assert(DestTy->isFloatingPointTy() && "invalid bitcast"); 697fdd87907SChris Lattner if (DestTy->isFloatTy()) 6984fd528f2SReid Spencer GV.FloatVal = GV.IntVal.bitsToFloat(); 699fdd87907SChris Lattner else if (DestTy->isDoubleTy()) 7004fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.bitsToDouble(); 7016c38f0bbSReid Spencer break; 7024fd528f2SReid Spencer case Type::FloatTyID: 7039dff9becSDuncan Sands assert(DestTy->isIntegerTy(32) && "Invalid bitcast"); 7043447fb01SJay Foad GV.IntVal = APInt::floatToBits(GV.FloatVal); 7054fd528f2SReid Spencer break; 7064fd528f2SReid Spencer case Type::DoubleTyID: 7079dff9becSDuncan Sands assert(DestTy->isIntegerTy(64) && "Invalid bitcast"); 7083447fb01SJay Foad GV.IntVal = APInt::doubleToBits(GV.DoubleVal); 7094fd528f2SReid Spencer break; 7104fd528f2SReid Spencer case Type::PointerTyID: 71119d0b47bSDuncan Sands assert(DestTy->isPointerTy() && "Invalid bitcast"); 7124fd528f2SReid Spencer break; // getConstantValue(Op0) above already converted it 7136c38f0bbSReid Spencer } 7144fd528f2SReid Spencer return GV; 71568cbcc3eSChris Lattner } 71668cbcc3eSChris Lattner case Instruction::Add: 717a5b9645cSDan Gohman case Instruction::FAdd: 7184fd528f2SReid Spencer case Instruction::Sub: 719a5b9645cSDan Gohman case Instruction::FSub: 7204fd528f2SReid Spencer case Instruction::Mul: 721a5b9645cSDan Gohman case Instruction::FMul: 7224fd528f2SReid Spencer case Instruction::UDiv: 7234fd528f2SReid Spencer case Instruction::SDiv: 7244fd528f2SReid Spencer case Instruction::URem: 7254fd528f2SReid Spencer case Instruction::SRem: 7264fd528f2SReid Spencer case Instruction::And: 7274fd528f2SReid Spencer case Instruction::Or: 7284fd528f2SReid Spencer case Instruction::Xor: { 7294fd528f2SReid Spencer GenericValue LHS = getConstantValue(Op0); 7304fd528f2SReid Spencer GenericValue RHS = getConstantValue(CE->getOperand(1)); 7314fd528f2SReid Spencer GenericValue GV; 732c4e6bb5fSChris Lattner switch (CE->getOperand(0)->getType()->getTypeID()) { 733fbcc663cSTorok Edwin default: llvm_unreachable("Bad add type!"); 7347a9c62baSReid Spencer case Type::IntegerTyID: 7354fd528f2SReid Spencer switch (CE->getOpcode()) { 736fbcc663cSTorok Edwin default: llvm_unreachable("Invalid integer opcode"); 7374fd528f2SReid Spencer case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 7384fd528f2SReid Spencer case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 7394fd528f2SReid Spencer case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 7404fd528f2SReid Spencer case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 7414fd528f2SReid Spencer case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 7424fd528f2SReid Spencer case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 7434fd528f2SReid Spencer case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 7444fd528f2SReid Spencer case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 7454fd528f2SReid Spencer case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 7464fd528f2SReid Spencer case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 7474fd528f2SReid Spencer } 748c4e6bb5fSChris Lattner break; 749c4e6bb5fSChris Lattner case Type::FloatTyID: 7504fd528f2SReid Spencer switch (CE->getOpcode()) { 751fbcc663cSTorok Edwin default: llvm_unreachable("Invalid float opcode"); 752a5b9645cSDan Gohman case Instruction::FAdd: 7534fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 754a5b9645cSDan Gohman case Instruction::FSub: 7554fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 756a5b9645cSDan Gohman case Instruction::FMul: 7574fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 7584fd528f2SReid Spencer case Instruction::FDiv: 7594fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 7604fd528f2SReid Spencer case Instruction::FRem: 76193cd0f1cSChris Lattner GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break; 7624fd528f2SReid Spencer } 763c4e6bb5fSChris Lattner break; 764c4e6bb5fSChris Lattner case Type::DoubleTyID: 7654fd528f2SReid Spencer switch (CE->getOpcode()) { 766fbcc663cSTorok Edwin default: llvm_unreachable("Invalid double opcode"); 767a5b9645cSDan Gohman case Instruction::FAdd: 7684fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 769a5b9645cSDan Gohman case Instruction::FSub: 7704fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 771a5b9645cSDan Gohman case Instruction::FMul: 7724fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 7734fd528f2SReid Spencer case Instruction::FDiv: 7744fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 7754fd528f2SReid Spencer case Instruction::FRem: 77693cd0f1cSChris Lattner GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 7774fd528f2SReid Spencer } 778c4e6bb5fSChris Lattner break; 779a1336cf5SDale Johannesen case Type::X86_FP80TyID: 780a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 781a1336cf5SDale Johannesen case Type::FP128TyID: { 78229178a34STim Northover const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics(); 78329178a34STim Northover APFloat apfLHS = APFloat(Sem, LHS.IntVal); 784a1336cf5SDale Johannesen switch (CE->getOpcode()) { 785e4f47434SDaniel Dunbar default: llvm_unreachable("Invalid long double opcode"); 786a5b9645cSDan Gohman case Instruction::FAdd: 78729178a34STim Northover apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven); 78854306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 789a1336cf5SDale Johannesen break; 790a5b9645cSDan Gohman case Instruction::FSub: 79129178a34STim Northover apfLHS.subtract(APFloat(Sem, RHS.IntVal), 79229178a34STim Northover APFloat::rmNearestTiesToEven); 79354306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 794a1336cf5SDale Johannesen break; 795a5b9645cSDan Gohman case Instruction::FMul: 79629178a34STim Northover apfLHS.multiply(APFloat(Sem, RHS.IntVal), 79729178a34STim Northover APFloat::rmNearestTiesToEven); 79854306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 799a1336cf5SDale Johannesen break; 800a1336cf5SDale Johannesen case Instruction::FDiv: 80129178a34STim Northover apfLHS.divide(APFloat(Sem, RHS.IntVal), 80229178a34STim Northover APFloat::rmNearestTiesToEven); 80354306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 804a1336cf5SDale Johannesen break; 805a1336cf5SDale Johannesen case Instruction::FRem: 80629178a34STim Northover apfLHS.mod(APFloat(Sem, RHS.IntVal), 80729178a34STim Northover APFloat::rmNearestTiesToEven); 80854306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 809a1336cf5SDale Johannesen break; 810a1336cf5SDale Johannesen } 811a1336cf5SDale Johannesen } 812a1336cf5SDale Johannesen break; 813c4e6bb5fSChris Lattner } 8144fd528f2SReid Spencer return GV; 8154fd528f2SReid Spencer } 8169de0d14dSChris Lattner default: 81768cbcc3eSChris Lattner break; 81868cbcc3eSChris Lattner } 819868e3f09SDaniel Dunbar 820868e3f09SDaniel Dunbar SmallString<256> Msg; 821868e3f09SDaniel Dunbar raw_svector_ostream OS(Msg); 822868e3f09SDaniel Dunbar OS << "ConstantExpr not handled: " << *CE; 823868e3f09SDaniel Dunbar report_fatal_error(OS.str()); 8249de0d14dSChris Lattner } 825996fe010SChris Lattner 826868e3f09SDaniel Dunbar // Otherwise, we have a simple constant. 8274fd528f2SReid Spencer GenericValue Result; 8286b727599SChris Lattner switch (C->getType()->getTypeID()) { 82987aa65f4SReid Spencer case Type::FloatTyID: 830bed9dc42SDale Johannesen Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 8317a9c62baSReid Spencer break; 83287aa65f4SReid Spencer case Type::DoubleTyID: 833bed9dc42SDale Johannesen Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 83487aa65f4SReid Spencer break; 835a1336cf5SDale Johannesen case Type::X86_FP80TyID: 836a1336cf5SDale Johannesen case Type::FP128TyID: 837a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 83854306fe4SDale Johannesen Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt(); 839a1336cf5SDale Johannesen break; 84087aa65f4SReid Spencer case Type::IntegerTyID: 84187aa65f4SReid Spencer Result.IntVal = cast<ConstantInt>(C)->getValue(); 84287aa65f4SReid Spencer break; 843996fe010SChris Lattner case Type::PointerTyID: 8446a0fd73bSReid Spencer if (isa<ConstantPointerNull>(C)) 845996fe010SChris Lattner Result.PointerVal = 0; 8466a0fd73bSReid Spencer else if (const Function *F = dyn_cast<Function>(C)) 8476a0fd73bSReid Spencer Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 8486a0fd73bSReid Spencer else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) 8496a0fd73bSReid Spencer Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 8500c778f70SChris Lattner else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 8510c778f70SChris Lattner Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>( 8520c778f70SChris Lattner BA->getBasicBlock()))); 853e6492f10SChris Lattner else 854fbcc663cSTorok Edwin llvm_unreachable("Unknown constant pointer type!"); 855996fe010SChris Lattner break; 856be79a7acSNadav Rotem case Type::VectorTyID: { 857be79a7acSNadav Rotem unsigned elemNum; 858be79a7acSNadav Rotem Type* ElemTy; 859be79a7acSNadav Rotem const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C); 860be79a7acSNadav Rotem const ConstantVector *CV = dyn_cast<ConstantVector>(C); 861be79a7acSNadav Rotem const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C); 862be79a7acSNadav Rotem 863be79a7acSNadav Rotem if (CDV) { 864be79a7acSNadav Rotem elemNum = CDV->getNumElements(); 865be79a7acSNadav Rotem ElemTy = CDV->getElementType(); 866be79a7acSNadav Rotem } else if (CV || CAZ) { 867be79a7acSNadav Rotem VectorType* VTy = dyn_cast<VectorType>(C->getType()); 868be79a7acSNadav Rotem elemNum = VTy->getNumElements(); 869be79a7acSNadav Rotem ElemTy = VTy->getElementType(); 870be79a7acSNadav Rotem } else { 871be79a7acSNadav Rotem llvm_unreachable("Unknown constant vector type!"); 872be79a7acSNadav Rotem } 873be79a7acSNadav Rotem 874be79a7acSNadav Rotem Result.AggregateVal.resize(elemNum); 875be79a7acSNadav Rotem // Check if vector holds floats. 876be79a7acSNadav Rotem if(ElemTy->isFloatTy()) { 877be79a7acSNadav Rotem if (CAZ) { 878be79a7acSNadav Rotem GenericValue floatZero; 879be79a7acSNadav Rotem floatZero.FloatVal = 0.f; 880be79a7acSNadav Rotem std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 881be79a7acSNadav Rotem floatZero); 882be79a7acSNadav Rotem break; 883be79a7acSNadav Rotem } 884be79a7acSNadav Rotem if(CV) { 885be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 886be79a7acSNadav Rotem if (!isa<UndefValue>(CV->getOperand(i))) 887be79a7acSNadav Rotem Result.AggregateVal[i].FloatVal = cast<ConstantFP>( 888be79a7acSNadav Rotem CV->getOperand(i))->getValueAPF().convertToFloat(); 889be79a7acSNadav Rotem break; 890be79a7acSNadav Rotem } 891be79a7acSNadav Rotem if(CDV) 892be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 893be79a7acSNadav Rotem Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i); 894be79a7acSNadav Rotem 895be79a7acSNadav Rotem break; 896be79a7acSNadav Rotem } 897be79a7acSNadav Rotem // Check if vector holds doubles. 898be79a7acSNadav Rotem if (ElemTy->isDoubleTy()) { 899be79a7acSNadav Rotem if (CAZ) { 900be79a7acSNadav Rotem GenericValue doubleZero; 901be79a7acSNadav Rotem doubleZero.DoubleVal = 0.0; 902be79a7acSNadav Rotem std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 903be79a7acSNadav Rotem doubleZero); 904be79a7acSNadav Rotem break; 905be79a7acSNadav Rotem } 906be79a7acSNadav Rotem if(CV) { 907be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 908be79a7acSNadav Rotem if (!isa<UndefValue>(CV->getOperand(i))) 909be79a7acSNadav Rotem Result.AggregateVal[i].DoubleVal = cast<ConstantFP>( 910be79a7acSNadav Rotem CV->getOperand(i))->getValueAPF().convertToDouble(); 911be79a7acSNadav Rotem break; 912be79a7acSNadav Rotem } 913be79a7acSNadav Rotem if(CDV) 914be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 915be79a7acSNadav Rotem Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i); 916be79a7acSNadav Rotem 917be79a7acSNadav Rotem break; 918be79a7acSNadav Rotem } 919be79a7acSNadav Rotem // Check if vector holds integers. 920be79a7acSNadav Rotem if (ElemTy->isIntegerTy()) { 921be79a7acSNadav Rotem if (CAZ) { 922be79a7acSNadav Rotem GenericValue intZero; 923be79a7acSNadav Rotem intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull); 924be79a7acSNadav Rotem std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 925be79a7acSNadav Rotem intZero); 926be79a7acSNadav Rotem break; 927be79a7acSNadav Rotem } 928be79a7acSNadav Rotem if(CV) { 929be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 930be79a7acSNadav Rotem if (!isa<UndefValue>(CV->getOperand(i))) 931be79a7acSNadav Rotem Result.AggregateVal[i].IntVal = cast<ConstantInt>( 932be79a7acSNadav Rotem CV->getOperand(i))->getValue(); 933be79a7acSNadav Rotem else { 934be79a7acSNadav Rotem Result.AggregateVal[i].IntVal = 935be79a7acSNadav Rotem APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0); 936be79a7acSNadav Rotem } 937be79a7acSNadav Rotem break; 938be79a7acSNadav Rotem } 939be79a7acSNadav Rotem if(CDV) 940be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 941be79a7acSNadav Rotem Result.AggregateVal[i].IntVal = APInt( 942be79a7acSNadav Rotem CDV->getElementType()->getPrimitiveSizeInBits(), 943be79a7acSNadav Rotem CDV->getElementAsInteger(i)); 944be79a7acSNadav Rotem 945be79a7acSNadav Rotem break; 946be79a7acSNadav Rotem } 947be79a7acSNadav Rotem llvm_unreachable("Unknown constant pointer type!"); 948be79a7acSNadav Rotem } 949be79a7acSNadav Rotem break; 950be79a7acSNadav Rotem 951996fe010SChris Lattner default: 952868e3f09SDaniel Dunbar SmallString<256> Msg; 953868e3f09SDaniel Dunbar raw_svector_ostream OS(Msg); 954868e3f09SDaniel Dunbar OS << "ERROR: Constant unimplemented for type: " << *C->getType(); 955868e3f09SDaniel Dunbar report_fatal_error(OS.str()); 956996fe010SChris Lattner } 957868e3f09SDaniel Dunbar 958996fe010SChris Lattner return Result; 959996fe010SChris Lattner } 960996fe010SChris Lattner 9611202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 9621202d1b1SDuncan Sands /// with the integer held in IntVal. 9631202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 9641202d1b1SDuncan Sands unsigned StoreBytes) { 9651202d1b1SDuncan Sands assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 966ad06cee2SRoman Divacky const uint8_t *Src = (const uint8_t *)IntVal.getRawData(); 9675c65cb46SDuncan Sands 96841cb64f4SRafael Espindola if (sys::IsLittleEndianHost) { 9691202d1b1SDuncan Sands // Little-endian host - the source is ordered from LSB to MSB. Order the 9701202d1b1SDuncan Sands // destination from LSB to MSB: Do a straight copy. 9715c65cb46SDuncan Sands memcpy(Dst, Src, StoreBytes); 972868e3f09SDaniel Dunbar } else { 9735c65cb46SDuncan Sands // Big-endian host - the source is an array of 64 bit words ordered from 9741202d1b1SDuncan Sands // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 9751202d1b1SDuncan Sands // from MSB to LSB: Reverse the word order, but not the bytes in a word. 9765c65cb46SDuncan Sands while (StoreBytes > sizeof(uint64_t)) { 9775c65cb46SDuncan Sands StoreBytes -= sizeof(uint64_t); 9785c65cb46SDuncan Sands // May not be aligned so use memcpy. 9795c65cb46SDuncan Sands memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 9805c65cb46SDuncan Sands Src += sizeof(uint64_t); 9815c65cb46SDuncan Sands } 9825c65cb46SDuncan Sands 9835c65cb46SDuncan Sands memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 984815f8dd2SReid Spencer } 9857a9c62baSReid Spencer } 9861202d1b1SDuncan Sands 98709053e62SEvan Cheng void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, 988229907cdSChris Lattner GenericValue *Ptr, Type *Ty) { 989cdfe20b9SMicah Villmow const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty); 9901202d1b1SDuncan Sands 9911202d1b1SDuncan Sands switch (Ty->getTypeID()) { 992be79a7acSNadav Rotem default: 993be79a7acSNadav Rotem dbgs() << "Cannot store value of type " << *Ty << "!\n"; 994be79a7acSNadav Rotem break; 9951202d1b1SDuncan Sands case Type::IntegerTyID: 9961202d1b1SDuncan Sands StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes); 9971202d1b1SDuncan Sands break; 998996fe010SChris Lattner case Type::FloatTyID: 99987aa65f4SReid Spencer *((float*)Ptr) = Val.FloatVal; 100087aa65f4SReid Spencer break; 100187aa65f4SReid Spencer case Type::DoubleTyID: 100287aa65f4SReid Spencer *((double*)Ptr) = Val.DoubleVal; 1003996fe010SChris Lattner break; 10044d7e4ee7SDale Johannesen case Type::X86_FP80TyID: 10054d7e4ee7SDale Johannesen memcpy(Ptr, Val.IntVal.getRawData(), 10); 1006a1336cf5SDale Johannesen break; 10077a9c62baSReid Spencer case Type::PointerTyID: 10081202d1b1SDuncan Sands // Ensure 64 bit target pointers are fully initialized on 32 bit hosts. 10091202d1b1SDuncan Sands if (StoreBytes != sizeof(PointerTy)) 101093da3c82SChandler Carruth memset(&(Ptr->PointerVal), 0, StoreBytes); 10111202d1b1SDuncan Sands 101287aa65f4SReid Spencer *((PointerTy*)Ptr) = Val.PointerVal; 1013996fe010SChris Lattner break; 1014be79a7acSNadav Rotem case Type::VectorTyID: 1015be79a7acSNadav Rotem for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) { 1016be79a7acSNadav Rotem if (cast<VectorType>(Ty)->getElementType()->isDoubleTy()) 1017be79a7acSNadav Rotem *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal; 1018be79a7acSNadav Rotem if (cast<VectorType>(Ty)->getElementType()->isFloatTy()) 1019be79a7acSNadav Rotem *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal; 1020be79a7acSNadav Rotem if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) { 1021be79a7acSNadav Rotem unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8; 1022be79a7acSNadav Rotem StoreIntToMemory(Val.AggregateVal[i].IntVal, 1023be79a7acSNadav Rotem (uint8_t*)Ptr + numOfBytes*i, numOfBytes); 1024be79a7acSNadav Rotem } 1025be79a7acSNadav Rotem } 1026be79a7acSNadav Rotem break; 1027996fe010SChris Lattner } 10281202d1b1SDuncan Sands 102941cb64f4SRafael Espindola if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian()) 10301202d1b1SDuncan Sands // Host and target are different endian - reverse the stored bytes. 10311202d1b1SDuncan Sands std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr); 1032996fe010SChris Lattner } 1033996fe010SChris Lattner 10341202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 10351202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 10361202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) { 10371202d1b1SDuncan Sands assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 103882b63578SDavid Greene uint8_t *Dst = reinterpret_cast<uint8_t *>( 103982b63578SDavid Greene const_cast<uint64_t *>(IntVal.getRawData())); 10405c65cb46SDuncan Sands 104141cb64f4SRafael Espindola if (sys::IsLittleEndianHost) 10425c65cb46SDuncan Sands // Little-endian host - the destination must be ordered from LSB to MSB. 10435c65cb46SDuncan Sands // The source is ordered from LSB to MSB: Do a straight copy. 10445c65cb46SDuncan Sands memcpy(Dst, Src, LoadBytes); 10455c65cb46SDuncan Sands else { 10465c65cb46SDuncan Sands // Big-endian - the destination is an array of 64 bit words ordered from 10475c65cb46SDuncan Sands // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 10485c65cb46SDuncan Sands // ordered from MSB to LSB: Reverse the word order, but not the bytes in 10495c65cb46SDuncan Sands // a word. 10505c65cb46SDuncan Sands while (LoadBytes > sizeof(uint64_t)) { 10515c65cb46SDuncan Sands LoadBytes -= sizeof(uint64_t); 10525c65cb46SDuncan Sands // May not be aligned so use memcpy. 10535c65cb46SDuncan Sands memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 10545c65cb46SDuncan Sands Dst += sizeof(uint64_t); 10555c65cb46SDuncan Sands } 10565c65cb46SDuncan Sands 10575c65cb46SDuncan Sands memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 10585c65cb46SDuncan Sands } 10597a9c62baSReid Spencer } 10601202d1b1SDuncan Sands 10611202d1b1SDuncan Sands /// FIXME: document 10621202d1b1SDuncan Sands /// 10631202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 10641202d1b1SDuncan Sands GenericValue *Ptr, 1065229907cdSChris Lattner Type *Ty) { 1066cdfe20b9SMicah Villmow const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty); 10671202d1b1SDuncan Sands 10681202d1b1SDuncan Sands switch (Ty->getTypeID()) { 10691202d1b1SDuncan Sands case Type::IntegerTyID: 10701202d1b1SDuncan Sands // An APInt with all words initially zero. 10711202d1b1SDuncan Sands Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0); 10721202d1b1SDuncan Sands LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes); 10731202d1b1SDuncan Sands break; 10747f389e8cSChris Lattner case Type::FloatTyID: 107587aa65f4SReid Spencer Result.FloatVal = *((float*)Ptr); 107687aa65f4SReid Spencer break; 107787aa65f4SReid Spencer case Type::DoubleTyID: 107887aa65f4SReid Spencer Result.DoubleVal = *((double*)Ptr); 10797f389e8cSChris Lattner break; 10807a9c62baSReid Spencer case Type::PointerTyID: 108187aa65f4SReid Spencer Result.PointerVal = *((PointerTy*)Ptr); 10827f389e8cSChris Lattner break; 1083a1336cf5SDale Johannesen case Type::X86_FP80TyID: { 1084a1336cf5SDale Johannesen // This is endian dependent, but it will only work on x86 anyway. 108526d6539eSDuncan Sands // FIXME: Will not trap if loading a signaling NaN. 1086ff306287SDuncan Sands uint64_t y[2]; 10874d7e4ee7SDale Johannesen memcpy(y, Ptr, 10); 10887a162881SJeffrey Yasskin Result.IntVal = APInt(80, y); 1089a1336cf5SDale Johannesen break; 1090a1336cf5SDale Johannesen } 1091be79a7acSNadav Rotem case Type::VectorTyID: { 1092be79a7acSNadav Rotem const VectorType *VT = cast<VectorType>(Ty); 1093be79a7acSNadav Rotem const Type *ElemT = VT->getElementType(); 1094be79a7acSNadav Rotem const unsigned numElems = VT->getNumElements(); 1095be79a7acSNadav Rotem if (ElemT->isFloatTy()) { 1096be79a7acSNadav Rotem Result.AggregateVal.resize(numElems); 1097be79a7acSNadav Rotem for (unsigned i = 0; i < numElems; ++i) 1098be79a7acSNadav Rotem Result.AggregateVal[i].FloatVal = *((float*)Ptr+i); 1099be79a7acSNadav Rotem } 1100be79a7acSNadav Rotem if (ElemT->isDoubleTy()) { 1101be79a7acSNadav Rotem Result.AggregateVal.resize(numElems); 1102be79a7acSNadav Rotem for (unsigned i = 0; i < numElems; ++i) 1103be79a7acSNadav Rotem Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i); 1104be79a7acSNadav Rotem } 1105be79a7acSNadav Rotem if (ElemT->isIntegerTy()) { 1106be79a7acSNadav Rotem GenericValue intZero; 1107be79a7acSNadav Rotem const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth(); 1108be79a7acSNadav Rotem intZero.IntVal = APInt(elemBitWidth, 0); 1109be79a7acSNadav Rotem Result.AggregateVal.resize(numElems, intZero); 1110be79a7acSNadav Rotem for (unsigned i = 0; i < numElems; ++i) 1111be79a7acSNadav Rotem LoadIntFromMemory(Result.AggregateVal[i].IntVal, 1112be79a7acSNadav Rotem (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8); 1113be79a7acSNadav Rotem } 1114be79a7acSNadav Rotem break; 1115be79a7acSNadav Rotem } 11167f389e8cSChris Lattner default: 1117868e3f09SDaniel Dunbar SmallString<256> Msg; 1118868e3f09SDaniel Dunbar raw_svector_ostream OS(Msg); 1119868e3f09SDaniel Dunbar OS << "Cannot load value of type " << *Ty << "!"; 1120868e3f09SDaniel Dunbar report_fatal_error(OS.str()); 11217f389e8cSChris Lattner } 11227f389e8cSChris Lattner } 11237f389e8cSChris Lattner 1124996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 11250967d2dfSDavid Greene DEBUG(dbgs() << "JIT: Initializing " << Addr << " "); 1126b086d382SDale Johannesen DEBUG(Init->dump()); 112700245f42SChris Lattner if (isa<UndefValue>(Init)) 112861753bf8SChris Lattner return; 112900245f42SChris Lattner 113000245f42SChris Lattner if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 113169d62138SRobert Bocchino unsigned ElementSize = 1132cdfe20b9SMicah Villmow getDataLayout()->getTypeAllocSize(CP->getType()->getElementType()); 113369d62138SRobert Bocchino for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 113469d62138SRobert Bocchino InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 113569d62138SRobert Bocchino return; 113600245f42SChris Lattner } 113700245f42SChris Lattner 113800245f42SChris Lattner if (isa<ConstantAggregateZero>(Init)) { 1139cdfe20b9SMicah Villmow memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType())); 11401dd86b11SChris Lattner return; 114100245f42SChris Lattner } 114200245f42SChris Lattner 114300245f42SChris Lattner if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) { 114469ddfbfeSDan Gohman unsigned ElementSize = 1145cdfe20b9SMicah Villmow getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType()); 114669ddfbfeSDan Gohman for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 114769ddfbfeSDan Gohman InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 114869ddfbfeSDan Gohman return; 114900245f42SChris Lattner } 115000245f42SChris Lattner 115100245f42SChris Lattner if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) { 115269ddfbfeSDan Gohman const StructLayout *SL = 1153cdfe20b9SMicah Villmow getDataLayout()->getStructLayout(cast<StructType>(CPS->getType())); 115469ddfbfeSDan Gohman for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 115569ddfbfeSDan Gohman InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 115669ddfbfeSDan Gohman return; 115700245f42SChris Lattner } 115800245f42SChris Lattner 115900245f42SChris Lattner if (const ConstantDataSequential *CDS = 116000245f42SChris Lattner dyn_cast<ConstantDataSequential>(Init)) { 116100245f42SChris Lattner // CDS is already laid out in host memory order. 116200245f42SChris Lattner StringRef Data = CDS->getRawDataValues(); 116300245f42SChris Lattner memcpy(Addr, Data.data(), Data.size()); 116400245f42SChris Lattner return; 116500245f42SChris Lattner } 116600245f42SChris Lattner 116700245f42SChris Lattner if (Init->getType()->isFirstClassType()) { 1168996fe010SChris Lattner GenericValue Val = getConstantValue(Init); 1169996fe010SChris Lattner StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 1170996fe010SChris Lattner return; 1171996fe010SChris Lattner } 1172996fe010SChris Lattner 1173868e3f09SDaniel Dunbar DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n"); 1174fbcc663cSTorok Edwin llvm_unreachable("Unknown constant type to initialize memory with!"); 1175996fe010SChris Lattner } 1176996fe010SChris Lattner 1177996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their 1178996fe010SChris Lattner /// addresses into GlobalAddress. This must make sure to copy the contents of 1179996fe010SChris Lattner /// their initializers into the memory. 1180996fe010SChris Lattner void ExecutionEngine::emitGlobals() { 1181996fe010SChris Lattner // Loop over all of the global variables in the program, allocating the memory 11820621caefSChris Lattner // to hold them. If there is more than one module, do a prepass over globals 11830621caefSChris Lattner // to figure out how the different modules should link together. 1184229907cdSChris Lattner std::map<std::pair<std::string, Type*>, 11850621caefSChris Lattner const GlobalValue*> LinkedGlobalsMap; 11860621caefSChris Lattner 11870621caefSChris Lattner if (Modules.size() != 1) { 11880621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1189091217beSJeffrey Yasskin Module &M = *Modules[m]; 11900621caefSChris Lattner for (Module::const_global_iterator I = M.global_begin(), 11910621caefSChris Lattner E = M.global_end(); I != E; ++I) { 11920621caefSChris Lattner const GlobalValue *GV = I; 11936de96a1bSRafael Espindola if (GV->hasLocalLinkage() || GV->isDeclaration() || 11940621caefSChris Lattner GV->hasAppendingLinkage() || !GV->hasName()) 11950621caefSChris Lattner continue;// Ignore external globals and globals with internal linkage. 11960621caefSChris Lattner 11970621caefSChris Lattner const GlobalValue *&GVEntry = 11980621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 11990621caefSChris Lattner 12000621caefSChris Lattner // If this is the first time we've seen this global, it is the canonical 12010621caefSChris Lattner // version. 12020621caefSChris Lattner if (!GVEntry) { 12030621caefSChris Lattner GVEntry = GV; 12040621caefSChris Lattner continue; 12050621caefSChris Lattner } 12060621caefSChris Lattner 12070621caefSChris Lattner // If the existing global is strong, never replace it. 1208d61d39ecSAnton Korobeynikov if (GVEntry->hasExternalLinkage() || 1209d61d39ecSAnton Korobeynikov GVEntry->hasDLLImportLinkage() || 1210d61d39ecSAnton Korobeynikov GVEntry->hasDLLExportLinkage()) 12110621caefSChris Lattner continue; 12120621caefSChris Lattner 12130621caefSChris Lattner // Otherwise, we know it's linkonce/weak, replace it if this is a strong 1214ce4396bcSDale Johannesen // symbol. FIXME is this right for common? 121512c94949SAnton Korobeynikov if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 12160621caefSChris Lattner GVEntry = GV; 12170621caefSChris Lattner } 12180621caefSChris Lattner } 12190621caefSChris Lattner } 12200621caefSChris Lattner 12210621caefSChris Lattner std::vector<const GlobalValue*> NonCanonicalGlobals; 12220621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1223091217beSJeffrey Yasskin Module &M = *Modules[m]; 12248ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 12250621caefSChris Lattner I != E; ++I) { 12260621caefSChris Lattner // In the multi-module case, see what this global maps to. 12270621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 12280621caefSChris Lattner if (const GlobalValue *GVEntry = 12290621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) { 12300621caefSChris Lattner // If something else is the canonical global, ignore this one. 12310621caefSChris Lattner if (GVEntry != &*I) { 12320621caefSChris Lattner NonCanonicalGlobals.push_back(I); 12330621caefSChris Lattner continue; 12340621caefSChris Lattner } 12350621caefSChris Lattner } 12360621caefSChris Lattner } 12370621caefSChris Lattner 12385301e7c6SReid Spencer if (!I->isDeclaration()) { 12395457ce9aSNicolas Geoffray addGlobalMapping(I, getMemoryForGV(I)); 1240996fe010SChris Lattner } else { 1241e8bbcfc2SBrian Gaeke // External variable reference. Try to use the dynamic loader to 1242e8bbcfc2SBrian Gaeke // get a pointer to it. 12430621caefSChris Lattner if (void *SymAddr = 12445899e340SDaniel Dunbar sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName())) 1245748e8579SChris Lattner addGlobalMapping(I, SymAddr); 12469de0d14dSChris Lattner else { 12472104b8d3SChris Lattner report_fatal_error("Could not resolve external global address: " 12486c2d233eSTorok Edwin +I->getName()); 12499de0d14dSChris Lattner } 1250996fe010SChris Lattner } 12510621caefSChris Lattner } 12520621caefSChris Lattner 12530621caefSChris Lattner // If there are multiple modules, map the non-canonical globals to their 12540621caefSChris Lattner // canonical location. 12550621caefSChris Lattner if (!NonCanonicalGlobals.empty()) { 12560621caefSChris Lattner for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 12570621caefSChris Lattner const GlobalValue *GV = NonCanonicalGlobals[i]; 12580621caefSChris Lattner const GlobalValue *CGV = 12590621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 12600621caefSChris Lattner void *Ptr = getPointerToGlobalIfAvailable(CGV); 12610621caefSChris Lattner assert(Ptr && "Canonical global wasn't codegen'd!"); 1262a67f06b9SNuno Lopes addGlobalMapping(GV, Ptr); 12630621caefSChris Lattner } 12640621caefSChris Lattner } 1265996fe010SChris Lattner 12667a9c62baSReid Spencer // Now that all of the globals are set up in memory, loop through them all 12677a9c62baSReid Spencer // and initialize their contents. 12688ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 12690621caefSChris Lattner I != E; ++I) { 12705301e7c6SReid Spencer if (!I->isDeclaration()) { 12710621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 12720621caefSChris Lattner if (const GlobalValue *GVEntry = 12730621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) 12740621caefSChris Lattner if (GVEntry != &*I) // Not the canonical variable. 12750621caefSChris Lattner continue; 12760621caefSChris Lattner } 12776bbe3eceSChris Lattner EmitGlobalVariable(I); 12786bbe3eceSChris Lattner } 12790621caefSChris Lattner } 12800621caefSChris Lattner } 12810621caefSChris Lattner } 12826bbe3eceSChris Lattner 12836bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the 12846bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not 12856bbe3eceSChris Lattner // already in the map. 1286fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 1287748e8579SChris Lattner void *GA = getPointerToGlobalIfAvailable(GV); 1288dc631735SChris Lattner 12896bbe3eceSChris Lattner if (GA == 0) { 12906bbe3eceSChris Lattner // If it's not already specified, allocate memory for the global. 12915457ce9aSNicolas Geoffray GA = getMemoryForGV(GV); 1292748e8579SChris Lattner addGlobalMapping(GV, GA); 12936bbe3eceSChris Lattner } 1294fbcc0aa1SChris Lattner 12955457ce9aSNicolas Geoffray // Don't initialize if it's thread local, let the client do it. 12965457ce9aSNicolas Geoffray if (!GV->isThreadLocal()) 12976bbe3eceSChris Lattner InitializeMemory(GV->getInitializer(), GA); 12985457ce9aSNicolas Geoffray 1299229907cdSChris Lattner Type *ElTy = GV->getType()->getElementType(); 1300cdfe20b9SMicah Villmow size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy); 1301df1f1524SChris Lattner NumInitBytes += (unsigned)GVSize; 13026bbe3eceSChris Lattner ++NumGlobals; 1303996fe010SChris Lattner } 1304f98e981cSJeffrey Yasskin 1305d0fc8f80SJeffrey Yasskin ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE) 1306d0fc8f80SJeffrey Yasskin : EE(EE), GlobalAddressMap(this) { 1307f98e981cSJeffrey Yasskin } 1308f98e981cSJeffrey Yasskin 1309868e3f09SDaniel Dunbar sys::Mutex * 1310868e3f09SDaniel Dunbar ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) { 1311d0fc8f80SJeffrey Yasskin return &EES->EE.lock; 1312d0fc8f80SJeffrey Yasskin } 1313868e3f09SDaniel Dunbar 1314868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES, 1315868e3f09SDaniel Dunbar const GlobalValue *Old) { 1316d0fc8f80SJeffrey Yasskin void *OldVal = EES->GlobalAddressMap.lookup(Old); 1317d0fc8f80SJeffrey Yasskin EES->GlobalAddressReverseMap.erase(OldVal); 1318d0fc8f80SJeffrey Yasskin } 1319d0fc8f80SJeffrey Yasskin 1320868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *, 1321868e3f09SDaniel Dunbar const GlobalValue *, 1322868e3f09SDaniel Dunbar const GlobalValue *) { 1323a2886c21SCraig Topper llvm_unreachable("The ExecutionEngine doesn't know how to handle a" 1324f98e981cSJeffrey Yasskin " RAUW on a value it has a global mapping for."); 1325f98e981cSJeffrey Yasskin } 1326