ExecutionEngine.cpp 46 KB

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