ExecutionEngine.cpp 47 KB

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