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 156bf87df5SJeffrey Yasskin #include "llvm/ExecutionEngine/ExecutionEngine.h" 16868e3f09SDaniel Dunbar #include "llvm/ADT/SmallString.h" 17390d78b3SChris Lattner #include "llvm/ADT/Statistic.h" 18ed0881b2SChandler Carruth #include "llvm/ExecutionEngine/GenericValue.h" 198a8cd2baSChandler Carruth #include "llvm/ExecutionEngine/JITMemoryManager.h" 208a8cd2baSChandler Carruth #include "llvm/ExecutionEngine/ObjectCache.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" 264220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h" 2735907d8eSDavid Blaikie #include "llvm/Object/ObjectFile.h" 287c16caa3SReid Spencer #include "llvm/Support/Debug.h" 29ed0881b2SChandler Carruth #include "llvm/Support/DynamicLibrary.h" 306c2d233eSTorok Edwin #include "llvm/Support/ErrorHandling.h" 31ed0881b2SChandler Carruth #include "llvm/Support/Host.h" 326d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h" 33ed0881b2SChandler Carruth #include "llvm/Support/TargetRegistry.h" 34ccb29cd2STorok Edwin #include "llvm/Support/raw_ostream.h" 358418fdcdSDylan Noblesmith #include "llvm/Target/TargetMachine.h" 36579f0713SAnton Korobeynikov #include <cmath> 37579f0713SAnton Korobeynikov #include <cstring> 3829681deeSChris Lattner using namespace llvm; 39996fe010SChris Lattner 40f58e376dSChandler Carruth #define DEBUG_TYPE "jit" 41f58e376dSChandler Carruth 42c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 43c346ecd7SChris Lattner STATISTIC(NumGlobals , "Number of global vars initialized"); 44996fe010SChris Lattner 45d12ccbd3SJuergen Ributzka // Pin the vtable to this file. 46d12ccbd3SJuergen Ributzka void ObjectCache::anchor() {} 47d12ccbd3SJuergen Ributzka void ObjectBuffer::anchor() {} 48d12ccbd3SJuergen Ributzka void ObjectBufferStream::anchor() {} 49d12ccbd3SJuergen Ributzka 5031faefffSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::JITCtor)( 5131faefffSJeffrey Yasskin Module *M, 52fc8a2d5aSReid Kleckner std::string *ErrorStr, 53fc8a2d5aSReid Kleckner JITMemoryManager *JMM, 54700d08e1SEric Christopher bool GVsWithCode, 552617dcceSCraig Topper TargetMachine *TM) = nullptr; 5670ff8b05SDaniel Dunbar ExecutionEngine *(*ExecutionEngine::MCJITCtor)( 5770ff8b05SDaniel Dunbar Module *M, 5870ff8b05SDaniel Dunbar std::string *ErrorStr, 599bc53e84SFilip Pizlo RTDyldMemoryManager *MCJMM, 602617dcceSCraig Topper TargetMachine *TM) = nullptr; 61091217beSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M, 622617dcceSCraig Topper std::string *ErrorStr) =nullptr; 632d52c1b8SChris Lattner 64091217beSJeffrey Yasskin ExecutionEngine::ExecutionEngine(Module *M) 65f98e981cSJeffrey Yasskin : EEState(*this), 662617dcceSCraig Topper LazyFunctionCreator(nullptr) { 674567db45SJeffrey Yasskin CompilingLazily = false; 68cdc0060eSEvan Cheng GVCompilationDisabled = false; 6984a9055eSEvan Cheng SymbolSearchingDisabled = false; 70bc876017SLang Hames 71bc876017SLang Hames // IR module verification is enabled by default in debug builds, and disabled 72bc876017SLang Hames // by default in release builds. 73bc876017SLang Hames #ifndef NDEBUG 74bc876017SLang Hames VerifyModules = true; 75bc876017SLang Hames #else 76bc876017SLang Hames VerifyModules = false; 77bc876017SLang Hames #endif 78bc876017SLang Hames 79091217beSJeffrey Yasskin Modules.push_back(M); 80091217beSJeffrey Yasskin assert(M && "Module is null?"); 81260b0c88SMisha Brukman } 82260b0c88SMisha Brukman 8392f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() { 84603682adSReid Spencer clearAllGlobalMappings(); 850621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) 860621caefSChris Lattner delete Modules[i]; 8792f8b30dSBrian Gaeke } 8892f8b30dSBrian Gaeke 89a4044332SJeffrey Yasskin namespace { 90868e3f09SDaniel Dunbar /// \brief Helper class which uses a value handler to automatically deletes the 91868e3f09SDaniel Dunbar /// memory block when the GlobalVariable is destroyed. 92a4044332SJeffrey Yasskin class GVMemoryBlock : public CallbackVH { 93a4044332SJeffrey Yasskin GVMemoryBlock(const GlobalVariable *GV) 94a4044332SJeffrey Yasskin : CallbackVH(const_cast<GlobalVariable*>(GV)) {} 95a4044332SJeffrey Yasskin 96a4044332SJeffrey Yasskin public: 97868e3f09SDaniel Dunbar /// \brief Returns the address the GlobalVariable should be written into. The 98868e3f09SDaniel Dunbar /// GVMemoryBlock object prefixes that. 99cdfe20b9SMicah Villmow static char *Create(const GlobalVariable *GV, const DataLayout& TD) { 100229907cdSChris Lattner Type *ElTy = GV->getType()->getElementType(); 101a4044332SJeffrey Yasskin size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy); 102a4044332SJeffrey Yasskin void *RawMemory = ::operator new( 103cdfe20b9SMicah Villmow DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock), 104a4044332SJeffrey Yasskin TD.getPreferredAlignment(GV)) 105a4044332SJeffrey Yasskin + GVSize); 106a4044332SJeffrey Yasskin new(RawMemory) GVMemoryBlock(GV); 107a4044332SJeffrey Yasskin return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock); 108a4044332SJeffrey Yasskin } 109a4044332SJeffrey Yasskin 110b51ff603SCraig Topper void deleted() override { 111a4044332SJeffrey Yasskin // We allocated with operator new and with some extra memory hanging off the 112a4044332SJeffrey Yasskin // end, so don't just delete this. I'm not sure if this is actually 113a4044332SJeffrey Yasskin // required. 114a4044332SJeffrey Yasskin this->~GVMemoryBlock(); 115a4044332SJeffrey Yasskin ::operator delete(this); 116a4044332SJeffrey Yasskin } 117a4044332SJeffrey Yasskin }; 118a4044332SJeffrey Yasskin } // anonymous namespace 119a4044332SJeffrey Yasskin 120a4044332SJeffrey Yasskin char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) { 121cdfe20b9SMicah Villmow return GVMemoryBlock::Create(GV, *getDataLayout()); 1225457ce9aSNicolas Geoffray } 1235457ce9aSNicolas Geoffray 12435907d8eSDavid Blaikie void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) { 12535907d8eSDavid Blaikie llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile."); 12635907d8eSDavid Blaikie } 12735907d8eSDavid Blaikie 128091217beSJeffrey Yasskin bool ExecutionEngine::removeModule(Module *M) { 129af0dea13SCraig Topper for(SmallVectorImpl<Module *>::iterator I = Modules.begin(), 130324fe890SDevang Patel E = Modules.end(); I != E; ++I) { 131091217beSJeffrey Yasskin Module *Found = *I; 132091217beSJeffrey Yasskin if (Found == M) { 133324fe890SDevang Patel Modules.erase(I); 134091217beSJeffrey Yasskin clearGlobalMappingsFromModule(M); 135091217beSJeffrey Yasskin return true; 136324fe890SDevang Patel } 137324fe890SDevang Patel } 138091217beSJeffrey Yasskin return false; 139617001d8SNate Begeman } 140617001d8SNate Begeman 1410621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 1420621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 143091217beSJeffrey Yasskin if (Function *F = Modules[i]->getFunction(FnName)) 1440621caefSChris Lattner return F; 1450621caefSChris Lattner } 1462617dcceSCraig Topper return nullptr; 1470621caefSChris Lattner } 1480621caefSChris Lattner 1490621caefSChris Lattner 1502f825df6SZachary Turner void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) { 151d0fc8f80SJeffrey Yasskin GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap); 152307c053fSJeffrey Yasskin void *OldVal; 153868e3f09SDaniel Dunbar 154868e3f09SDaniel Dunbar // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the 155868e3f09SDaniel Dunbar // GlobalAddressMap. 156307c053fSJeffrey Yasskin if (I == GlobalAddressMap.end()) 1572617dcceSCraig Topper OldVal = nullptr; 158307c053fSJeffrey Yasskin else { 159307c053fSJeffrey Yasskin OldVal = I->second; 160307c053fSJeffrey Yasskin GlobalAddressMap.erase(I); 161307c053fSJeffrey Yasskin } 162307c053fSJeffrey Yasskin 163307c053fSJeffrey Yasskin GlobalAddressReverseMap.erase(OldVal); 164307c053fSJeffrey Yasskin return OldVal; 165307c053fSJeffrey Yasskin } 166307c053fSJeffrey Yasskin 1676d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 168c04b892fSZachary Turner MutexGuard locked(lock); 1696d8dd189SChris Lattner 1700967d2dfSDavid Greene DEBUG(dbgs() << "JIT: Map \'" << GV->getName() 1719813b0b0SDaniel Dunbar << "\' to [" << Addr << "]\n";); 1722f825df6SZachary Turner void *&CurVal = EEState.getGlobalAddressMap()[GV]; 1732617dcceSCraig Topper assert((!CurVal || !Addr) && "GlobalMapping already established!"); 1746d8dd189SChris Lattner CurVal = Addr; 1756d8dd189SChris Lattner 176868e3f09SDaniel Dunbar // If we are using the reverse mapping, add it too. 1772f825df6SZachary Turner if (!EEState.getGlobalAddressReverseMap().empty()) { 1786bf87df5SJeffrey Yasskin AssertingVH<const GlobalValue> &V = 1792f825df6SZachary Turner EEState.getGlobalAddressReverseMap()[Addr]; 1802617dcceSCraig Topper assert((!V || !GV) && "GlobalMapping already established!"); 1816d8dd189SChris Lattner V = GV; 1826d8dd189SChris Lattner } 1836d8dd189SChris Lattner } 1846d8dd189SChris Lattner 1856d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() { 186c04b892fSZachary Turner MutexGuard locked(lock); 1876d8dd189SChris Lattner 1882f825df6SZachary Turner EEState.getGlobalAddressMap().clear(); 1892f825df6SZachary Turner EEState.getGlobalAddressReverseMap().clear(); 1906d8dd189SChris Lattner } 1916d8dd189SChris Lattner 1928f83fc4dSNate Begeman void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) { 193c04b892fSZachary Turner MutexGuard locked(lock); 1948f83fc4dSNate Begeman 195868e3f09SDaniel Dunbar for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) 1962f825df6SZachary Turner EEState.RemoveMapping(FI); 1978f83fc4dSNate Begeman for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 198868e3f09SDaniel Dunbar GI != GE; ++GI) 1992f825df6SZachary Turner EEState.RemoveMapping(GI); 2008f83fc4dSNate Begeman } 2018f83fc4dSNate Begeman 202ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 203c04b892fSZachary Turner MutexGuard locked(lock); 2046d8dd189SChris Lattner 205d0fc8f80SJeffrey Yasskin ExecutionEngineState::GlobalAddressMapTy &Map = 2062f825df6SZachary Turner EEState.getGlobalAddressMap(); 207ee181730SChris Lattner 2086d8dd189SChris Lattner // Deleting from the mapping? 2092617dcceSCraig Topper if (!Addr) 2102f825df6SZachary Turner return EEState.RemoveMapping(GV); 211ee181730SChris Lattner 212d0fc8f80SJeffrey Yasskin void *&CurVal = Map[GV]; 213ee181730SChris Lattner void *OldVal = CurVal; 214ee181730SChris Lattner 2152f825df6SZachary Turner if (CurVal && !EEState.getGlobalAddressReverseMap().empty()) 2162f825df6SZachary Turner EEState.getGlobalAddressReverseMap().erase(CurVal); 2176d8dd189SChris Lattner CurVal = Addr; 2186d8dd189SChris Lattner 219868e3f09SDaniel Dunbar // If we are using the reverse mapping, add it too. 2202f825df6SZachary Turner if (!EEState.getGlobalAddressReverseMap().empty()) { 2216bf87df5SJeffrey Yasskin AssertingVH<const GlobalValue> &V = 2222f825df6SZachary Turner EEState.getGlobalAddressReverseMap()[Addr]; 2232617dcceSCraig Topper assert((!V || !GV) && "GlobalMapping already established!"); 2246d8dd189SChris Lattner V = GV; 2256d8dd189SChris Lattner } 226ee181730SChris Lattner return OldVal; 2276d8dd189SChris Lattner } 2286d8dd189SChris Lattner 2296d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 230c04b892fSZachary Turner MutexGuard locked(lock); 2316d8dd189SChris Lattner 232d0fc8f80SJeffrey Yasskin ExecutionEngineState::GlobalAddressMapTy::iterator I = 2332f825df6SZachary Turner EEState.getGlobalAddressMap().find(GV); 2342f825df6SZachary Turner return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr; 2356d8dd189SChris Lattner } 2366d8dd189SChris Lattner 237748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 238c04b892fSZachary Turner MutexGuard locked(lock); 23979876f52SReid Spencer 240748e8579SChris Lattner // If we haven't computed the reverse mapping yet, do so first. 2412f825df6SZachary Turner if (EEState.getGlobalAddressReverseMap().empty()) { 242d0fc8f80SJeffrey Yasskin for (ExecutionEngineState::GlobalAddressMapTy::iterator 2432f825df6SZachary Turner I = EEState.getGlobalAddressMap().begin(), 2442f825df6SZachary Turner E = EEState.getGlobalAddressMap().end(); I != E; ++I) 2452f825df6SZachary Turner EEState.getGlobalAddressReverseMap().insert(std::make_pair( 246e4f47434SDaniel Dunbar I->second, I->first)); 247748e8579SChris Lattner } 248748e8579SChris Lattner 2496bf87df5SJeffrey Yasskin std::map<void *, AssertingVH<const GlobalValue> >::iterator I = 2502f825df6SZachary Turner EEState.getGlobalAddressReverseMap().find(Addr); 2512f825df6SZachary Turner return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr; 252748e8579SChris Lattner } 2535a0d4829SChris Lattner 254bfd38abbSJeffrey Yasskin namespace { 255bfd38abbSJeffrey Yasskin class ArgvArray { 256bfd38abbSJeffrey Yasskin char *Array; 257bfd38abbSJeffrey Yasskin std::vector<char*> Values; 258bfd38abbSJeffrey Yasskin public: 2592617dcceSCraig Topper ArgvArray() : Array(nullptr) {} 260bfd38abbSJeffrey Yasskin ~ArgvArray() { clear(); } 261bfd38abbSJeffrey Yasskin void clear() { 262bfd38abbSJeffrey Yasskin delete[] Array; 2632617dcceSCraig Topper Array = nullptr; 264bfd38abbSJeffrey Yasskin for (size_t I = 0, E = Values.size(); I != E; ++I) { 265bfd38abbSJeffrey Yasskin delete[] Values[I]; 266bfd38abbSJeffrey Yasskin } 267bfd38abbSJeffrey Yasskin Values.clear(); 268bfd38abbSJeffrey Yasskin } 269bfd38abbSJeffrey Yasskin /// Turn a vector of strings into a nice argv style array of pointers to null 270bfd38abbSJeffrey Yasskin /// terminated strings. 271bfd38abbSJeffrey Yasskin void *reset(LLVMContext &C, ExecutionEngine *EE, 272bfd38abbSJeffrey Yasskin const std::vector<std::string> &InputArgv); 273bfd38abbSJeffrey Yasskin }; 274bfd38abbSJeffrey Yasskin } // anonymous namespace 275bfd38abbSJeffrey Yasskin void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE, 2765a0d4829SChris Lattner const std::vector<std::string> &InputArgv) { 277bfd38abbSJeffrey Yasskin clear(); // Free the old contents. 2785da3f051SChandler Carruth unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 279bfd38abbSJeffrey Yasskin Array = new char[(InputArgv.size()+1)*PtrSize]; 2805a0d4829SChris Lattner 281bfd38abbSJeffrey Yasskin DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n"); 282229907cdSChris Lattner Type *SBytePtr = Type::getInt8PtrTy(C); 2835a0d4829SChris Lattner 2845a0d4829SChris Lattner for (unsigned i = 0; i != InputArgv.size(); ++i) { 2855a0d4829SChris Lattner unsigned Size = InputArgv[i].size()+1; 2865a0d4829SChris Lattner char *Dest = new char[Size]; 287bfd38abbSJeffrey Yasskin Values.push_back(Dest); 2880967d2dfSDavid Greene DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n"); 2895a0d4829SChris Lattner 2905a0d4829SChris Lattner std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 2915a0d4829SChris Lattner Dest[Size-1] = 0; 2925a0d4829SChris Lattner 293bfd38abbSJeffrey Yasskin // Endian safe: Array[i] = (PointerTy)Dest; 294bfd38abbSJeffrey Yasskin EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize), 2955a0d4829SChris Lattner SBytePtr); 2965a0d4829SChris Lattner } 2975a0d4829SChris Lattner 2985a0d4829SChris Lattner // Null terminate it 2992617dcceSCraig Topper EE->StoreValueToMemory(PTOGV(nullptr), 300bfd38abbSJeffrey Yasskin (GenericValue*)(Array+InputArgv.size()*PtrSize), 3015a0d4829SChris Lattner SBytePtr); 302bfd38abbSJeffrey Yasskin return Array; 3035a0d4829SChris Lattner } 3045a0d4829SChris Lattner 30541fa2bd1SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(Module *module, 30641fa2bd1SChris Lattner bool isDtors) { 307faae50b6SChris Lattner const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 3081a9a0b7bSEvan Cheng GlobalVariable *GV = module->getNamedGlobal(Name); 309fe36eaebSChris Lattner 310fe36eaebSChris Lattner // If this global has internal linkage, or if it has a use, then it must be 311fe36eaebSChris Lattner // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 3120621caefSChris Lattner // this is the case, don't execute any of the global ctors, __main will do 3130621caefSChris Lattner // it. 3146de96a1bSRafael Espindola if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return; 315faae50b6SChris Lattner 3160cbfcb2bSNick Lewycky // Should be an array of '{ i32, void ()* }' structs. The first value is 3170621caefSChris Lattner // the init priority, which we ignore. 31800245f42SChris Lattner ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 3192617dcceSCraig Topper if (!InitList) 3200f857898SNick Lewycky return; 321868e3f09SDaniel Dunbar for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 32200245f42SChris Lattner ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i)); 3232617dcceSCraig Topper if (!CS) continue; 324faae50b6SChris Lattner 325faae50b6SChris Lattner Constant *FP = CS->getOperand(1); 326faae50b6SChris Lattner if (FP->isNullValue()) 3270f857898SNick Lewycky continue; // Found a sentinal value, ignore. 328faae50b6SChris Lattner 329868e3f09SDaniel Dunbar // Strip off constant expression casts. 330faae50b6SChris Lattner if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 3316c38f0bbSReid Spencer if (CE->isCast()) 332faae50b6SChris Lattner FP = CE->getOperand(0); 333868e3f09SDaniel Dunbar 334faae50b6SChris Lattner // Execute the ctor/dtor function! 335868e3f09SDaniel Dunbar if (Function *F = dyn_cast<Function>(FP)) 336faae50b6SChris Lattner runFunction(F, std::vector<GenericValue>()); 337868e3f09SDaniel Dunbar 338868e3f09SDaniel Dunbar // FIXME: It is marginally lame that we just do nothing here if we see an 339868e3f09SDaniel Dunbar // entry we don't recognize. It might not be unreasonable for the verifier 340868e3f09SDaniel Dunbar // to not even allow this and just assert here. 341faae50b6SChris Lattner } 342faae50b6SChris Lattner } 3431a9a0b7bSEvan Cheng 3441a9a0b7bSEvan Cheng void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 3451a9a0b7bSEvan Cheng // Execute global ctors/dtors for each module in the program. 346868e3f09SDaniel Dunbar for (unsigned i = 0, e = Modules.size(); i != e; ++i) 347868e3f09SDaniel Dunbar runStaticConstructorsDestructors(Modules[i], isDtors); 3480621caefSChris Lattner } 349faae50b6SChris Lattner 350cf3e3017SDan Gohman #ifndef NDEBUG 3511202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null. 3521202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) { 3535da3f051SChandler Carruth unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 3541202d1b1SDuncan Sands for (unsigned i = 0; i < PtrSize; ++i) 3551202d1b1SDuncan Sands if (*(i + (uint8_t*)Loc)) 3561202d1b1SDuncan Sands return false; 3571202d1b1SDuncan Sands return true; 3581202d1b1SDuncan Sands } 359cf3e3017SDan Gohman #endif 3601202d1b1SDuncan Sands 3615a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn, 3625a0d4829SChris Lattner const std::vector<std::string> &argv, 3635a0d4829SChris Lattner const char * const * envp) { 3645a0d4829SChris Lattner std::vector<GenericValue> GVArgs; 3655a0d4829SChris Lattner GenericValue GVArgc; 36687aa65f4SReid Spencer GVArgc.IntVal = APInt(32, argv.size()); 3678c32c111SAnton Korobeynikov 3688c32c111SAnton Korobeynikov // Check main() type 369b1cad0b3SChris Lattner unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 370229907cdSChris Lattner FunctionType *FTy = Fn->getFunctionType(); 371229907cdSChris Lattner Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo(); 372868e3f09SDaniel Dunbar 373868e3f09SDaniel Dunbar // Check the argument types. 374868e3f09SDaniel Dunbar if (NumArgs > 3) 3752104b8d3SChris Lattner report_fatal_error("Invalid number of arguments of main() supplied"); 376868e3f09SDaniel Dunbar if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty) 377868e3f09SDaniel Dunbar report_fatal_error("Invalid type for third argument of main() supplied"); 378868e3f09SDaniel Dunbar if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty) 379868e3f09SDaniel Dunbar report_fatal_error("Invalid type for second argument of main() supplied"); 380868e3f09SDaniel Dunbar if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32)) 381868e3f09SDaniel Dunbar report_fatal_error("Invalid type for first argument of main() supplied"); 382868e3f09SDaniel Dunbar if (!FTy->getReturnType()->isIntegerTy() && 383868e3f09SDaniel Dunbar !FTy->getReturnType()->isVoidTy()) 384868e3f09SDaniel Dunbar report_fatal_error("Invalid return type of main() supplied"); 3858c32c111SAnton Korobeynikov 386bfd38abbSJeffrey Yasskin ArgvArray CArgv; 387bfd38abbSJeffrey Yasskin ArgvArray CEnv; 388b1cad0b3SChris Lattner if (NumArgs) { 3895a0d4829SChris Lattner GVArgs.push_back(GVArgc); // Arg #0 = argc. 390b1cad0b3SChris Lattner if (NumArgs > 1) { 39155f1c09eSOwen Anderson // Arg #1 = argv. 392bfd38abbSJeffrey Yasskin GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv))); 3931202d1b1SDuncan Sands assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) && 394b1cad0b3SChris Lattner "argv[0] was null after CreateArgv"); 395b1cad0b3SChris Lattner if (NumArgs > 2) { 3965a0d4829SChris Lattner std::vector<std::string> EnvVars; 3975a0d4829SChris Lattner for (unsigned i = 0; envp[i]; ++i) 3985a0d4829SChris Lattner EnvVars.push_back(envp[i]); 39955f1c09eSOwen Anderson // Arg #2 = envp. 400bfd38abbSJeffrey Yasskin GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars))); 401b1cad0b3SChris Lattner } 402b1cad0b3SChris Lattner } 403b1cad0b3SChris Lattner } 404868e3f09SDaniel Dunbar 40587aa65f4SReid Spencer return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 4065a0d4829SChris Lattner } 4075a0d4829SChris Lattner 408322db9eaSAlp Toker void EngineBuilder::InitEngine() { 409322db9eaSAlp Toker WhichEngine = EngineKind::Either; 410322db9eaSAlp Toker ErrorStr = nullptr; 411322db9eaSAlp Toker OptLevel = CodeGenOpt::Default; 412322db9eaSAlp Toker MCJMM = nullptr; 413322db9eaSAlp Toker JMM = nullptr; 414322db9eaSAlp Toker Options = TargetOptions(); 415322db9eaSAlp Toker AllocateGVsWithCode = false; 416322db9eaSAlp Toker RelocModel = Reloc::Default; 417322db9eaSAlp Toker CMModel = CodeModel::JITDefault; 418322db9eaSAlp Toker UseMCJIT = false; 419322db9eaSAlp Toker 420322db9eaSAlp Toker // IR module verification is enabled by default in debug builds, and disabled 421322db9eaSAlp Toker // by default in release builds. 422322db9eaSAlp Toker #ifndef NDEBUG 423322db9eaSAlp Toker VerifyModules = true; 424322db9eaSAlp Toker #else 425322db9eaSAlp Toker VerifyModules = false; 426322db9eaSAlp Toker #endif 427322db9eaSAlp Toker } 428322db9eaSAlp Toker 429add6f1d2SOwen Anderson ExecutionEngine *EngineBuilder::create(TargetMachine *TM) { 43056440fd8SAhmed Charles std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership. 43125a3d816SBenjamin Kramer 432a53414fdSNick Lewycky // Make sure we can resolve symbols in the program as well. The zero arg 433a53414fdSNick Lewycky // to the function tells DynamicLibrary to load the program, not a library. 4342617dcceSCraig Topper if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr)) 4352617dcceSCraig Topper return nullptr; 436a53414fdSNick Lewycky 4379bc53e84SFilip Pizlo assert(!(JMM && MCJMM)); 4389bc53e84SFilip Pizlo 439fc8a2d5aSReid Kleckner // If the user specified a memory manager but didn't specify which engine to 440fc8a2d5aSReid Kleckner // create, we assume they only want the JIT, and we fail if they only want 441fc8a2d5aSReid Kleckner // the interpreter. 4429bc53e84SFilip Pizlo if (JMM || MCJMM) { 44341fa2bd1SChris Lattner if (WhichEngine & EngineKind::JIT) 444fc8a2d5aSReid Kleckner WhichEngine = EngineKind::JIT; 44541fa2bd1SChris Lattner else { 4468bcc6445SChris Lattner if (ErrorStr) 447fc8a2d5aSReid Kleckner *ErrorStr = "Cannot create an interpreter with a memory manager."; 4482617dcceSCraig Topper return nullptr; 449fc8a2d5aSReid Kleckner } 4504bd3bd5bSBrian Gaeke } 4514bd3bd5bSBrian Gaeke 4529bc53e84SFilip Pizlo if (MCJMM && ! UseMCJIT) { 4539bc53e84SFilip Pizlo if (ErrorStr) 4549bc53e84SFilip Pizlo *ErrorStr = 4559bc53e84SFilip Pizlo "Cannot create a legacy JIT with a runtime dyld memory " 4569bc53e84SFilip Pizlo "manager."; 4572617dcceSCraig Topper return nullptr; 4589bc53e84SFilip Pizlo } 4599bc53e84SFilip Pizlo 460fc8a2d5aSReid Kleckner // Unless the interpreter was explicitly selected or the JIT is not linked, 461fc8a2d5aSReid Kleckner // try making a JIT. 46225a3d816SBenjamin Kramer if ((WhichEngine & EngineKind::JIT) && TheTM) { 4637f26246aSDylan Noblesmith Triple TT(M->getTargetTriple()); 4647f26246aSDylan Noblesmith if (!TM->getTarget().hasJIT()) { 4657f26246aSDylan Noblesmith errs() << "WARNING: This target JIT is not designed for the host" 4667f26246aSDylan Noblesmith << " you are running. If bad things happen, please choose" 4677f26246aSDylan Noblesmith << " a different -march switch.\n"; 4687f26246aSDylan Noblesmith } 4697f26246aSDylan Noblesmith 470bc876017SLang Hames ExecutionEngine *EE = nullptr; 471bc876017SLang Hames if (UseMCJIT && ExecutionEngine::MCJITCtor) 472bc876017SLang Hames EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM, 473*b9a23cdcSRafael Espindola TheTM.release()); 474bc876017SLang Hames else if (ExecutionEngine::JITCtor) 475bc876017SLang Hames EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM, 47696c9d95fSAhmed Charles AllocateGVsWithCode, TheTM.release()); 477bc876017SLang Hames 478bc876017SLang Hames if (EE) { 479bc876017SLang Hames EE->setVerifyModules(VerifyModules); 480bc876017SLang Hames return EE; 48141fa2bd1SChris Lattner } 482fc8a2d5aSReid Kleckner } 483fc8a2d5aSReid Kleckner 484fc8a2d5aSReid Kleckner // If we can't make a JIT and we didn't request one specifically, try making 485fc8a2d5aSReid Kleckner // an interpreter instead. 48641fa2bd1SChris Lattner if (WhichEngine & EngineKind::Interpreter) { 48741fa2bd1SChris Lattner if (ExecutionEngine::InterpCtor) 488091217beSJeffrey Yasskin return ExecutionEngine::InterpCtor(M, ErrorStr); 4898bcc6445SChris Lattner if (ErrorStr) 49041fa2bd1SChris Lattner *ErrorStr = "Interpreter has not been linked in."; 4912617dcceSCraig Topper return nullptr; 492fc8a2d5aSReid Kleckner } 493fc8a2d5aSReid Kleckner 4942617dcceSCraig Topper if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor && 4952617dcceSCraig Topper !ExecutionEngine::MCJITCtor) { 4968bcc6445SChris Lattner if (ErrorStr) 4978bcc6445SChris Lattner *ErrorStr = "JIT has not been linked in."; 4988bcc6445SChris Lattner } 499868e3f09SDaniel Dunbar 5002617dcceSCraig Topper return nullptr; 501b5163bb9SChris Lattner } 502b5163bb9SChris Lattner 503996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 5041678e859SBrian Gaeke if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 505996fe010SChris Lattner return getPointerToFunction(F); 506996fe010SChris Lattner 507c04b892fSZachary Turner MutexGuard locked(lock); 5082f825df6SZachary Turner if (void *P = EEState.getGlobalAddressMap()[GV]) 509868e3f09SDaniel Dunbar return P; 51069e84901SJeff Cohen 51169e84901SJeff Cohen // Global variable might have been added since interpreter started. 51269e84901SJeff Cohen if (GlobalVariable *GVar = 51369e84901SJeff Cohen const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 51469e84901SJeff Cohen EmitGlobalVariable(GVar); 51569e84901SJeff Cohen else 516fbcc663cSTorok Edwin llvm_unreachable("Global hasn't had an address allocated yet!"); 517868e3f09SDaniel Dunbar 5182f825df6SZachary Turner return EEState.getGlobalAddressMap()[GV]; 519996fe010SChris Lattner } 520996fe010SChris Lattner 521868e3f09SDaniel Dunbar /// \brief Converts a Constant* into a GenericValue, including handling of 522868e3f09SDaniel Dunbar /// ConstantExpr values. 523996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 5246c38f0bbSReid Spencer // If its undefined, return the garbage. 525bcbdbfb3SJay Foad if (isa<UndefValue>(C)) { 526bcbdbfb3SJay Foad GenericValue Result; 527bcbdbfb3SJay Foad switch (C->getType()->getTypeID()) { 528be79a7acSNadav Rotem default: 529be79a7acSNadav Rotem break; 530bcbdbfb3SJay Foad case Type::IntegerTyID: 531bcbdbfb3SJay Foad case Type::X86_FP80TyID: 532bcbdbfb3SJay Foad case Type::FP128TyID: 533bcbdbfb3SJay Foad case Type::PPC_FP128TyID: 534bcbdbfb3SJay Foad // Although the value is undefined, we still have to construct an APInt 535bcbdbfb3SJay Foad // with the correct bit width. 536bcbdbfb3SJay Foad Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0); 537bcbdbfb3SJay Foad break; 5388e97f016SElena Demikhovsky case Type::StructTyID: { 5398e97f016SElena Demikhovsky // if the whole struct is 'undef' just reserve memory for the value. 5408e97f016SElena Demikhovsky if(StructType *STy = dyn_cast<StructType>(C->getType())) { 5418e97f016SElena Demikhovsky unsigned int elemNum = STy->getNumElements(); 5428e97f016SElena Demikhovsky Result.AggregateVal.resize(elemNum); 5438e97f016SElena Demikhovsky for (unsigned int i = 0; i < elemNum; ++i) { 5448e97f016SElena Demikhovsky Type *ElemTy = STy->getElementType(i); 5458e97f016SElena Demikhovsky if (ElemTy->isIntegerTy()) 5468e97f016SElena Demikhovsky Result.AggregateVal[i].IntVal = 5478e97f016SElena Demikhovsky APInt(ElemTy->getPrimitiveSizeInBits(), 0); 5488e97f016SElena Demikhovsky else if (ElemTy->isAggregateType()) { 5498e97f016SElena Demikhovsky const Constant *ElemUndef = UndefValue::get(ElemTy); 5508e97f016SElena Demikhovsky Result.AggregateVal[i] = getConstantValue(ElemUndef); 5518e97f016SElena Demikhovsky } 5528e97f016SElena Demikhovsky } 5538e97f016SElena Demikhovsky } 5548e97f016SElena Demikhovsky } 5558e97f016SElena Demikhovsky break; 556be79a7acSNadav Rotem case Type::VectorTyID: 557be79a7acSNadav Rotem // if the whole vector is 'undef' just reserve memory for the value. 558be79a7acSNadav Rotem const VectorType* VTy = dyn_cast<VectorType>(C->getType()); 559be79a7acSNadav Rotem const Type *ElemTy = VTy->getElementType(); 560be79a7acSNadav Rotem unsigned int elemNum = VTy->getNumElements(); 561be79a7acSNadav Rotem Result.AggregateVal.resize(elemNum); 562be79a7acSNadav Rotem if (ElemTy->isIntegerTy()) 563be79a7acSNadav Rotem for (unsigned int i = 0; i < elemNum; ++i) 564be79a7acSNadav Rotem Result.AggregateVal[i].IntVal = 565be79a7acSNadav Rotem APInt(ElemTy->getPrimitiveSizeInBits(), 0); 566bcbdbfb3SJay Foad break; 567bcbdbfb3SJay Foad } 568bcbdbfb3SJay Foad return Result; 569bcbdbfb3SJay Foad } 5709de0d14dSChris Lattner 571868e3f09SDaniel Dunbar // Otherwise, if the value is a ConstantExpr... 5726c38f0bbSReid Spencer if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 5734fd528f2SReid Spencer Constant *Op0 = CE->getOperand(0); 5749de0d14dSChris Lattner switch (CE->getOpcode()) { 5759de0d14dSChris Lattner case Instruction::GetElementPtr: { 5766c38f0bbSReid Spencer // Compute the index 5774fd528f2SReid Spencer GenericValue Result = getConstantValue(Op0); 5787c68bebbSRafael Espindola APInt Offset(DL->getPointerSizeInBits(), 0); 5797c68bebbSRafael Espindola cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset); 5809de0d14dSChris Lattner 58187aa65f4SReid Spencer char* tmp = (char*) Result.PointerVal; 582b6ad9822SNuno Lopes Result = PTOGV(tmp + Offset.getSExtValue()); 5839de0d14dSChris Lattner return Result; 5849de0d14dSChris Lattner } 5854fd528f2SReid Spencer case Instruction::Trunc: { 5864fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5874fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 5884fd528f2SReid Spencer GV.IntVal = GV.IntVal.trunc(BitWidth); 5894fd528f2SReid Spencer return GV; 5904fd528f2SReid Spencer } 5914fd528f2SReid Spencer case Instruction::ZExt: { 5924fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5934fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 5944fd528f2SReid Spencer GV.IntVal = GV.IntVal.zext(BitWidth); 5954fd528f2SReid Spencer return GV; 5964fd528f2SReid Spencer } 5974fd528f2SReid Spencer case Instruction::SExt: { 5984fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5994fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 6004fd528f2SReid Spencer GV.IntVal = GV.IntVal.sext(BitWidth); 6014fd528f2SReid Spencer return GV; 6024fd528f2SReid Spencer } 6034fd528f2SReid Spencer case Instruction::FPTrunc: { 604a1336cf5SDale Johannesen // FIXME long double 6054fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6064fd528f2SReid Spencer GV.FloatVal = float(GV.DoubleVal); 6074fd528f2SReid Spencer return GV; 6084fd528f2SReid Spencer } 6094fd528f2SReid Spencer case Instruction::FPExt:{ 610a1336cf5SDale Johannesen // FIXME long double 6114fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6124fd528f2SReid Spencer GV.DoubleVal = double(GV.FloatVal); 6134fd528f2SReid Spencer return GV; 6144fd528f2SReid Spencer } 6154fd528f2SReid Spencer case Instruction::UIToFP: { 6164fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 617fdd87907SChris Lattner if (CE->getType()->isFloatTy()) 6184fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.roundToDouble()); 619fdd87907SChris Lattner else if (CE->getType()->isDoubleTy()) 6204fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.roundToDouble(); 621fdd87907SChris Lattner else if (CE->getType()->isX86_FP80Ty()) { 62231920b0aSBenjamin Kramer APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 623ca24fd90SDan Gohman (void)apf.convertFromAPInt(GV.IntVal, 624ca24fd90SDan Gohman false, 6259150652bSDale Johannesen APFloat::rmNearestTiesToEven); 62654306fe4SDale Johannesen GV.IntVal = apf.bitcastToAPInt(); 627a1336cf5SDale Johannesen } 6284fd528f2SReid Spencer return GV; 6294fd528f2SReid Spencer } 6304fd528f2SReid Spencer case Instruction::SIToFP: { 6314fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 632fdd87907SChris Lattner if (CE->getType()->isFloatTy()) 6334fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 634fdd87907SChris Lattner else if (CE->getType()->isDoubleTy()) 6354fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 636fdd87907SChris Lattner else if (CE->getType()->isX86_FP80Ty()) { 63731920b0aSBenjamin Kramer APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 638ca24fd90SDan Gohman (void)apf.convertFromAPInt(GV.IntVal, 639ca24fd90SDan Gohman true, 6409150652bSDale Johannesen APFloat::rmNearestTiesToEven); 64154306fe4SDale Johannesen GV.IntVal = apf.bitcastToAPInt(); 642a1336cf5SDale Johannesen } 6434fd528f2SReid Spencer return GV; 6444fd528f2SReid Spencer } 6454fd528f2SReid Spencer case Instruction::FPToUI: // double->APInt conversion handles sign 6464fd528f2SReid Spencer case Instruction::FPToSI: { 6474fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6484fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 649fdd87907SChris Lattner if (Op0->getType()->isFloatTy()) 6504fd528f2SReid Spencer GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 651fdd87907SChris Lattner else if (Op0->getType()->isDoubleTy()) 6524fd528f2SReid Spencer GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 653fdd87907SChris Lattner else if (Op0->getType()->isX86_FP80Ty()) { 65429178a34STim Northover APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal); 655a1336cf5SDale Johannesen uint64_t v; 6564f0bd68cSDale Johannesen bool ignored; 657a1336cf5SDale Johannesen (void)apf.convertToInteger(&v, BitWidth, 658a1336cf5SDale Johannesen CE->getOpcode()==Instruction::FPToSI, 6594f0bd68cSDale Johannesen APFloat::rmTowardZero, &ignored); 660a1336cf5SDale Johannesen GV.IntVal = v; // endian? 661a1336cf5SDale Johannesen } 6624fd528f2SReid Spencer return GV; 6634fd528f2SReid Spencer } 6646c38f0bbSReid Spencer case Instruction::PtrToInt: { 6654fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6667c68bebbSRafael Espindola uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType()); 667fc1f2cd3SEli Friedman assert(PtrWidth <= 64 && "Bad pointer width"); 6684fd528f2SReid Spencer GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 6697c68bebbSRafael Espindola uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType()); 670fc1f2cd3SEli Friedman GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth); 6714fd528f2SReid Spencer return GV; 6724fd528f2SReid Spencer } 6734fd528f2SReid Spencer case Instruction::IntToPtr: { 6744fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6757c68bebbSRafael Espindola uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType()); 6764fd528f2SReid Spencer GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 6774fd528f2SReid Spencer assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 6784fd528f2SReid Spencer GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 6796c38f0bbSReid Spencer return GV; 6806c38f0bbSReid Spencer } 6816c38f0bbSReid Spencer case Instruction::BitCast: { 6824fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 683229907cdSChris Lattner Type* DestTy = CE->getType(); 6844fd528f2SReid Spencer switch (Op0->getType()->getTypeID()) { 685fbcc663cSTorok Edwin default: llvm_unreachable("Invalid bitcast operand"); 6864fd528f2SReid Spencer case Type::IntegerTyID: 6879dff9becSDuncan Sands assert(DestTy->isFloatingPointTy() && "invalid bitcast"); 688fdd87907SChris Lattner if (DestTy->isFloatTy()) 6894fd528f2SReid Spencer GV.FloatVal = GV.IntVal.bitsToFloat(); 690fdd87907SChris Lattner else if (DestTy->isDoubleTy()) 6914fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.bitsToDouble(); 6926c38f0bbSReid Spencer break; 6934fd528f2SReid Spencer case Type::FloatTyID: 6949dff9becSDuncan Sands assert(DestTy->isIntegerTy(32) && "Invalid bitcast"); 6953447fb01SJay Foad GV.IntVal = APInt::floatToBits(GV.FloatVal); 6964fd528f2SReid Spencer break; 6974fd528f2SReid Spencer case Type::DoubleTyID: 6989dff9becSDuncan Sands assert(DestTy->isIntegerTy(64) && "Invalid bitcast"); 6993447fb01SJay Foad GV.IntVal = APInt::doubleToBits(GV.DoubleVal); 7004fd528f2SReid Spencer break; 7014fd528f2SReid Spencer case Type::PointerTyID: 70219d0b47bSDuncan Sands assert(DestTy->isPointerTy() && "Invalid bitcast"); 7034fd528f2SReid Spencer break; // getConstantValue(Op0) above already converted it 7046c38f0bbSReid Spencer } 7054fd528f2SReid Spencer return GV; 70668cbcc3eSChris Lattner } 70768cbcc3eSChris Lattner case Instruction::Add: 708a5b9645cSDan Gohman case Instruction::FAdd: 7094fd528f2SReid Spencer case Instruction::Sub: 710a5b9645cSDan Gohman case Instruction::FSub: 7114fd528f2SReid Spencer case Instruction::Mul: 712a5b9645cSDan Gohman case Instruction::FMul: 7134fd528f2SReid Spencer case Instruction::UDiv: 7144fd528f2SReid Spencer case Instruction::SDiv: 7154fd528f2SReid Spencer case Instruction::URem: 7164fd528f2SReid Spencer case Instruction::SRem: 7174fd528f2SReid Spencer case Instruction::And: 7184fd528f2SReid Spencer case Instruction::Or: 7194fd528f2SReid Spencer case Instruction::Xor: { 7204fd528f2SReid Spencer GenericValue LHS = getConstantValue(Op0); 7214fd528f2SReid Spencer GenericValue RHS = getConstantValue(CE->getOperand(1)); 7224fd528f2SReid Spencer GenericValue GV; 723c4e6bb5fSChris Lattner switch (CE->getOperand(0)->getType()->getTypeID()) { 724fbcc663cSTorok Edwin default: llvm_unreachable("Bad add type!"); 7257a9c62baSReid Spencer case Type::IntegerTyID: 7264fd528f2SReid Spencer switch (CE->getOpcode()) { 727fbcc663cSTorok Edwin default: llvm_unreachable("Invalid integer opcode"); 7284fd528f2SReid Spencer case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 7294fd528f2SReid Spencer case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 7304fd528f2SReid Spencer case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 7314fd528f2SReid Spencer case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 7324fd528f2SReid Spencer case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 7334fd528f2SReid Spencer case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 7344fd528f2SReid Spencer case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 7354fd528f2SReid Spencer case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 7364fd528f2SReid Spencer case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 7374fd528f2SReid Spencer case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 7384fd528f2SReid Spencer } 739c4e6bb5fSChris Lattner break; 740c4e6bb5fSChris Lattner case Type::FloatTyID: 7414fd528f2SReid Spencer switch (CE->getOpcode()) { 742fbcc663cSTorok Edwin default: llvm_unreachable("Invalid float opcode"); 743a5b9645cSDan Gohman case Instruction::FAdd: 7444fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 745a5b9645cSDan Gohman case Instruction::FSub: 7464fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 747a5b9645cSDan Gohman case Instruction::FMul: 7484fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 7494fd528f2SReid Spencer case Instruction::FDiv: 7504fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 7514fd528f2SReid Spencer case Instruction::FRem: 75293cd0f1cSChris Lattner GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break; 7534fd528f2SReid Spencer } 754c4e6bb5fSChris Lattner break; 755c4e6bb5fSChris Lattner case Type::DoubleTyID: 7564fd528f2SReid Spencer switch (CE->getOpcode()) { 757fbcc663cSTorok Edwin default: llvm_unreachable("Invalid double opcode"); 758a5b9645cSDan Gohman case Instruction::FAdd: 7594fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 760a5b9645cSDan Gohman case Instruction::FSub: 7614fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 762a5b9645cSDan Gohman case Instruction::FMul: 7634fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 7644fd528f2SReid Spencer case Instruction::FDiv: 7654fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 7664fd528f2SReid Spencer case Instruction::FRem: 76793cd0f1cSChris Lattner GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 7684fd528f2SReid Spencer } 769c4e6bb5fSChris Lattner break; 770a1336cf5SDale Johannesen case Type::X86_FP80TyID: 771a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 772a1336cf5SDale Johannesen case Type::FP128TyID: { 77329178a34STim Northover const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics(); 77429178a34STim Northover APFloat apfLHS = APFloat(Sem, LHS.IntVal); 775a1336cf5SDale Johannesen switch (CE->getOpcode()) { 776e4f47434SDaniel Dunbar default: llvm_unreachable("Invalid long double opcode"); 777a5b9645cSDan Gohman case Instruction::FAdd: 77829178a34STim Northover apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven); 77954306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 780a1336cf5SDale Johannesen break; 781a5b9645cSDan Gohman case Instruction::FSub: 78229178a34STim Northover apfLHS.subtract(APFloat(Sem, RHS.IntVal), 78329178a34STim Northover APFloat::rmNearestTiesToEven); 78454306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 785a1336cf5SDale Johannesen break; 786a5b9645cSDan Gohman case Instruction::FMul: 78729178a34STim Northover apfLHS.multiply(APFloat(Sem, RHS.IntVal), 78829178a34STim Northover APFloat::rmNearestTiesToEven); 78954306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 790a1336cf5SDale Johannesen break; 791a1336cf5SDale Johannesen case Instruction::FDiv: 79229178a34STim Northover apfLHS.divide(APFloat(Sem, RHS.IntVal), 79329178a34STim Northover APFloat::rmNearestTiesToEven); 79454306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 795a1336cf5SDale Johannesen break; 796a1336cf5SDale Johannesen case Instruction::FRem: 79729178a34STim Northover apfLHS.mod(APFloat(Sem, RHS.IntVal), 79829178a34STim Northover APFloat::rmNearestTiesToEven); 79954306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 800a1336cf5SDale Johannesen break; 801a1336cf5SDale Johannesen } 802a1336cf5SDale Johannesen } 803a1336cf5SDale Johannesen break; 804c4e6bb5fSChris Lattner } 8054fd528f2SReid Spencer return GV; 8064fd528f2SReid Spencer } 8079de0d14dSChris Lattner default: 80868cbcc3eSChris Lattner break; 80968cbcc3eSChris Lattner } 810868e3f09SDaniel Dunbar 811868e3f09SDaniel Dunbar SmallString<256> Msg; 812868e3f09SDaniel Dunbar raw_svector_ostream OS(Msg); 813868e3f09SDaniel Dunbar OS << "ConstantExpr not handled: " << *CE; 814868e3f09SDaniel Dunbar report_fatal_error(OS.str()); 8159de0d14dSChris Lattner } 816996fe010SChris Lattner 817868e3f09SDaniel Dunbar // Otherwise, we have a simple constant. 8184fd528f2SReid Spencer GenericValue Result; 8196b727599SChris Lattner switch (C->getType()->getTypeID()) { 82087aa65f4SReid Spencer case Type::FloatTyID: 821bed9dc42SDale Johannesen Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 8227a9c62baSReid Spencer break; 82387aa65f4SReid Spencer case Type::DoubleTyID: 824bed9dc42SDale Johannesen Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 82587aa65f4SReid Spencer break; 826a1336cf5SDale Johannesen case Type::X86_FP80TyID: 827a1336cf5SDale Johannesen case Type::FP128TyID: 828a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 82954306fe4SDale Johannesen Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt(); 830a1336cf5SDale Johannesen break; 83187aa65f4SReid Spencer case Type::IntegerTyID: 83287aa65f4SReid Spencer Result.IntVal = cast<ConstantInt>(C)->getValue(); 83387aa65f4SReid Spencer break; 834996fe010SChris Lattner case Type::PointerTyID: 8356a0fd73bSReid Spencer if (isa<ConstantPointerNull>(C)) 8362617dcceSCraig Topper Result.PointerVal = nullptr; 8376a0fd73bSReid Spencer else if (const Function *F = dyn_cast<Function>(C)) 8386a0fd73bSReid Spencer Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 8396a0fd73bSReid Spencer else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) 8406a0fd73bSReid Spencer Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 8410c778f70SChris Lattner else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 8420c778f70SChris Lattner Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>( 8430c778f70SChris Lattner BA->getBasicBlock()))); 844e6492f10SChris Lattner else 845fbcc663cSTorok Edwin llvm_unreachable("Unknown constant pointer type!"); 846996fe010SChris Lattner break; 847be79a7acSNadav Rotem case Type::VectorTyID: { 848be79a7acSNadav Rotem unsigned elemNum; 849be79a7acSNadav Rotem Type* ElemTy; 850be79a7acSNadav Rotem const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C); 851be79a7acSNadav Rotem const ConstantVector *CV = dyn_cast<ConstantVector>(C); 852be79a7acSNadav Rotem const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C); 853be79a7acSNadav Rotem 854be79a7acSNadav Rotem if (CDV) { 855be79a7acSNadav Rotem elemNum = CDV->getNumElements(); 856be79a7acSNadav Rotem ElemTy = CDV->getElementType(); 857be79a7acSNadav Rotem } else if (CV || CAZ) { 858be79a7acSNadav Rotem VectorType* VTy = dyn_cast<VectorType>(C->getType()); 859be79a7acSNadav Rotem elemNum = VTy->getNumElements(); 860be79a7acSNadav Rotem ElemTy = VTy->getElementType(); 861be79a7acSNadav Rotem } else { 862be79a7acSNadav Rotem llvm_unreachable("Unknown constant vector type!"); 863be79a7acSNadav Rotem } 864be79a7acSNadav Rotem 865be79a7acSNadav Rotem Result.AggregateVal.resize(elemNum); 866be79a7acSNadav Rotem // Check if vector holds floats. 867be79a7acSNadav Rotem if(ElemTy->isFloatTy()) { 868be79a7acSNadav Rotem if (CAZ) { 869be79a7acSNadav Rotem GenericValue floatZero; 870be79a7acSNadav Rotem floatZero.FloatVal = 0.f; 871be79a7acSNadav Rotem std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 872be79a7acSNadav Rotem floatZero); 873be79a7acSNadav Rotem break; 874be79a7acSNadav Rotem } 875be79a7acSNadav Rotem if(CV) { 876be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 877be79a7acSNadav Rotem if (!isa<UndefValue>(CV->getOperand(i))) 878be79a7acSNadav Rotem Result.AggregateVal[i].FloatVal = cast<ConstantFP>( 879be79a7acSNadav Rotem CV->getOperand(i))->getValueAPF().convertToFloat(); 880be79a7acSNadav Rotem break; 881be79a7acSNadav Rotem } 882be79a7acSNadav Rotem if(CDV) 883be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 884be79a7acSNadav Rotem Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i); 885be79a7acSNadav Rotem 886be79a7acSNadav Rotem break; 887be79a7acSNadav Rotem } 888be79a7acSNadav Rotem // Check if vector holds doubles. 889be79a7acSNadav Rotem if (ElemTy->isDoubleTy()) { 890be79a7acSNadav Rotem if (CAZ) { 891be79a7acSNadav Rotem GenericValue doubleZero; 892be79a7acSNadav Rotem doubleZero.DoubleVal = 0.0; 893be79a7acSNadav Rotem std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 894be79a7acSNadav Rotem doubleZero); 895be79a7acSNadav Rotem break; 896be79a7acSNadav Rotem } 897be79a7acSNadav Rotem if(CV) { 898be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 899be79a7acSNadav Rotem if (!isa<UndefValue>(CV->getOperand(i))) 900be79a7acSNadav Rotem Result.AggregateVal[i].DoubleVal = cast<ConstantFP>( 901be79a7acSNadav Rotem CV->getOperand(i))->getValueAPF().convertToDouble(); 902be79a7acSNadav Rotem break; 903be79a7acSNadav Rotem } 904be79a7acSNadav Rotem if(CDV) 905be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 906be79a7acSNadav Rotem Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i); 907be79a7acSNadav Rotem 908be79a7acSNadav Rotem break; 909be79a7acSNadav Rotem } 910be79a7acSNadav Rotem // Check if vector holds integers. 911be79a7acSNadav Rotem if (ElemTy->isIntegerTy()) { 912be79a7acSNadav Rotem if (CAZ) { 913be79a7acSNadav Rotem GenericValue intZero; 914be79a7acSNadav Rotem intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull); 915be79a7acSNadav Rotem std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 916be79a7acSNadav Rotem intZero); 917be79a7acSNadav Rotem break; 918be79a7acSNadav Rotem } 919be79a7acSNadav Rotem if(CV) { 920be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 921be79a7acSNadav Rotem if (!isa<UndefValue>(CV->getOperand(i))) 922be79a7acSNadav Rotem Result.AggregateVal[i].IntVal = cast<ConstantInt>( 923be79a7acSNadav Rotem CV->getOperand(i))->getValue(); 924be79a7acSNadav Rotem else { 925be79a7acSNadav Rotem Result.AggregateVal[i].IntVal = 926be79a7acSNadav Rotem APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0); 927be79a7acSNadav Rotem } 928be79a7acSNadav Rotem break; 929be79a7acSNadav Rotem } 930be79a7acSNadav Rotem if(CDV) 931be79a7acSNadav Rotem for (unsigned i = 0; i < elemNum; ++i) 932be79a7acSNadav Rotem Result.AggregateVal[i].IntVal = APInt( 933be79a7acSNadav Rotem CDV->getElementType()->getPrimitiveSizeInBits(), 934be79a7acSNadav Rotem CDV->getElementAsInteger(i)); 935be79a7acSNadav Rotem 936be79a7acSNadav Rotem break; 937be79a7acSNadav Rotem } 938be79a7acSNadav Rotem llvm_unreachable("Unknown constant pointer type!"); 939be79a7acSNadav Rotem } 940be79a7acSNadav Rotem break; 941be79a7acSNadav Rotem 942996fe010SChris Lattner default: 943868e3f09SDaniel Dunbar SmallString<256> Msg; 944868e3f09SDaniel Dunbar raw_svector_ostream OS(Msg); 945868e3f09SDaniel Dunbar OS << "ERROR: Constant unimplemented for type: " << *C->getType(); 946868e3f09SDaniel Dunbar report_fatal_error(OS.str()); 947996fe010SChris Lattner } 948868e3f09SDaniel Dunbar 949996fe010SChris Lattner return Result; 950996fe010SChris Lattner } 951996fe010SChris Lattner 9521202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 9531202d1b1SDuncan Sands /// with the integer held in IntVal. 9541202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 9551202d1b1SDuncan Sands unsigned StoreBytes) { 9561202d1b1SDuncan Sands assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 957ad06cee2SRoman Divacky const uint8_t *Src = (const uint8_t *)IntVal.getRawData(); 9585c65cb46SDuncan Sands 95941cb64f4SRafael Espindola if (sys::IsLittleEndianHost) { 9601202d1b1SDuncan Sands // Little-endian host - the source is ordered from LSB to MSB. Order the 9611202d1b1SDuncan Sands // destination from LSB to MSB: Do a straight copy. 9625c65cb46SDuncan Sands memcpy(Dst, Src, StoreBytes); 963868e3f09SDaniel Dunbar } else { 9645c65cb46SDuncan Sands // Big-endian host - the source is an array of 64 bit words ordered from 9651202d1b1SDuncan Sands // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 9661202d1b1SDuncan Sands // from MSB to LSB: Reverse the word order, but not the bytes in a word. 9675c65cb46SDuncan Sands while (StoreBytes > sizeof(uint64_t)) { 9685c65cb46SDuncan Sands StoreBytes -= sizeof(uint64_t); 9695c65cb46SDuncan Sands // May not be aligned so use memcpy. 9705c65cb46SDuncan Sands memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 9715c65cb46SDuncan Sands Src += sizeof(uint64_t); 9725c65cb46SDuncan Sands } 9735c65cb46SDuncan Sands 9745c65cb46SDuncan Sands memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 975815f8dd2SReid Spencer } 9767a9c62baSReid Spencer } 9771202d1b1SDuncan Sands 97809053e62SEvan Cheng void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, 979229907cdSChris Lattner GenericValue *Ptr, Type *Ty) { 980cdfe20b9SMicah Villmow const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty); 9811202d1b1SDuncan Sands 9821202d1b1SDuncan Sands switch (Ty->getTypeID()) { 983be79a7acSNadav Rotem default: 984be79a7acSNadav Rotem dbgs() << "Cannot store value of type " << *Ty << "!\n"; 985be79a7acSNadav Rotem break; 9861202d1b1SDuncan Sands case Type::IntegerTyID: 9871202d1b1SDuncan Sands StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes); 9881202d1b1SDuncan Sands break; 989996fe010SChris Lattner case Type::FloatTyID: 99087aa65f4SReid Spencer *((float*)Ptr) = Val.FloatVal; 99187aa65f4SReid Spencer break; 99287aa65f4SReid Spencer case Type::DoubleTyID: 99387aa65f4SReid Spencer *((double*)Ptr) = Val.DoubleVal; 994996fe010SChris Lattner break; 9954d7e4ee7SDale Johannesen case Type::X86_FP80TyID: 9964d7e4ee7SDale Johannesen memcpy(Ptr, Val.IntVal.getRawData(), 10); 997a1336cf5SDale Johannesen break; 9987a9c62baSReid Spencer case Type::PointerTyID: 9991202d1b1SDuncan Sands // Ensure 64 bit target pointers are fully initialized on 32 bit hosts. 10001202d1b1SDuncan Sands if (StoreBytes != sizeof(PointerTy)) 100193da3c82SChandler Carruth memset(&(Ptr->PointerVal), 0, StoreBytes); 10021202d1b1SDuncan Sands 100387aa65f4SReid Spencer *((PointerTy*)Ptr) = Val.PointerVal; 1004996fe010SChris Lattner break; 1005be79a7acSNadav Rotem case Type::VectorTyID: 1006be79a7acSNadav Rotem for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) { 1007be79a7acSNadav Rotem if (cast<VectorType>(Ty)->getElementType()->isDoubleTy()) 1008be79a7acSNadav Rotem *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal; 1009be79a7acSNadav Rotem if (cast<VectorType>(Ty)->getElementType()->isFloatTy()) 1010be79a7acSNadav Rotem *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal; 1011be79a7acSNadav Rotem if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) { 1012be79a7acSNadav Rotem unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8; 1013be79a7acSNadav Rotem StoreIntToMemory(Val.AggregateVal[i].IntVal, 1014be79a7acSNadav Rotem (uint8_t*)Ptr + numOfBytes*i, numOfBytes); 1015be79a7acSNadav Rotem } 1016be79a7acSNadav Rotem } 1017be79a7acSNadav Rotem break; 1018996fe010SChris Lattner } 10191202d1b1SDuncan Sands 102041cb64f4SRafael Espindola if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian()) 10211202d1b1SDuncan Sands // Host and target are different endian - reverse the stored bytes. 10221202d1b1SDuncan Sands std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr); 1023996fe010SChris Lattner } 1024996fe010SChris Lattner 10251202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 10261202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 10271202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) { 10281202d1b1SDuncan Sands assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 102982b63578SDavid Greene uint8_t *Dst = reinterpret_cast<uint8_t *>( 103082b63578SDavid Greene const_cast<uint64_t *>(IntVal.getRawData())); 10315c65cb46SDuncan Sands 103241cb64f4SRafael Espindola if (sys::IsLittleEndianHost) 10335c65cb46SDuncan Sands // Little-endian host - the destination must be ordered from LSB to MSB. 10345c65cb46SDuncan Sands // The source is ordered from LSB to MSB: Do a straight copy. 10355c65cb46SDuncan Sands memcpy(Dst, Src, LoadBytes); 10365c65cb46SDuncan Sands else { 10375c65cb46SDuncan Sands // Big-endian - the destination is an array of 64 bit words ordered from 10385c65cb46SDuncan Sands // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 10395c65cb46SDuncan Sands // ordered from MSB to LSB: Reverse the word order, but not the bytes in 10405c65cb46SDuncan Sands // a word. 10415c65cb46SDuncan Sands while (LoadBytes > sizeof(uint64_t)) { 10425c65cb46SDuncan Sands LoadBytes -= sizeof(uint64_t); 10435c65cb46SDuncan Sands // May not be aligned so use memcpy. 10445c65cb46SDuncan Sands memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 10455c65cb46SDuncan Sands Dst += sizeof(uint64_t); 10465c65cb46SDuncan Sands } 10475c65cb46SDuncan Sands 10485c65cb46SDuncan Sands memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 10495c65cb46SDuncan Sands } 10507a9c62baSReid Spencer } 10511202d1b1SDuncan Sands 10521202d1b1SDuncan Sands /// FIXME: document 10531202d1b1SDuncan Sands /// 10541202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 10551202d1b1SDuncan Sands GenericValue *Ptr, 1056229907cdSChris Lattner Type *Ty) { 1057cdfe20b9SMicah Villmow const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty); 10581202d1b1SDuncan Sands 10591202d1b1SDuncan Sands switch (Ty->getTypeID()) { 10601202d1b1SDuncan Sands case Type::IntegerTyID: 10611202d1b1SDuncan Sands // An APInt with all words initially zero. 10621202d1b1SDuncan Sands Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0); 10631202d1b1SDuncan Sands LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes); 10641202d1b1SDuncan Sands break; 10657f389e8cSChris Lattner case Type::FloatTyID: 106687aa65f4SReid Spencer Result.FloatVal = *((float*)Ptr); 106787aa65f4SReid Spencer break; 106887aa65f4SReid Spencer case Type::DoubleTyID: 106987aa65f4SReid Spencer Result.DoubleVal = *((double*)Ptr); 10707f389e8cSChris Lattner break; 10717a9c62baSReid Spencer case Type::PointerTyID: 107287aa65f4SReid Spencer Result.PointerVal = *((PointerTy*)Ptr); 10737f389e8cSChris Lattner break; 1074a1336cf5SDale Johannesen case Type::X86_FP80TyID: { 1075a1336cf5SDale Johannesen // This is endian dependent, but it will only work on x86 anyway. 107626d6539eSDuncan Sands // FIXME: Will not trap if loading a signaling NaN. 1077ff306287SDuncan Sands uint64_t y[2]; 10784d7e4ee7SDale Johannesen memcpy(y, Ptr, 10); 10797a162881SJeffrey Yasskin Result.IntVal = APInt(80, y); 1080a1336cf5SDale Johannesen break; 1081a1336cf5SDale Johannesen } 1082be79a7acSNadav Rotem case Type::VectorTyID: { 1083be79a7acSNadav Rotem const VectorType *VT = cast<VectorType>(Ty); 1084be79a7acSNadav Rotem const Type *ElemT = VT->getElementType(); 1085be79a7acSNadav Rotem const unsigned numElems = VT->getNumElements(); 1086be79a7acSNadav Rotem if (ElemT->isFloatTy()) { 1087be79a7acSNadav Rotem Result.AggregateVal.resize(numElems); 1088be79a7acSNadav Rotem for (unsigned i = 0; i < numElems; ++i) 1089be79a7acSNadav Rotem Result.AggregateVal[i].FloatVal = *((float*)Ptr+i); 1090be79a7acSNadav Rotem } 1091be79a7acSNadav Rotem if (ElemT->isDoubleTy()) { 1092be79a7acSNadav Rotem Result.AggregateVal.resize(numElems); 1093be79a7acSNadav Rotem for (unsigned i = 0; i < numElems; ++i) 1094be79a7acSNadav Rotem Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i); 1095be79a7acSNadav Rotem } 1096be79a7acSNadav Rotem if (ElemT->isIntegerTy()) { 1097be79a7acSNadav Rotem GenericValue intZero; 1098be79a7acSNadav Rotem const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth(); 1099be79a7acSNadav Rotem intZero.IntVal = APInt(elemBitWidth, 0); 1100be79a7acSNadav Rotem Result.AggregateVal.resize(numElems, intZero); 1101be79a7acSNadav Rotem for (unsigned i = 0; i < numElems; ++i) 1102be79a7acSNadav Rotem LoadIntFromMemory(Result.AggregateVal[i].IntVal, 1103be79a7acSNadav Rotem (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8); 1104be79a7acSNadav Rotem } 1105be79a7acSNadav Rotem break; 1106be79a7acSNadav Rotem } 11077f389e8cSChris Lattner default: 1108868e3f09SDaniel Dunbar SmallString<256> Msg; 1109868e3f09SDaniel Dunbar raw_svector_ostream OS(Msg); 1110868e3f09SDaniel Dunbar OS << "Cannot load value of type " << *Ty << "!"; 1111868e3f09SDaniel Dunbar report_fatal_error(OS.str()); 11127f389e8cSChris Lattner } 11137f389e8cSChris Lattner } 11147f389e8cSChris Lattner 1115996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 11160967d2dfSDavid Greene DEBUG(dbgs() << "JIT: Initializing " << Addr << " "); 1117b086d382SDale Johannesen DEBUG(Init->dump()); 111800245f42SChris Lattner if (isa<UndefValue>(Init)) 111961753bf8SChris Lattner return; 112000245f42SChris Lattner 112100245f42SChris Lattner if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 112269d62138SRobert Bocchino unsigned ElementSize = 1123cdfe20b9SMicah Villmow getDataLayout()->getTypeAllocSize(CP->getType()->getElementType()); 112469d62138SRobert Bocchino for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 112569d62138SRobert Bocchino InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 112669d62138SRobert Bocchino return; 112700245f42SChris Lattner } 112800245f42SChris Lattner 112900245f42SChris Lattner if (isa<ConstantAggregateZero>(Init)) { 1130cdfe20b9SMicah Villmow memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType())); 11311dd86b11SChris Lattner return; 113200245f42SChris Lattner } 113300245f42SChris Lattner 113400245f42SChris Lattner if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) { 113569ddfbfeSDan Gohman unsigned ElementSize = 1136cdfe20b9SMicah Villmow getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType()); 113769ddfbfeSDan Gohman for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 113869ddfbfeSDan Gohman InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 113969ddfbfeSDan Gohman return; 114000245f42SChris Lattner } 114100245f42SChris Lattner 114200245f42SChris Lattner if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) { 114369ddfbfeSDan Gohman const StructLayout *SL = 1144cdfe20b9SMicah Villmow getDataLayout()->getStructLayout(cast<StructType>(CPS->getType())); 114569ddfbfeSDan Gohman for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 114669ddfbfeSDan Gohman InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 114769ddfbfeSDan Gohman return; 114800245f42SChris Lattner } 114900245f42SChris Lattner 115000245f42SChris Lattner if (const ConstantDataSequential *CDS = 115100245f42SChris Lattner dyn_cast<ConstantDataSequential>(Init)) { 115200245f42SChris Lattner // CDS is already laid out in host memory order. 115300245f42SChris Lattner StringRef Data = CDS->getRawDataValues(); 115400245f42SChris Lattner memcpy(Addr, Data.data(), Data.size()); 115500245f42SChris Lattner return; 115600245f42SChris Lattner } 115700245f42SChris Lattner 115800245f42SChris Lattner if (Init->getType()->isFirstClassType()) { 1159996fe010SChris Lattner GenericValue Val = getConstantValue(Init); 1160996fe010SChris Lattner StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 1161996fe010SChris Lattner return; 1162996fe010SChris Lattner } 1163996fe010SChris Lattner 1164868e3f09SDaniel Dunbar DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n"); 1165fbcc663cSTorok Edwin llvm_unreachable("Unknown constant type to initialize memory with!"); 1166996fe010SChris Lattner } 1167996fe010SChris Lattner 1168996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their 1169996fe010SChris Lattner /// addresses into GlobalAddress. This must make sure to copy the contents of 1170996fe010SChris Lattner /// their initializers into the memory. 1171996fe010SChris Lattner void ExecutionEngine::emitGlobals() { 1172996fe010SChris Lattner // Loop over all of the global variables in the program, allocating the memory 11730621caefSChris Lattner // to hold them. If there is more than one module, do a prepass over globals 11740621caefSChris Lattner // to figure out how the different modules should link together. 1175229907cdSChris Lattner std::map<std::pair<std::string, Type*>, 11760621caefSChris Lattner const GlobalValue*> LinkedGlobalsMap; 11770621caefSChris Lattner 11780621caefSChris Lattner if (Modules.size() != 1) { 11790621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1180091217beSJeffrey Yasskin Module &M = *Modules[m]; 118149bb65a4SRafael Espindola for (const auto &GV : M.globals()) { 118249bb65a4SRafael Espindola if (GV.hasLocalLinkage() || GV.isDeclaration() || 118349bb65a4SRafael Espindola GV.hasAppendingLinkage() || !GV.hasName()) 11840621caefSChris Lattner continue;// Ignore external globals and globals with internal linkage. 11850621caefSChris Lattner 11860621caefSChris Lattner const GlobalValue *&GVEntry = 118749bb65a4SRafael Espindola LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]; 11880621caefSChris Lattner 11890621caefSChris Lattner // If this is the first time we've seen this global, it is the canonical 11900621caefSChris Lattner // version. 11910621caefSChris Lattner if (!GVEntry) { 119249bb65a4SRafael Espindola GVEntry = &GV; 11930621caefSChris Lattner continue; 11940621caefSChris Lattner } 11950621caefSChris Lattner 11960621caefSChris Lattner // If the existing global is strong, never replace it. 11977157bb76SNico Rieck if (GVEntry->hasExternalLinkage()) 11980621caefSChris Lattner continue; 11990621caefSChris Lattner 12000621caefSChris Lattner // Otherwise, we know it's linkonce/weak, replace it if this is a strong 1201ce4396bcSDale Johannesen // symbol. FIXME is this right for common? 120249bb65a4SRafael Espindola if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 120349bb65a4SRafael Espindola GVEntry = &GV; 12040621caefSChris Lattner } 12050621caefSChris Lattner } 12060621caefSChris Lattner } 12070621caefSChris Lattner 12080621caefSChris Lattner std::vector<const GlobalValue*> NonCanonicalGlobals; 12090621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1210091217beSJeffrey Yasskin Module &M = *Modules[m]; 121149bb65a4SRafael Espindola for (const auto &GV : M.globals()) { 12120621caefSChris Lattner // In the multi-module case, see what this global maps to. 12130621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 12140621caefSChris Lattner if (const GlobalValue *GVEntry = 121549bb65a4SRafael Espindola LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) { 12160621caefSChris Lattner // If something else is the canonical global, ignore this one. 121749bb65a4SRafael Espindola if (GVEntry != &GV) { 121849bb65a4SRafael Espindola NonCanonicalGlobals.push_back(&GV); 12190621caefSChris Lattner continue; 12200621caefSChris Lattner } 12210621caefSChris Lattner } 12220621caefSChris Lattner } 12230621caefSChris Lattner 122449bb65a4SRafael Espindola if (!GV.isDeclaration()) { 122549bb65a4SRafael Espindola addGlobalMapping(&GV, getMemoryForGV(&GV)); 1226996fe010SChris Lattner } else { 1227e8bbcfc2SBrian Gaeke // External variable reference. Try to use the dynamic loader to 1228e8bbcfc2SBrian Gaeke // get a pointer to it. 12290621caefSChris Lattner if (void *SymAddr = 123049bb65a4SRafael Espindola sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName())) 123149bb65a4SRafael Espindola addGlobalMapping(&GV, SymAddr); 12329de0d14dSChris Lattner else { 12332104b8d3SChris Lattner report_fatal_error("Could not resolve external global address: " 123449bb65a4SRafael Espindola +GV.getName()); 12359de0d14dSChris Lattner } 1236996fe010SChris Lattner } 12370621caefSChris Lattner } 12380621caefSChris Lattner 12390621caefSChris Lattner // If there are multiple modules, map the non-canonical globals to their 12400621caefSChris Lattner // canonical location. 12410621caefSChris Lattner if (!NonCanonicalGlobals.empty()) { 12420621caefSChris Lattner for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 12430621caefSChris Lattner const GlobalValue *GV = NonCanonicalGlobals[i]; 12440621caefSChris Lattner const GlobalValue *CGV = 12450621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 12460621caefSChris Lattner void *Ptr = getPointerToGlobalIfAvailable(CGV); 12470621caefSChris Lattner assert(Ptr && "Canonical global wasn't codegen'd!"); 1248a67f06b9SNuno Lopes addGlobalMapping(GV, Ptr); 12490621caefSChris Lattner } 12500621caefSChris Lattner } 1251996fe010SChris Lattner 12527a9c62baSReid Spencer // Now that all of the globals are set up in memory, loop through them all 12537a9c62baSReid Spencer // and initialize their contents. 125449bb65a4SRafael Espindola for (const auto &GV : M.globals()) { 125549bb65a4SRafael Espindola if (!GV.isDeclaration()) { 12560621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 12570621caefSChris Lattner if (const GlobalValue *GVEntry = 125849bb65a4SRafael Espindola LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) 125949bb65a4SRafael Espindola if (GVEntry != &GV) // Not the canonical variable. 12600621caefSChris Lattner continue; 12610621caefSChris Lattner } 126249bb65a4SRafael Espindola EmitGlobalVariable(&GV); 12636bbe3eceSChris Lattner } 12640621caefSChris Lattner } 12650621caefSChris Lattner } 12660621caefSChris Lattner } 12676bbe3eceSChris Lattner 12686bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the 12696bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not 12706bbe3eceSChris Lattner // already in the map. 1271fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 1272748e8579SChris Lattner void *GA = getPointerToGlobalIfAvailable(GV); 1273dc631735SChris Lattner 12742617dcceSCraig Topper if (!GA) { 12756bbe3eceSChris Lattner // If it's not already specified, allocate memory for the global. 12765457ce9aSNicolas Geoffray GA = getMemoryForGV(GV); 12773b442379SAndrew Kaylor 12783b442379SAndrew Kaylor // If we failed to allocate memory for this global, return. 12792617dcceSCraig Topper if (!GA) return; 12803b442379SAndrew Kaylor 1281748e8579SChris Lattner addGlobalMapping(GV, GA); 12826bbe3eceSChris Lattner } 1283fbcc0aa1SChris Lattner 12845457ce9aSNicolas Geoffray // Don't initialize if it's thread local, let the client do it. 12855457ce9aSNicolas Geoffray if (!GV->isThreadLocal()) 12866bbe3eceSChris Lattner InitializeMemory(GV->getInitializer(), GA); 12875457ce9aSNicolas Geoffray 1288229907cdSChris Lattner Type *ElTy = GV->getType()->getElementType(); 1289cdfe20b9SMicah Villmow size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy); 1290df1f1524SChris Lattner NumInitBytes += (unsigned)GVSize; 12916bbe3eceSChris Lattner ++NumGlobals; 1292996fe010SChris Lattner } 1293f98e981cSJeffrey Yasskin 1294d0fc8f80SJeffrey Yasskin ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE) 1295d0fc8f80SJeffrey Yasskin : EE(EE), GlobalAddressMap(this) { 1296f98e981cSJeffrey Yasskin } 1297f98e981cSJeffrey Yasskin 1298c04b892fSZachary Turner sys::Mutex * 1299868e3f09SDaniel Dunbar ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) { 1300d0fc8f80SJeffrey Yasskin return &EES->EE.lock; 1301d0fc8f80SJeffrey Yasskin } 1302868e3f09SDaniel Dunbar 1303868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES, 1304868e3f09SDaniel Dunbar const GlobalValue *Old) { 1305d0fc8f80SJeffrey Yasskin void *OldVal = EES->GlobalAddressMap.lookup(Old); 1306d0fc8f80SJeffrey Yasskin EES->GlobalAddressReverseMap.erase(OldVal); 1307d0fc8f80SJeffrey Yasskin } 1308d0fc8f80SJeffrey Yasskin 1309868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *, 1310868e3f09SDaniel Dunbar const GlobalValue *, 1311868e3f09SDaniel Dunbar const GlobalValue *) { 1312a2886c21SCraig Topper llvm_unreachable("The ExecutionEngine doesn't know how to handle a" 1313f98e981cSJeffrey Yasskin " RAUW on a value it has a global mapping for."); 1314f98e981cSJeffrey Yasskin } 1315