ExecutionEngine.cpp 46 KB

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