ExecutionEngine.cpp 48 KB

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