ExecutionEngine.cpp 48 KB

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