ExecutionEngine.cpp 48 KB

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