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" 176bf87df5SJeffrey Yasskin 18996fe010SChris Lattner #include "llvm/Constants.h" 19260b0c88SMisha Brukman #include "llvm/DerivedTypes.h" 20996fe010SChris Lattner #include "llvm/Module.h" 21ad481312SChris Lattner #include "llvm/ExecutionEngine/GenericValue.h" 22868e3f09SDaniel Dunbar #include "llvm/ADT/SmallString.h" 23390d78b3SChris Lattner #include "llvm/ADT/Statistic.h" 247c16caa3SReid Spencer #include "llvm/Support/Debug.h" 256c2d233eSTorok Edwin #include "llvm/Support/ErrorHandling.h" 266d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h" 276bf87df5SJeffrey Yasskin #include "llvm/Support/ValueHandle.h" 28ccb29cd2STorok Edwin #include "llvm/Support/raw_ostream.h" 29*447762daSMichael J. Spencer #include "llvm/Support/DynamicLibrary.h" 30*447762daSMichael J. Spencer #include "llvm/Support/Host.h" 3170e37278SReid Spencer #include "llvm/Target/TargetData.h" 32579f0713SAnton Korobeynikov #include <cmath> 33579f0713SAnton Korobeynikov #include <cstring> 3429681deeSChris Lattner using namespace llvm; 35996fe010SChris Lattner 36c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 37c346ecd7SChris Lattner STATISTIC(NumGlobals , "Number of global vars initialized"); 38996fe010SChris Lattner 3931faefffSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::JITCtor)( 4031faefffSJeffrey Yasskin Module *M, 41fc8a2d5aSReid Kleckner std::string *ErrorStr, 42fc8a2d5aSReid Kleckner JITMemoryManager *JMM, 43fc8a2d5aSReid Kleckner CodeGenOpt::Level OptLevel, 44700d08e1SEric Christopher bool GVsWithCode, 4531faefffSJeffrey Yasskin CodeModel::Model CMM, 4631faefffSJeffrey Yasskin StringRef MArch, 4731faefffSJeffrey Yasskin StringRef MCPU, 4831faefffSJeffrey Yasskin const SmallVectorImpl<std::string>& MAttrs) = 0; 4970ff8b05SDaniel Dunbar ExecutionEngine *(*ExecutionEngine::MCJITCtor)( 5070ff8b05SDaniel Dunbar Module *M, 5170ff8b05SDaniel Dunbar std::string *ErrorStr, 5270ff8b05SDaniel Dunbar JITMemoryManager *JMM, 5370ff8b05SDaniel Dunbar CodeGenOpt::Level OptLevel, 5470ff8b05SDaniel Dunbar bool GVsWithCode, 5570ff8b05SDaniel Dunbar CodeModel::Model CMM, 5670ff8b05SDaniel Dunbar StringRef MArch, 5770ff8b05SDaniel Dunbar StringRef MCPU, 5870ff8b05SDaniel Dunbar const SmallVectorImpl<std::string>& MAttrs) = 0; 59091217beSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M, 60fc8a2d5aSReid Kleckner std::string *ErrorStr) = 0; 612d52c1b8SChris Lattner 62091217beSJeffrey Yasskin ExecutionEngine::ExecutionEngine(Module *M) 63f98e981cSJeffrey Yasskin : EEState(*this), 64abc7901eSDuncan Sands LazyFunctionCreator(0), 65abc7901eSDuncan Sands ExceptionTableRegister(0), 66abc7901eSDuncan Sands ExceptionTableDeregister(0) { 674567db45SJeffrey Yasskin CompilingLazily = false; 68cdc0060eSEvan Cheng GVCompilationDisabled = false; 6984a9055eSEvan Cheng SymbolSearchingDisabled = false; 70091217beSJeffrey Yasskin Modules.push_back(M); 71091217beSJeffrey Yasskin assert(M && "Module is null?"); 72260b0c88SMisha Brukman } 73260b0c88SMisha Brukman 7492f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() { 75603682adSReid Spencer clearAllGlobalMappings(); 760621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) 770621caefSChris Lattner delete Modules[i]; 7892f8b30dSBrian Gaeke } 7992f8b30dSBrian Gaeke 80abc7901eSDuncan Sands void ExecutionEngine::DeregisterAllTables() { 81abc7901eSDuncan Sands if (ExceptionTableDeregister) { 82868e3f09SDaniel Dunbar for (std::vector<void*>::iterator it = AllExceptionTables.begin(), 83868e3f09SDaniel Dunbar ie = AllExceptionTables.end(); it != ie; ++it) 84abc7901eSDuncan Sands ExceptionTableDeregister(*it); 85abc7901eSDuncan Sands AllExceptionTables.clear(); 86abc7901eSDuncan Sands } 87abc7901eSDuncan Sands } 88abc7901eSDuncan Sands 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. 99a4044332SJeffrey Yasskin static char *Create(const GlobalVariable *GV, const TargetData& TD) { 1005457ce9aSNicolas Geoffray const Type *ElTy = GV->getType()->getElementType(); 101a4044332SJeffrey Yasskin size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy); 102a4044332SJeffrey Yasskin void *RawMemory = ::operator new( 103a4044332SJeffrey Yasskin TargetData::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 110a4044332SJeffrey Yasskin virtual void deleted() { 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) { 121a4044332SJeffrey Yasskin return GVMemoryBlock::Create(GV, *getTargetData()); 1225457ce9aSNicolas Geoffray } 1235457ce9aSNicolas Geoffray 124091217beSJeffrey Yasskin bool ExecutionEngine::removeModule(Module *M) { 125091217beSJeffrey Yasskin for(SmallVector<Module *, 1>::iterator I = Modules.begin(), 126324fe890SDevang Patel E = Modules.end(); I != E; ++I) { 127091217beSJeffrey Yasskin Module *Found = *I; 128091217beSJeffrey Yasskin if (Found == M) { 129324fe890SDevang Patel Modules.erase(I); 130091217beSJeffrey Yasskin clearGlobalMappingsFromModule(M); 131091217beSJeffrey Yasskin return true; 132324fe890SDevang Patel } 133324fe890SDevang Patel } 134091217beSJeffrey Yasskin return false; 135617001d8SNate Begeman } 136617001d8SNate Begeman 1370621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 1380621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 139091217beSJeffrey Yasskin if (Function *F = Modules[i]->getFunction(FnName)) 1400621caefSChris Lattner return F; 1410621caefSChris Lattner } 1420621caefSChris Lattner return 0; 1430621caefSChris Lattner } 1440621caefSChris Lattner 1450621caefSChris Lattner 146868e3f09SDaniel Dunbar void *ExecutionEngineState::RemoveMapping(const MutexGuard &, 147868e3f09SDaniel Dunbar const GlobalValue *ToUnmap) { 148d0fc8f80SJeffrey Yasskin GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap); 149307c053fSJeffrey Yasskin void *OldVal; 150868e3f09SDaniel Dunbar 151868e3f09SDaniel Dunbar // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the 152868e3f09SDaniel Dunbar // GlobalAddressMap. 153307c053fSJeffrey Yasskin if (I == GlobalAddressMap.end()) 154307c053fSJeffrey Yasskin OldVal = 0; 155307c053fSJeffrey Yasskin else { 156307c053fSJeffrey Yasskin OldVal = I->second; 157307c053fSJeffrey Yasskin GlobalAddressMap.erase(I); 158307c053fSJeffrey Yasskin } 159307c053fSJeffrey Yasskin 160307c053fSJeffrey Yasskin GlobalAddressReverseMap.erase(OldVal); 161307c053fSJeffrey Yasskin return OldVal; 162307c053fSJeffrey Yasskin } 163307c053fSJeffrey Yasskin 1646d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 1656d8dd189SChris Lattner MutexGuard locked(lock); 1666d8dd189SChris Lattner 1670967d2dfSDavid Greene DEBUG(dbgs() << "JIT: Map \'" << GV->getName() 1689813b0b0SDaniel Dunbar << "\' to [" << Addr << "]\n";); 169d0fc8f80SJeffrey Yasskin void *&CurVal = EEState.getGlobalAddressMap(locked)[GV]; 1706d8dd189SChris Lattner assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!"); 1716d8dd189SChris Lattner CurVal = Addr; 1726d8dd189SChris Lattner 173868e3f09SDaniel Dunbar // If we are using the reverse mapping, add it too. 174f98e981cSJeffrey Yasskin if (!EEState.getGlobalAddressReverseMap(locked).empty()) { 1756bf87df5SJeffrey Yasskin AssertingVH<const GlobalValue> &V = 176f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked)[Addr]; 1776d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 1786d8dd189SChris Lattner V = GV; 1796d8dd189SChris Lattner } 1806d8dd189SChris Lattner } 1816d8dd189SChris Lattner 1826d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() { 1836d8dd189SChris Lattner MutexGuard locked(lock); 1846d8dd189SChris Lattner 185f98e981cSJeffrey Yasskin EEState.getGlobalAddressMap(locked).clear(); 186f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked).clear(); 1876d8dd189SChris Lattner } 1886d8dd189SChris Lattner 1898f83fc4dSNate Begeman void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) { 1908f83fc4dSNate Begeman MutexGuard locked(lock); 1918f83fc4dSNate Begeman 192868e3f09SDaniel Dunbar for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) 193f98e981cSJeffrey Yasskin EEState.RemoveMapping(locked, FI); 1948f83fc4dSNate Begeman for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 195868e3f09SDaniel Dunbar GI != GE; ++GI) 196f98e981cSJeffrey Yasskin EEState.RemoveMapping(locked, GI); 1978f83fc4dSNate Begeman } 1988f83fc4dSNate Begeman 199ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 2006d8dd189SChris Lattner MutexGuard locked(lock); 2016d8dd189SChris Lattner 202d0fc8f80SJeffrey Yasskin ExecutionEngineState::GlobalAddressMapTy &Map = 203f98e981cSJeffrey Yasskin EEState.getGlobalAddressMap(locked); 204ee181730SChris Lattner 2056d8dd189SChris Lattner // Deleting from the mapping? 206868e3f09SDaniel Dunbar if (Addr == 0) 207f98e981cSJeffrey Yasskin return EEState.RemoveMapping(locked, GV); 208ee181730SChris Lattner 209d0fc8f80SJeffrey Yasskin void *&CurVal = Map[GV]; 210ee181730SChris Lattner void *OldVal = CurVal; 211ee181730SChris Lattner 212f98e981cSJeffrey Yasskin if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty()) 213f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked).erase(CurVal); 2146d8dd189SChris Lattner CurVal = Addr; 2156d8dd189SChris Lattner 216868e3f09SDaniel Dunbar // If we are using the reverse mapping, add it too. 217f98e981cSJeffrey Yasskin if (!EEState.getGlobalAddressReverseMap(locked).empty()) { 2186bf87df5SJeffrey Yasskin AssertingVH<const GlobalValue> &V = 219f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked)[Addr]; 2206d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 2216d8dd189SChris Lattner V = GV; 2226d8dd189SChris Lattner } 223ee181730SChris Lattner return OldVal; 2246d8dd189SChris Lattner } 2256d8dd189SChris Lattner 2266d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 2276d8dd189SChris Lattner MutexGuard locked(lock); 2286d8dd189SChris Lattner 229d0fc8f80SJeffrey Yasskin ExecutionEngineState::GlobalAddressMapTy::iterator I = 230d0fc8f80SJeffrey Yasskin EEState.getGlobalAddressMap(locked).find(GV); 231f98e981cSJeffrey Yasskin return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0; 2326d8dd189SChris Lattner } 2336d8dd189SChris Lattner 234748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 23579876f52SReid Spencer MutexGuard locked(lock); 23679876f52SReid Spencer 237748e8579SChris Lattner // If we haven't computed the reverse mapping yet, do so first. 238f98e981cSJeffrey Yasskin if (EEState.getGlobalAddressReverseMap(locked).empty()) { 239d0fc8f80SJeffrey Yasskin for (ExecutionEngineState::GlobalAddressMapTy::iterator 240f98e981cSJeffrey Yasskin I = EEState.getGlobalAddressMap(locked).begin(), 241f98e981cSJeffrey Yasskin E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I) 242e4f47434SDaniel Dunbar EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair( 243e4f47434SDaniel Dunbar I->second, I->first)); 244748e8579SChris Lattner } 245748e8579SChris Lattner 2466bf87df5SJeffrey Yasskin std::map<void *, AssertingVH<const GlobalValue> >::iterator I = 247f98e981cSJeffrey Yasskin EEState.getGlobalAddressReverseMap(locked).find(Addr); 248f98e981cSJeffrey Yasskin return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0; 249748e8579SChris Lattner } 2505a0d4829SChris Lattner 251bfd38abbSJeffrey Yasskin namespace { 252bfd38abbSJeffrey Yasskin class ArgvArray { 253bfd38abbSJeffrey Yasskin char *Array; 254bfd38abbSJeffrey Yasskin std::vector<char*> Values; 255bfd38abbSJeffrey Yasskin public: 256bfd38abbSJeffrey Yasskin ArgvArray() : Array(NULL) {} 257bfd38abbSJeffrey Yasskin ~ArgvArray() { clear(); } 258bfd38abbSJeffrey Yasskin void clear() { 259bfd38abbSJeffrey Yasskin delete[] Array; 260bfd38abbSJeffrey Yasskin Array = NULL; 261bfd38abbSJeffrey Yasskin for (size_t I = 0, E = Values.size(); I != E; ++I) { 262bfd38abbSJeffrey Yasskin delete[] Values[I]; 263bfd38abbSJeffrey Yasskin } 264bfd38abbSJeffrey Yasskin Values.clear(); 265bfd38abbSJeffrey Yasskin } 266bfd38abbSJeffrey Yasskin /// Turn a vector of strings into a nice argv style array of pointers to null 267bfd38abbSJeffrey Yasskin /// terminated strings. 268bfd38abbSJeffrey Yasskin void *reset(LLVMContext &C, ExecutionEngine *EE, 269bfd38abbSJeffrey Yasskin const std::vector<std::string> &InputArgv); 270bfd38abbSJeffrey Yasskin }; 271bfd38abbSJeffrey Yasskin } // anonymous namespace 272bfd38abbSJeffrey Yasskin void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE, 2735a0d4829SChris Lattner const std::vector<std::string> &InputArgv) { 274bfd38abbSJeffrey Yasskin clear(); // Free the old contents. 27520a631fdSOwen Anderson unsigned PtrSize = EE->getTargetData()->getPointerSize(); 276bfd38abbSJeffrey Yasskin Array = new char[(InputArgv.size()+1)*PtrSize]; 2775a0d4829SChris Lattner 278bfd38abbSJeffrey Yasskin DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n"); 2799ed7b16bSDuncan Sands const Type *SBytePtr = Type::getInt8PtrTy(C); 2805a0d4829SChris Lattner 2815a0d4829SChris Lattner for (unsigned i = 0; i != InputArgv.size(); ++i) { 2825a0d4829SChris Lattner unsigned Size = InputArgv[i].size()+1; 2835a0d4829SChris Lattner char *Dest = new char[Size]; 284bfd38abbSJeffrey Yasskin Values.push_back(Dest); 2850967d2dfSDavid Greene DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n"); 2865a0d4829SChris Lattner 2875a0d4829SChris Lattner std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 2885a0d4829SChris Lattner Dest[Size-1] = 0; 2895a0d4829SChris Lattner 290bfd38abbSJeffrey Yasskin // Endian safe: Array[i] = (PointerTy)Dest; 291bfd38abbSJeffrey Yasskin EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize), 2925a0d4829SChris Lattner SBytePtr); 2935a0d4829SChris Lattner } 2945a0d4829SChris Lattner 2955a0d4829SChris Lattner // Null terminate it 2965a0d4829SChris Lattner EE->StoreValueToMemory(PTOGV(0), 297bfd38abbSJeffrey Yasskin (GenericValue*)(Array+InputArgv.size()*PtrSize), 2985a0d4829SChris Lattner SBytePtr); 299bfd38abbSJeffrey Yasskin return Array; 3005a0d4829SChris Lattner } 3015a0d4829SChris Lattner 30241fa2bd1SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(Module *module, 30341fa2bd1SChris Lattner bool isDtors) { 304faae50b6SChris Lattner const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 3051a9a0b7bSEvan Cheng GlobalVariable *GV = module->getNamedGlobal(Name); 306fe36eaebSChris Lattner 307fe36eaebSChris Lattner // If this global has internal linkage, or if it has a use, then it must be 308fe36eaebSChris Lattner // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 3090621caefSChris Lattner // this is the case, don't execute any of the global ctors, __main will do 3100621caefSChris Lattner // it. 3116de96a1bSRafael Espindola if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return; 312faae50b6SChris Lattner 3130621caefSChris Lattner // Should be an array of '{ int, void ()* }' structs. The first value is 3140621caefSChris Lattner // the init priority, which we ignore. 315faae50b6SChris Lattner ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 3161a9a0b7bSEvan Cheng if (!InitList) return; 317868e3f09SDaniel Dunbar for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 318868e3f09SDaniel Dunbar ConstantStruct *CS = 319868e3f09SDaniel Dunbar dyn_cast<ConstantStruct>(InitList->getOperand(i)); 320868e3f09SDaniel Dunbar if (!CS) continue; 3211a9a0b7bSEvan Cheng if (CS->getNumOperands() != 2) return; // Not array of 2-element structs. 322faae50b6SChris Lattner 323faae50b6SChris Lattner Constant *FP = CS->getOperand(1); 324faae50b6SChris Lattner if (FP->isNullValue()) 3250621caefSChris Lattner break; // Found a null terminator, exit. 326faae50b6SChris Lattner 327868e3f09SDaniel Dunbar // Strip off constant expression casts. 328faae50b6SChris Lattner if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 3296c38f0bbSReid Spencer if (CE->isCast()) 330faae50b6SChris Lattner FP = CE->getOperand(0); 331868e3f09SDaniel Dunbar 332faae50b6SChris Lattner // Execute the ctor/dtor function! 333868e3f09SDaniel Dunbar if (Function *F = dyn_cast<Function>(FP)) 334faae50b6SChris Lattner runFunction(F, std::vector<GenericValue>()); 335868e3f09SDaniel Dunbar 336868e3f09SDaniel Dunbar // FIXME: It is marginally lame that we just do nothing here if we see an 337868e3f09SDaniel Dunbar // entry we don't recognize. It might not be unreasonable for the verifier 338868e3f09SDaniel Dunbar // to not even allow this and just assert here. 339faae50b6SChris Lattner } 340faae50b6SChris Lattner } 3411a9a0b7bSEvan Cheng 3421a9a0b7bSEvan Cheng void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 3431a9a0b7bSEvan Cheng // Execute global ctors/dtors for each module in the program. 344868e3f09SDaniel Dunbar for (unsigned i = 0, e = Modules.size(); i != e; ++i) 345868e3f09SDaniel Dunbar runStaticConstructorsDestructors(Modules[i], isDtors); 3460621caefSChris Lattner } 347faae50b6SChris Lattner 348cf3e3017SDan Gohman #ifndef NDEBUG 3491202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null. 3501202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) { 3511202d1b1SDuncan Sands unsigned PtrSize = EE->getTargetData()->getPointerSize(); 3521202d1b1SDuncan Sands for (unsigned i = 0; i < PtrSize; ++i) 3531202d1b1SDuncan Sands if (*(i + (uint8_t*)Loc)) 3541202d1b1SDuncan Sands return false; 3551202d1b1SDuncan Sands return true; 3561202d1b1SDuncan Sands } 357cf3e3017SDan Gohman #endif 3581202d1b1SDuncan Sands 3595a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn, 3605a0d4829SChris Lattner const std::vector<std::string> &argv, 3615a0d4829SChris Lattner const char * const * envp) { 3625a0d4829SChris Lattner std::vector<GenericValue> GVArgs; 3635a0d4829SChris Lattner GenericValue GVArgc; 36487aa65f4SReid Spencer GVArgc.IntVal = APInt(32, argv.size()); 3658c32c111SAnton Korobeynikov 3668c32c111SAnton Korobeynikov // Check main() type 367b1cad0b3SChris Lattner unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 3688c32c111SAnton Korobeynikov const FunctionType *FTy = Fn->getFunctionType(); 369ccce8baeSBenjamin Kramer const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo(); 370868e3f09SDaniel Dunbar 371868e3f09SDaniel Dunbar // Check the argument types. 372868e3f09SDaniel Dunbar if (NumArgs > 3) 3732104b8d3SChris Lattner report_fatal_error("Invalid number of arguments of main() supplied"); 374868e3f09SDaniel Dunbar if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty) 375868e3f09SDaniel Dunbar report_fatal_error("Invalid type for third argument of main() supplied"); 376868e3f09SDaniel Dunbar if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty) 377868e3f09SDaniel Dunbar report_fatal_error("Invalid type for second argument of main() supplied"); 378868e3f09SDaniel Dunbar if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32)) 379868e3f09SDaniel Dunbar report_fatal_error("Invalid type for first argument of main() supplied"); 380868e3f09SDaniel Dunbar if (!FTy->getReturnType()->isIntegerTy() && 381868e3f09SDaniel Dunbar !FTy->getReturnType()->isVoidTy()) 382868e3f09SDaniel Dunbar report_fatal_error("Invalid return type of main() supplied"); 3838c32c111SAnton Korobeynikov 384bfd38abbSJeffrey Yasskin ArgvArray CArgv; 385bfd38abbSJeffrey Yasskin ArgvArray CEnv; 386b1cad0b3SChris Lattner if (NumArgs) { 3875a0d4829SChris Lattner GVArgs.push_back(GVArgc); // Arg #0 = argc. 388b1cad0b3SChris Lattner if (NumArgs > 1) { 38955f1c09eSOwen Anderson // Arg #1 = argv. 390bfd38abbSJeffrey Yasskin GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv))); 3911202d1b1SDuncan Sands assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) && 392b1cad0b3SChris Lattner "argv[0] was null after CreateArgv"); 393b1cad0b3SChris Lattner if (NumArgs > 2) { 3945a0d4829SChris Lattner std::vector<std::string> EnvVars; 3955a0d4829SChris Lattner for (unsigned i = 0; envp[i]; ++i) 3965a0d4829SChris Lattner EnvVars.push_back(envp[i]); 39755f1c09eSOwen Anderson // Arg #2 = envp. 398bfd38abbSJeffrey Yasskin GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars))); 399b1cad0b3SChris Lattner } 400b1cad0b3SChris Lattner } 401b1cad0b3SChris Lattner } 402868e3f09SDaniel Dunbar 40387aa65f4SReid Spencer return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 4045a0d4829SChris Lattner } 4055a0d4829SChris Lattner 406091217beSJeffrey Yasskin ExecutionEngine *ExecutionEngine::create(Module *M, 407603682adSReid Spencer bool ForceInterpreter, 4087ff05bf5SEvan Cheng std::string *ErrorStr, 40970415d97SJeffrey Yasskin CodeGenOpt::Level OptLevel, 41070415d97SJeffrey Yasskin bool GVsWithCode) { 411091217beSJeffrey Yasskin return EngineBuilder(M) 412fc8a2d5aSReid Kleckner .setEngineKind(ForceInterpreter 413fc8a2d5aSReid Kleckner ? EngineKind::Interpreter 414fc8a2d5aSReid Kleckner : EngineKind::JIT) 415fc8a2d5aSReid Kleckner .setErrorStr(ErrorStr) 416fc8a2d5aSReid Kleckner .setOptLevel(OptLevel) 417fc8a2d5aSReid Kleckner .setAllocateGVsWithCode(GVsWithCode) 418fc8a2d5aSReid Kleckner .create(); 419fc8a2d5aSReid Kleckner } 4204bd3bd5bSBrian Gaeke 421fc8a2d5aSReid Kleckner ExecutionEngine *EngineBuilder::create() { 422a53414fdSNick Lewycky // Make sure we can resolve symbols in the program as well. The zero arg 423a53414fdSNick Lewycky // to the function tells DynamicLibrary to load the program, not a library. 424a53414fdSNick Lewycky if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) 425a53414fdSNick Lewycky return 0; 426a53414fdSNick Lewycky 427fc8a2d5aSReid Kleckner // If the user specified a memory manager but didn't specify which engine to 428fc8a2d5aSReid Kleckner // create, we assume they only want the JIT, and we fail if they only want 429fc8a2d5aSReid Kleckner // the interpreter. 430fc8a2d5aSReid Kleckner if (JMM) { 43141fa2bd1SChris Lattner if (WhichEngine & EngineKind::JIT) 432fc8a2d5aSReid Kleckner WhichEngine = EngineKind::JIT; 43341fa2bd1SChris Lattner else { 4348bcc6445SChris Lattner if (ErrorStr) 435fc8a2d5aSReid Kleckner *ErrorStr = "Cannot create an interpreter with a memory manager."; 43641fa2bd1SChris Lattner return 0; 437fc8a2d5aSReid Kleckner } 4384bd3bd5bSBrian Gaeke } 4394bd3bd5bSBrian Gaeke 440fc8a2d5aSReid Kleckner // Unless the interpreter was explicitly selected or the JIT is not linked, 441fc8a2d5aSReid Kleckner // try making a JIT. 44241fa2bd1SChris Lattner if (WhichEngine & EngineKind::JIT) { 44370ff8b05SDaniel Dunbar if (UseMCJIT && ExecutionEngine::MCJITCtor) { 44470ff8b05SDaniel Dunbar ExecutionEngine *EE = 44570ff8b05SDaniel Dunbar ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel, 44670ff8b05SDaniel Dunbar AllocateGVsWithCode, CMModel, 44770ff8b05SDaniel Dunbar MArch, MCPU, MAttrs); 44870ff8b05SDaniel Dunbar if (EE) return EE; 44970ff8b05SDaniel Dunbar } else if (ExecutionEngine::JITCtor) { 45041fa2bd1SChris Lattner ExecutionEngine *EE = 451091217beSJeffrey Yasskin ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel, 45231faefffSJeffrey Yasskin AllocateGVsWithCode, CMModel, 45331faefffSJeffrey Yasskin MArch, MCPU, MAttrs); 45441fa2bd1SChris Lattner if (EE) return EE; 45541fa2bd1SChris Lattner } 456fc8a2d5aSReid Kleckner } 457fc8a2d5aSReid Kleckner 458fc8a2d5aSReid Kleckner // If we can't make a JIT and we didn't request one specifically, try making 459fc8a2d5aSReid Kleckner // an interpreter instead. 46041fa2bd1SChris Lattner if (WhichEngine & EngineKind::Interpreter) { 46141fa2bd1SChris Lattner if (ExecutionEngine::InterpCtor) 462091217beSJeffrey Yasskin return ExecutionEngine::InterpCtor(M, ErrorStr); 4638bcc6445SChris Lattner if (ErrorStr) 46441fa2bd1SChris Lattner *ErrorStr = "Interpreter has not been linked in."; 46541fa2bd1SChris Lattner return 0; 466fc8a2d5aSReid Kleckner } 467fc8a2d5aSReid Kleckner 4688bcc6445SChris Lattner if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) { 4698bcc6445SChris Lattner if (ErrorStr) 4708bcc6445SChris Lattner *ErrorStr = "JIT has not been linked in."; 4718bcc6445SChris Lattner } 472868e3f09SDaniel Dunbar 47341fa2bd1SChris Lattner return 0; 474b5163bb9SChris Lattner } 475b5163bb9SChris Lattner 476996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 4771678e859SBrian Gaeke if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 478996fe010SChris Lattner return getPointerToFunction(F); 479996fe010SChris Lattner 48079876f52SReid Spencer MutexGuard locked(lock); 481868e3f09SDaniel Dunbar if (void *P = EEState.getGlobalAddressMap(locked)[GV]) 482868e3f09SDaniel Dunbar return P; 48369e84901SJeff Cohen 48469e84901SJeff Cohen // Global variable might have been added since interpreter started. 48569e84901SJeff Cohen if (GlobalVariable *GVar = 48669e84901SJeff Cohen const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 48769e84901SJeff Cohen EmitGlobalVariable(GVar); 48869e84901SJeff Cohen else 489fbcc663cSTorok Edwin llvm_unreachable("Global hasn't had an address allocated yet!"); 490868e3f09SDaniel Dunbar 491d0fc8f80SJeffrey Yasskin return EEState.getGlobalAddressMap(locked)[GV]; 492996fe010SChris Lattner } 493996fe010SChris Lattner 494868e3f09SDaniel Dunbar /// \brief Converts a Constant* into a GenericValue, including handling of 495868e3f09SDaniel Dunbar /// ConstantExpr values. 496996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 4976c38f0bbSReid Spencer // If its undefined, return the garbage. 498bcbdbfb3SJay Foad if (isa<UndefValue>(C)) { 499bcbdbfb3SJay Foad GenericValue Result; 500bcbdbfb3SJay Foad switch (C->getType()->getTypeID()) { 501bcbdbfb3SJay Foad case Type::IntegerTyID: 502bcbdbfb3SJay Foad case Type::X86_FP80TyID: 503bcbdbfb3SJay Foad case Type::FP128TyID: 504bcbdbfb3SJay Foad case Type::PPC_FP128TyID: 505bcbdbfb3SJay Foad // Although the value is undefined, we still have to construct an APInt 506bcbdbfb3SJay Foad // with the correct bit width. 507bcbdbfb3SJay Foad Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0); 508bcbdbfb3SJay Foad break; 509bcbdbfb3SJay Foad default: 510bcbdbfb3SJay Foad break; 511bcbdbfb3SJay Foad } 512bcbdbfb3SJay Foad return Result; 513bcbdbfb3SJay Foad } 5149de0d14dSChris Lattner 515868e3f09SDaniel Dunbar // Otherwise, if the value is a ConstantExpr... 5166c38f0bbSReid Spencer if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 5174fd528f2SReid Spencer Constant *Op0 = CE->getOperand(0); 5189de0d14dSChris Lattner switch (CE->getOpcode()) { 5199de0d14dSChris Lattner case Instruction::GetElementPtr: { 5206c38f0bbSReid Spencer // Compute the index 5214fd528f2SReid Spencer GenericValue Result = getConstantValue(Op0); 522c44bd78aSChris Lattner SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end()); 5239de0d14dSChris Lattner uint64_t Offset = 5244fd528f2SReid Spencer TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size()); 5259de0d14dSChris Lattner 52687aa65f4SReid Spencer char* tmp = (char*) Result.PointerVal; 52787aa65f4SReid Spencer Result = PTOGV(tmp + Offset); 5289de0d14dSChris Lattner return Result; 5299de0d14dSChris Lattner } 5304fd528f2SReid Spencer case Instruction::Trunc: { 5314fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5324fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 5334fd528f2SReid Spencer GV.IntVal = GV.IntVal.trunc(BitWidth); 5344fd528f2SReid Spencer return GV; 5354fd528f2SReid Spencer } 5364fd528f2SReid Spencer case Instruction::ZExt: { 5374fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5384fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 5394fd528f2SReid Spencer GV.IntVal = GV.IntVal.zext(BitWidth); 5404fd528f2SReid Spencer return GV; 5414fd528f2SReid Spencer } 5424fd528f2SReid Spencer case Instruction::SExt: { 5434fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5444fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 5454fd528f2SReid Spencer GV.IntVal = GV.IntVal.sext(BitWidth); 5464fd528f2SReid Spencer return GV; 5474fd528f2SReid Spencer } 5484fd528f2SReid Spencer case Instruction::FPTrunc: { 549a1336cf5SDale Johannesen // FIXME long double 5504fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5514fd528f2SReid Spencer GV.FloatVal = float(GV.DoubleVal); 5524fd528f2SReid Spencer return GV; 5534fd528f2SReid Spencer } 5544fd528f2SReid Spencer case Instruction::FPExt:{ 555a1336cf5SDale Johannesen // FIXME long double 5564fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5574fd528f2SReid Spencer GV.DoubleVal = double(GV.FloatVal); 5584fd528f2SReid Spencer return GV; 5594fd528f2SReid Spencer } 5604fd528f2SReid Spencer case Instruction::UIToFP: { 5614fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 562fdd87907SChris Lattner if (CE->getType()->isFloatTy()) 5634fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.roundToDouble()); 564fdd87907SChris Lattner else if (CE->getType()->isDoubleTy()) 5654fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.roundToDouble(); 566fdd87907SChris Lattner else if (CE->getType()->isX86_FP80Ty()) { 567a1336cf5SDale Johannesen const uint64_t zero[] = {0, 0}; 568a1336cf5SDale Johannesen APFloat apf = APFloat(APInt(80, 2, zero)); 569ca24fd90SDan Gohman (void)apf.convertFromAPInt(GV.IntVal, 570ca24fd90SDan Gohman false, 5719150652bSDale Johannesen APFloat::rmNearestTiesToEven); 57254306fe4SDale Johannesen GV.IntVal = apf.bitcastToAPInt(); 573a1336cf5SDale Johannesen } 5744fd528f2SReid Spencer return GV; 5754fd528f2SReid Spencer } 5764fd528f2SReid Spencer case Instruction::SIToFP: { 5774fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 578fdd87907SChris Lattner if (CE->getType()->isFloatTy()) 5794fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 580fdd87907SChris Lattner else if (CE->getType()->isDoubleTy()) 5814fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 582fdd87907SChris Lattner else if (CE->getType()->isX86_FP80Ty()) { 583a1336cf5SDale Johannesen const uint64_t zero[] = { 0, 0}; 584a1336cf5SDale Johannesen APFloat apf = APFloat(APInt(80, 2, zero)); 585ca24fd90SDan Gohman (void)apf.convertFromAPInt(GV.IntVal, 586ca24fd90SDan Gohman true, 5879150652bSDale Johannesen APFloat::rmNearestTiesToEven); 58854306fe4SDale Johannesen GV.IntVal = apf.bitcastToAPInt(); 589a1336cf5SDale Johannesen } 5904fd528f2SReid Spencer return GV; 5914fd528f2SReid Spencer } 5924fd528f2SReid Spencer case Instruction::FPToUI: // double->APInt conversion handles sign 5934fd528f2SReid Spencer case Instruction::FPToSI: { 5944fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5954fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 596fdd87907SChris Lattner if (Op0->getType()->isFloatTy()) 5974fd528f2SReid Spencer GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 598fdd87907SChris Lattner else if (Op0->getType()->isDoubleTy()) 5994fd528f2SReid Spencer GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 600fdd87907SChris Lattner else if (Op0->getType()->isX86_FP80Ty()) { 601a1336cf5SDale Johannesen APFloat apf = APFloat(GV.IntVal); 602a1336cf5SDale Johannesen uint64_t v; 6034f0bd68cSDale Johannesen bool ignored; 604a1336cf5SDale Johannesen (void)apf.convertToInteger(&v, BitWidth, 605a1336cf5SDale Johannesen CE->getOpcode()==Instruction::FPToSI, 6064f0bd68cSDale Johannesen APFloat::rmTowardZero, &ignored); 607a1336cf5SDale Johannesen GV.IntVal = v; // endian? 608a1336cf5SDale Johannesen } 6094fd528f2SReid Spencer return GV; 6104fd528f2SReid Spencer } 6116c38f0bbSReid Spencer case Instruction::PtrToInt: { 6124fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6134fd528f2SReid Spencer uint32_t PtrWidth = TD->getPointerSizeInBits(); 6144fd528f2SReid Spencer GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 6154fd528f2SReid Spencer return GV; 6164fd528f2SReid Spencer } 6174fd528f2SReid Spencer case Instruction::IntToPtr: { 6184fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6194fd528f2SReid Spencer uint32_t PtrWidth = TD->getPointerSizeInBits(); 6204fd528f2SReid Spencer if (PtrWidth != GV.IntVal.getBitWidth()) 6214fd528f2SReid Spencer GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 6224fd528f2SReid Spencer assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 6234fd528f2SReid Spencer GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 6246c38f0bbSReid Spencer return GV; 6256c38f0bbSReid Spencer } 6266c38f0bbSReid Spencer case Instruction::BitCast: { 6274fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6284fd528f2SReid Spencer const Type* DestTy = CE->getType(); 6294fd528f2SReid Spencer switch (Op0->getType()->getTypeID()) { 630fbcc663cSTorok Edwin default: llvm_unreachable("Invalid bitcast operand"); 6314fd528f2SReid Spencer case Type::IntegerTyID: 6329dff9becSDuncan Sands assert(DestTy->isFloatingPointTy() && "invalid bitcast"); 633fdd87907SChris Lattner if (DestTy->isFloatTy()) 6344fd528f2SReid Spencer GV.FloatVal = GV.IntVal.bitsToFloat(); 635fdd87907SChris Lattner else if (DestTy->isDoubleTy()) 6364fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.bitsToDouble(); 6376c38f0bbSReid Spencer break; 6384fd528f2SReid Spencer case Type::FloatTyID: 6399dff9becSDuncan Sands assert(DestTy->isIntegerTy(32) && "Invalid bitcast"); 6403447fb01SJay Foad GV.IntVal = APInt::floatToBits(GV.FloatVal); 6414fd528f2SReid Spencer break; 6424fd528f2SReid Spencer case Type::DoubleTyID: 6439dff9becSDuncan Sands assert(DestTy->isIntegerTy(64) && "Invalid bitcast"); 6443447fb01SJay Foad GV.IntVal = APInt::doubleToBits(GV.DoubleVal); 6454fd528f2SReid Spencer break; 6464fd528f2SReid Spencer case Type::PointerTyID: 64719d0b47bSDuncan Sands assert(DestTy->isPointerTy() && "Invalid bitcast"); 6484fd528f2SReid Spencer break; // getConstantValue(Op0) above already converted it 6496c38f0bbSReid Spencer } 6504fd528f2SReid Spencer return GV; 65168cbcc3eSChris Lattner } 65268cbcc3eSChris Lattner case Instruction::Add: 653a5b9645cSDan Gohman case Instruction::FAdd: 6544fd528f2SReid Spencer case Instruction::Sub: 655a5b9645cSDan Gohman case Instruction::FSub: 6564fd528f2SReid Spencer case Instruction::Mul: 657a5b9645cSDan Gohman case Instruction::FMul: 6584fd528f2SReid Spencer case Instruction::UDiv: 6594fd528f2SReid Spencer case Instruction::SDiv: 6604fd528f2SReid Spencer case Instruction::URem: 6614fd528f2SReid Spencer case Instruction::SRem: 6624fd528f2SReid Spencer case Instruction::And: 6634fd528f2SReid Spencer case Instruction::Or: 6644fd528f2SReid Spencer case Instruction::Xor: { 6654fd528f2SReid Spencer GenericValue LHS = getConstantValue(Op0); 6664fd528f2SReid Spencer GenericValue RHS = getConstantValue(CE->getOperand(1)); 6674fd528f2SReid Spencer GenericValue GV; 668c4e6bb5fSChris Lattner switch (CE->getOperand(0)->getType()->getTypeID()) { 669fbcc663cSTorok Edwin default: llvm_unreachable("Bad add type!"); 6707a9c62baSReid Spencer case Type::IntegerTyID: 6714fd528f2SReid Spencer switch (CE->getOpcode()) { 672fbcc663cSTorok Edwin default: llvm_unreachable("Invalid integer opcode"); 6734fd528f2SReid Spencer case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 6744fd528f2SReid Spencer case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 6754fd528f2SReid Spencer case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 6764fd528f2SReid Spencer case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 6774fd528f2SReid Spencer case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 6784fd528f2SReid Spencer case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 6794fd528f2SReid Spencer case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 6804fd528f2SReid Spencer case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 6814fd528f2SReid Spencer case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 6824fd528f2SReid Spencer case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 6834fd528f2SReid Spencer } 684c4e6bb5fSChris Lattner break; 685c4e6bb5fSChris Lattner case Type::FloatTyID: 6864fd528f2SReid Spencer switch (CE->getOpcode()) { 687fbcc663cSTorok Edwin default: llvm_unreachable("Invalid float opcode"); 688a5b9645cSDan Gohman case Instruction::FAdd: 6894fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 690a5b9645cSDan Gohman case Instruction::FSub: 6914fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 692a5b9645cSDan Gohman case Instruction::FMul: 6934fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 6944fd528f2SReid Spencer case Instruction::FDiv: 6954fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 6964fd528f2SReid Spencer case Instruction::FRem: 69793cd0f1cSChris Lattner GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break; 6984fd528f2SReid Spencer } 699c4e6bb5fSChris Lattner break; 700c4e6bb5fSChris Lattner case Type::DoubleTyID: 7014fd528f2SReid Spencer switch (CE->getOpcode()) { 702fbcc663cSTorok Edwin default: llvm_unreachable("Invalid double opcode"); 703a5b9645cSDan Gohman case Instruction::FAdd: 7044fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 705a5b9645cSDan Gohman case Instruction::FSub: 7064fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 707a5b9645cSDan Gohman case Instruction::FMul: 7084fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 7094fd528f2SReid Spencer case Instruction::FDiv: 7104fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 7114fd528f2SReid Spencer case Instruction::FRem: 71293cd0f1cSChris Lattner GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 7134fd528f2SReid Spencer } 714c4e6bb5fSChris Lattner break; 715a1336cf5SDale Johannesen case Type::X86_FP80TyID: 716a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 717a1336cf5SDale Johannesen case Type::FP128TyID: { 718a1336cf5SDale Johannesen APFloat apfLHS = APFloat(LHS.IntVal); 719a1336cf5SDale Johannesen switch (CE->getOpcode()) { 720e4f47434SDaniel Dunbar default: llvm_unreachable("Invalid long double opcode"); 721a5b9645cSDan Gohman case Instruction::FAdd: 722a1336cf5SDale Johannesen apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 72354306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 724a1336cf5SDale Johannesen break; 725a5b9645cSDan Gohman case Instruction::FSub: 726a1336cf5SDale Johannesen apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 72754306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 728a1336cf5SDale Johannesen break; 729a5b9645cSDan Gohman case Instruction::FMul: 730a1336cf5SDale Johannesen apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 73154306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 732a1336cf5SDale Johannesen break; 733a1336cf5SDale Johannesen case Instruction::FDiv: 734a1336cf5SDale Johannesen apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 73554306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 736a1336cf5SDale Johannesen break; 737a1336cf5SDale Johannesen case Instruction::FRem: 738a1336cf5SDale Johannesen apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 73954306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 740a1336cf5SDale Johannesen break; 741a1336cf5SDale Johannesen } 742a1336cf5SDale Johannesen } 743a1336cf5SDale Johannesen break; 744c4e6bb5fSChris Lattner } 7454fd528f2SReid Spencer return GV; 7464fd528f2SReid Spencer } 7479de0d14dSChris Lattner default: 74868cbcc3eSChris Lattner break; 74968cbcc3eSChris Lattner } 750868e3f09SDaniel Dunbar 751868e3f09SDaniel Dunbar SmallString<256> Msg; 752868e3f09SDaniel Dunbar raw_svector_ostream OS(Msg); 753868e3f09SDaniel Dunbar OS << "ConstantExpr not handled: " << *CE; 754868e3f09SDaniel Dunbar report_fatal_error(OS.str()); 7559de0d14dSChris Lattner } 756996fe010SChris Lattner 757868e3f09SDaniel Dunbar // Otherwise, we have a simple constant. 7584fd528f2SReid Spencer GenericValue Result; 7596b727599SChris Lattner switch (C->getType()->getTypeID()) { 76087aa65f4SReid Spencer case Type::FloatTyID: 761bed9dc42SDale Johannesen Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 7627a9c62baSReid Spencer break; 76387aa65f4SReid Spencer case Type::DoubleTyID: 764bed9dc42SDale Johannesen Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 76587aa65f4SReid Spencer break; 766a1336cf5SDale Johannesen case Type::X86_FP80TyID: 767a1336cf5SDale Johannesen case Type::FP128TyID: 768a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 76954306fe4SDale Johannesen Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt(); 770a1336cf5SDale Johannesen break; 77187aa65f4SReid Spencer case Type::IntegerTyID: 77287aa65f4SReid Spencer Result.IntVal = cast<ConstantInt>(C)->getValue(); 77387aa65f4SReid Spencer break; 774996fe010SChris Lattner case Type::PointerTyID: 7756a0fd73bSReid Spencer if (isa<ConstantPointerNull>(C)) 776996fe010SChris Lattner Result.PointerVal = 0; 7776a0fd73bSReid Spencer else if (const Function *F = dyn_cast<Function>(C)) 7786a0fd73bSReid Spencer Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 7796a0fd73bSReid Spencer else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) 7806a0fd73bSReid Spencer Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 7810c778f70SChris Lattner else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 7820c778f70SChris Lattner Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>( 7830c778f70SChris Lattner BA->getBasicBlock()))); 784e6492f10SChris Lattner else 785fbcc663cSTorok Edwin llvm_unreachable("Unknown constant pointer type!"); 786996fe010SChris Lattner break; 787996fe010SChris Lattner default: 788868e3f09SDaniel Dunbar SmallString<256> Msg; 789868e3f09SDaniel Dunbar raw_svector_ostream OS(Msg); 790868e3f09SDaniel Dunbar OS << "ERROR: Constant unimplemented for type: " << *C->getType(); 791868e3f09SDaniel Dunbar report_fatal_error(OS.str()); 792996fe010SChris Lattner } 793868e3f09SDaniel Dunbar 794996fe010SChris Lattner return Result; 795996fe010SChris Lattner } 796996fe010SChris Lattner 7971202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 7981202d1b1SDuncan Sands /// with the integer held in IntVal. 7991202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 8001202d1b1SDuncan Sands unsigned StoreBytes) { 8011202d1b1SDuncan Sands assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 8021202d1b1SDuncan Sands uint8_t *Src = (uint8_t *)IntVal.getRawData(); 8035c65cb46SDuncan Sands 804868e3f09SDaniel Dunbar if (sys::isLittleEndianHost()) { 8051202d1b1SDuncan Sands // Little-endian host - the source is ordered from LSB to MSB. Order the 8061202d1b1SDuncan Sands // destination from LSB to MSB: Do a straight copy. 8075c65cb46SDuncan Sands memcpy(Dst, Src, StoreBytes); 808868e3f09SDaniel Dunbar } else { 8095c65cb46SDuncan Sands // Big-endian host - the source is an array of 64 bit words ordered from 8101202d1b1SDuncan Sands // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 8111202d1b1SDuncan Sands // from MSB to LSB: Reverse the word order, but not the bytes in a word. 8125c65cb46SDuncan Sands while (StoreBytes > sizeof(uint64_t)) { 8135c65cb46SDuncan Sands StoreBytes -= sizeof(uint64_t); 8145c65cb46SDuncan Sands // May not be aligned so use memcpy. 8155c65cb46SDuncan Sands memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 8165c65cb46SDuncan Sands Src += sizeof(uint64_t); 8175c65cb46SDuncan Sands } 8185c65cb46SDuncan Sands 8195c65cb46SDuncan Sands memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 820815f8dd2SReid Spencer } 8217a9c62baSReid Spencer } 8221202d1b1SDuncan Sands 82309053e62SEvan Cheng void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, 82409053e62SEvan Cheng GenericValue *Ptr, const Type *Ty) { 8251202d1b1SDuncan Sands const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty); 8261202d1b1SDuncan Sands 8271202d1b1SDuncan Sands switch (Ty->getTypeID()) { 8281202d1b1SDuncan Sands case Type::IntegerTyID: 8291202d1b1SDuncan Sands StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes); 8301202d1b1SDuncan Sands break; 831996fe010SChris Lattner case Type::FloatTyID: 83287aa65f4SReid Spencer *((float*)Ptr) = Val.FloatVal; 83387aa65f4SReid Spencer break; 83487aa65f4SReid Spencer case Type::DoubleTyID: 83587aa65f4SReid Spencer *((double*)Ptr) = Val.DoubleVal; 836996fe010SChris Lattner break; 8374d7e4ee7SDale Johannesen case Type::X86_FP80TyID: 8384d7e4ee7SDale Johannesen memcpy(Ptr, Val.IntVal.getRawData(), 10); 839a1336cf5SDale Johannesen break; 8407a9c62baSReid Spencer case Type::PointerTyID: 8411202d1b1SDuncan Sands // Ensure 64 bit target pointers are fully initialized on 32 bit hosts. 8421202d1b1SDuncan Sands if (StoreBytes != sizeof(PointerTy)) 8431202d1b1SDuncan Sands memset(Ptr, 0, StoreBytes); 8441202d1b1SDuncan Sands 84587aa65f4SReid Spencer *((PointerTy*)Ptr) = Val.PointerVal; 846996fe010SChris Lattner break; 847996fe010SChris Lattner default: 8480967d2dfSDavid Greene dbgs() << "Cannot store value of type " << *Ty << "!\n"; 849996fe010SChris Lattner } 8501202d1b1SDuncan Sands 851aa121227SChris Lattner if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian()) 8521202d1b1SDuncan Sands // Host and target are different endian - reverse the stored bytes. 8531202d1b1SDuncan Sands std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr); 854996fe010SChris Lattner } 855996fe010SChris Lattner 8561202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 8571202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 8581202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) { 8591202d1b1SDuncan Sands assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 8601202d1b1SDuncan Sands uint8_t *Dst = (uint8_t *)IntVal.getRawData(); 8615c65cb46SDuncan Sands 862aa121227SChris Lattner if (sys::isLittleEndianHost()) 8635c65cb46SDuncan Sands // Little-endian host - the destination must be ordered from LSB to MSB. 8645c65cb46SDuncan Sands // The source is ordered from LSB to MSB: Do a straight copy. 8655c65cb46SDuncan Sands memcpy(Dst, Src, LoadBytes); 8665c65cb46SDuncan Sands else { 8675c65cb46SDuncan Sands // Big-endian - the destination is an array of 64 bit words ordered from 8685c65cb46SDuncan Sands // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 8695c65cb46SDuncan Sands // ordered from MSB to LSB: Reverse the word order, but not the bytes in 8705c65cb46SDuncan Sands // a word. 8715c65cb46SDuncan Sands while (LoadBytes > sizeof(uint64_t)) { 8725c65cb46SDuncan Sands LoadBytes -= sizeof(uint64_t); 8735c65cb46SDuncan Sands // May not be aligned so use memcpy. 8745c65cb46SDuncan Sands memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 8755c65cb46SDuncan Sands Dst += sizeof(uint64_t); 8765c65cb46SDuncan Sands } 8775c65cb46SDuncan Sands 8785c65cb46SDuncan Sands memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 8795c65cb46SDuncan Sands } 8807a9c62baSReid Spencer } 8811202d1b1SDuncan Sands 8821202d1b1SDuncan Sands /// FIXME: document 8831202d1b1SDuncan Sands /// 8841202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 8851202d1b1SDuncan Sands GenericValue *Ptr, 8861202d1b1SDuncan Sands const Type *Ty) { 8871202d1b1SDuncan Sands const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty); 8881202d1b1SDuncan Sands 8891202d1b1SDuncan Sands switch (Ty->getTypeID()) { 8901202d1b1SDuncan Sands case Type::IntegerTyID: 8911202d1b1SDuncan Sands // An APInt with all words initially zero. 8921202d1b1SDuncan Sands Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0); 8931202d1b1SDuncan Sands LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes); 8941202d1b1SDuncan Sands break; 8957f389e8cSChris Lattner case Type::FloatTyID: 89687aa65f4SReid Spencer Result.FloatVal = *((float*)Ptr); 89787aa65f4SReid Spencer break; 89887aa65f4SReid Spencer case Type::DoubleTyID: 89987aa65f4SReid Spencer Result.DoubleVal = *((double*)Ptr); 9007f389e8cSChris Lattner break; 9017a9c62baSReid Spencer case Type::PointerTyID: 90287aa65f4SReid Spencer Result.PointerVal = *((PointerTy*)Ptr); 9037f389e8cSChris Lattner break; 904a1336cf5SDale Johannesen case Type::X86_FP80TyID: { 905a1336cf5SDale Johannesen // This is endian dependent, but it will only work on x86 anyway. 90626d6539eSDuncan Sands // FIXME: Will not trap if loading a signaling NaN. 907ff306287SDuncan Sands uint64_t y[2]; 9084d7e4ee7SDale Johannesen memcpy(y, Ptr, 10); 909ff306287SDuncan Sands Result.IntVal = APInt(80, 2, y); 910a1336cf5SDale Johannesen break; 911a1336cf5SDale Johannesen } 9127f389e8cSChris Lattner default: 913868e3f09SDaniel Dunbar SmallString<256> Msg; 914868e3f09SDaniel Dunbar raw_svector_ostream OS(Msg); 915868e3f09SDaniel Dunbar OS << "Cannot load value of type " << *Ty << "!"; 916868e3f09SDaniel Dunbar report_fatal_error(OS.str()); 9177f389e8cSChris Lattner } 9187f389e8cSChris Lattner } 9197f389e8cSChris Lattner 920996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 9210967d2dfSDavid Greene DEBUG(dbgs() << "JIT: Initializing " << Addr << " "); 922b086d382SDale Johannesen DEBUG(Init->dump()); 92361753bf8SChris Lattner if (isa<UndefValue>(Init)) { 92461753bf8SChris Lattner return; 925d84d35baSReid Spencer } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 92669d62138SRobert Bocchino unsigned ElementSize = 927af9eaa83SDuncan Sands getTargetData()->getTypeAllocSize(CP->getType()->getElementType()); 92869d62138SRobert Bocchino for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 92969d62138SRobert Bocchino InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 93069d62138SRobert Bocchino return; 9311dd86b11SChris Lattner } else if (isa<ConstantAggregateZero>(Init)) { 932af9eaa83SDuncan Sands memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType())); 9331dd86b11SChris Lattner return; 93469ddfbfeSDan Gohman } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) { 93569ddfbfeSDan Gohman unsigned ElementSize = 936af9eaa83SDuncan Sands getTargetData()->getTypeAllocSize(CPA->getType()->getElementType()); 93769ddfbfeSDan Gohman for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 93869ddfbfeSDan Gohman InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 93969ddfbfeSDan Gohman return; 94069ddfbfeSDan Gohman } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) { 94169ddfbfeSDan Gohman const StructLayout *SL = 94269ddfbfeSDan Gohman getTargetData()->getStructLayout(cast<StructType>(CPS->getType())); 94369ddfbfeSDan Gohman for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 94469ddfbfeSDan Gohman InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 94569ddfbfeSDan Gohman return; 94661753bf8SChris Lattner } else if (Init->getType()->isFirstClassType()) { 947996fe010SChris Lattner GenericValue Val = getConstantValue(Init); 948996fe010SChris Lattner StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 949996fe010SChris Lattner return; 950996fe010SChris Lattner } 951996fe010SChris Lattner 952868e3f09SDaniel Dunbar DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n"); 953fbcc663cSTorok Edwin llvm_unreachable("Unknown constant type to initialize memory with!"); 954996fe010SChris Lattner } 955996fe010SChris Lattner 956996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their 957996fe010SChris Lattner /// addresses into GlobalAddress. This must make sure to copy the contents of 958996fe010SChris Lattner /// their initializers into the memory. 959996fe010SChris Lattner void ExecutionEngine::emitGlobals() { 960996fe010SChris Lattner // Loop over all of the global variables in the program, allocating the memory 9610621caefSChris Lattner // to hold them. If there is more than one module, do a prepass over globals 9620621caefSChris Lattner // to figure out how the different modules should link together. 9630621caefSChris Lattner std::map<std::pair<std::string, const Type*>, 9640621caefSChris Lattner const GlobalValue*> LinkedGlobalsMap; 9650621caefSChris Lattner 9660621caefSChris Lattner if (Modules.size() != 1) { 9670621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 968091217beSJeffrey Yasskin Module &M = *Modules[m]; 9690621caefSChris Lattner for (Module::const_global_iterator I = M.global_begin(), 9700621caefSChris Lattner E = M.global_end(); I != E; ++I) { 9710621caefSChris Lattner const GlobalValue *GV = I; 9726de96a1bSRafael Espindola if (GV->hasLocalLinkage() || GV->isDeclaration() || 9730621caefSChris Lattner GV->hasAppendingLinkage() || !GV->hasName()) 9740621caefSChris Lattner continue;// Ignore external globals and globals with internal linkage. 9750621caefSChris Lattner 9760621caefSChris Lattner const GlobalValue *&GVEntry = 9770621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 9780621caefSChris Lattner 9790621caefSChris Lattner // If this is the first time we've seen this global, it is the canonical 9800621caefSChris Lattner // version. 9810621caefSChris Lattner if (!GVEntry) { 9820621caefSChris Lattner GVEntry = GV; 9830621caefSChris Lattner continue; 9840621caefSChris Lattner } 9850621caefSChris Lattner 9860621caefSChris Lattner // If the existing global is strong, never replace it. 987d61d39ecSAnton Korobeynikov if (GVEntry->hasExternalLinkage() || 988d61d39ecSAnton Korobeynikov GVEntry->hasDLLImportLinkage() || 989d61d39ecSAnton Korobeynikov GVEntry->hasDLLExportLinkage()) 9900621caefSChris Lattner continue; 9910621caefSChris Lattner 9920621caefSChris Lattner // Otherwise, we know it's linkonce/weak, replace it if this is a strong 993ce4396bcSDale Johannesen // symbol. FIXME is this right for common? 99412c94949SAnton Korobeynikov if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 9950621caefSChris Lattner GVEntry = GV; 9960621caefSChris Lattner } 9970621caefSChris Lattner } 9980621caefSChris Lattner } 9990621caefSChris Lattner 10000621caefSChris Lattner std::vector<const GlobalValue*> NonCanonicalGlobals; 10010621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1002091217beSJeffrey Yasskin Module &M = *Modules[m]; 10038ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 10040621caefSChris Lattner I != E; ++I) { 10050621caefSChris Lattner // In the multi-module case, see what this global maps to. 10060621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 10070621caefSChris Lattner if (const GlobalValue *GVEntry = 10080621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) { 10090621caefSChris Lattner // If something else is the canonical global, ignore this one. 10100621caefSChris Lattner if (GVEntry != &*I) { 10110621caefSChris Lattner NonCanonicalGlobals.push_back(I); 10120621caefSChris Lattner continue; 10130621caefSChris Lattner } 10140621caefSChris Lattner } 10150621caefSChris Lattner } 10160621caefSChris Lattner 10175301e7c6SReid Spencer if (!I->isDeclaration()) { 10185457ce9aSNicolas Geoffray addGlobalMapping(I, getMemoryForGV(I)); 1019996fe010SChris Lattner } else { 1020e8bbcfc2SBrian Gaeke // External variable reference. Try to use the dynamic loader to 1021e8bbcfc2SBrian Gaeke // get a pointer to it. 10220621caefSChris Lattner if (void *SymAddr = 10235899e340SDaniel Dunbar sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName())) 1024748e8579SChris Lattner addGlobalMapping(I, SymAddr); 10259de0d14dSChris Lattner else { 10262104b8d3SChris Lattner report_fatal_error("Could not resolve external global address: " 10276c2d233eSTorok Edwin +I->getName()); 10289de0d14dSChris Lattner } 1029996fe010SChris Lattner } 10300621caefSChris Lattner } 10310621caefSChris Lattner 10320621caefSChris Lattner // If there are multiple modules, map the non-canonical globals to their 10330621caefSChris Lattner // canonical location. 10340621caefSChris Lattner if (!NonCanonicalGlobals.empty()) { 10350621caefSChris Lattner for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 10360621caefSChris Lattner const GlobalValue *GV = NonCanonicalGlobals[i]; 10370621caefSChris Lattner const GlobalValue *CGV = 10380621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 10390621caefSChris Lattner void *Ptr = getPointerToGlobalIfAvailable(CGV); 10400621caefSChris Lattner assert(Ptr && "Canonical global wasn't codegen'd!"); 1041a67f06b9SNuno Lopes addGlobalMapping(GV, Ptr); 10420621caefSChris Lattner } 10430621caefSChris Lattner } 1044996fe010SChris Lattner 10457a9c62baSReid Spencer // Now that all of the globals are set up in memory, loop through them all 10467a9c62baSReid Spencer // and initialize their contents. 10478ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 10480621caefSChris Lattner I != E; ++I) { 10495301e7c6SReid Spencer if (!I->isDeclaration()) { 10500621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 10510621caefSChris Lattner if (const GlobalValue *GVEntry = 10520621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) 10530621caefSChris Lattner if (GVEntry != &*I) // Not the canonical variable. 10540621caefSChris Lattner continue; 10550621caefSChris Lattner } 10566bbe3eceSChris Lattner EmitGlobalVariable(I); 10576bbe3eceSChris Lattner } 10580621caefSChris Lattner } 10590621caefSChris Lattner } 10600621caefSChris Lattner } 10616bbe3eceSChris Lattner 10626bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the 10636bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not 10646bbe3eceSChris Lattner // already in the map. 1065fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 1066748e8579SChris Lattner void *GA = getPointerToGlobalIfAvailable(GV); 1067dc631735SChris Lattner 10686bbe3eceSChris Lattner if (GA == 0) { 10696bbe3eceSChris Lattner // If it's not already specified, allocate memory for the global. 10705457ce9aSNicolas Geoffray GA = getMemoryForGV(GV); 1071748e8579SChris Lattner addGlobalMapping(GV, GA); 10726bbe3eceSChris Lattner } 1073fbcc0aa1SChris Lattner 10745457ce9aSNicolas Geoffray // Don't initialize if it's thread local, let the client do it. 10755457ce9aSNicolas Geoffray if (!GV->isThreadLocal()) 10766bbe3eceSChris Lattner InitializeMemory(GV->getInitializer(), GA); 10775457ce9aSNicolas Geoffray 10785457ce9aSNicolas Geoffray const Type *ElTy = GV->getType()->getElementType(); 1079af9eaa83SDuncan Sands size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy); 1080df1f1524SChris Lattner NumInitBytes += (unsigned)GVSize; 10816bbe3eceSChris Lattner ++NumGlobals; 1082996fe010SChris Lattner } 1083f98e981cSJeffrey Yasskin 1084d0fc8f80SJeffrey Yasskin ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE) 1085d0fc8f80SJeffrey Yasskin : EE(EE), GlobalAddressMap(this) { 1086f98e981cSJeffrey Yasskin } 1087f98e981cSJeffrey Yasskin 1088868e3f09SDaniel Dunbar sys::Mutex * 1089868e3f09SDaniel Dunbar ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) { 1090d0fc8f80SJeffrey Yasskin return &EES->EE.lock; 1091d0fc8f80SJeffrey Yasskin } 1092868e3f09SDaniel Dunbar 1093868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES, 1094868e3f09SDaniel Dunbar const GlobalValue *Old) { 1095d0fc8f80SJeffrey Yasskin void *OldVal = EES->GlobalAddressMap.lookup(Old); 1096d0fc8f80SJeffrey Yasskin EES->GlobalAddressReverseMap.erase(OldVal); 1097d0fc8f80SJeffrey Yasskin } 1098d0fc8f80SJeffrey Yasskin 1099868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *, 1100868e3f09SDaniel Dunbar const GlobalValue *, 1101868e3f09SDaniel Dunbar const GlobalValue *) { 1102f98e981cSJeffrey Yasskin assert(false && "The ExecutionEngine doesn't know how to handle a" 1103f98e981cSJeffrey Yasskin " RAUW on a value it has a global mapping for."); 1104f98e981cSJeffrey Yasskin } 1105