ExecutionEngine.cpp 46 KB

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