ExecutionEngine.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/Module.h"
  18. #include "llvm/ModuleProvider.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Config/alloca.h"
  21. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  22. #include "llvm/ExecutionEngine/GenericValue.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/MutexGuard.h"
  26. #include "llvm/System/DynamicLibrary.h"
  27. #include "llvm/System/Host.h"
  28. #include "llvm/Target/TargetData.h"
  29. #include <cmath>
  30. #include <cstring>
  31. using namespace llvm;
  32. STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
  33. STATISTIC(NumGlobals , "Number of global vars initialized");
  34. ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
  35. ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
  36. ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
  37. ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
  38. LazyCompilationDisabled = false;
  39. GVCompilationDisabled = false;
  40. SymbolSearchingDisabled = false;
  41. DlsymStubsEnabled = false;
  42. Modules.push_back(P);
  43. assert(P && "ModuleProvider is null?");
  44. }
  45. ExecutionEngine::~ExecutionEngine() {
  46. clearAllGlobalMappings();
  47. for (unsigned i = 0, e = Modules.size(); i != e; ++i)
  48. delete Modules[i];
  49. }
  50. char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
  51. const Type *ElTy = GV->getType()->getElementType();
  52. size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
  53. return new char[GVSize];
  54. }
  55. /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
  56. /// Relases the Module from the ModuleProvider, materializing it in the
  57. /// process, and returns the materialized Module.
  58. Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
  59. std::string *ErrInfo) {
  60. for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
  61. E = Modules.end(); I != E; ++I) {
  62. ModuleProvider *MP = *I;
  63. if (MP == P) {
  64. Modules.erase(I);
  65. clearGlobalMappingsFromModule(MP->getModule());
  66. return MP->releaseModule(ErrInfo);
  67. }
  68. }
  69. return NULL;
  70. }
  71. /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
  72. /// and deletes the ModuleProvider and owned Module. Avoids materializing
  73. /// the underlying module.
  74. void ExecutionEngine::deleteModuleProvider(ModuleProvider *P,
  75. std::string *ErrInfo) {
  76. for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
  77. E = Modules.end(); I != E; ++I) {
  78. ModuleProvider *MP = *I;
  79. if (MP == P) {
  80. Modules.erase(I);
  81. clearGlobalMappingsFromModule(MP->getModule());
  82. delete MP;
  83. return;
  84. }
  85. }
  86. }
  87. /// FindFunctionNamed - Search all of the active modules to find the one that
  88. /// defines FnName. This is very slow operation and shouldn't be used for
  89. /// general code.
  90. Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
  91. for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
  92. if (Function *F = Modules[i]->getModule()->getFunction(FnName))
  93. return F;
  94. }
  95. return 0;
  96. }
  97. /// addGlobalMapping - Tell the execution engine that the specified global is
  98. /// at the specified location. This is used internally as functions are JIT'd
  99. /// and as global variables are laid out in memory. It can and should also be
  100. /// used by clients of the EE that want to have an LLVM global overlay
  101. /// existing data in memory.
  102. void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
  103. MutexGuard locked(lock);
  104. DOUT << "JIT: Map \'" << GV->getNameStart() << "\' to [" << Addr << "]\n";
  105. void *&CurVal = state.getGlobalAddressMap(locked)[GV];
  106. assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
  107. CurVal = Addr;
  108. // If we are using the reverse mapping, add it too
  109. if (!state.getGlobalAddressReverseMap(locked).empty()) {
  110. const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
  111. assert((V == 0 || GV == 0) && "GlobalMapping already established!");
  112. V = GV;
  113. }
  114. }
  115. /// clearAllGlobalMappings - Clear all global mappings and start over again
  116. /// use in dynamic compilation scenarios when you want to move globals
  117. void ExecutionEngine::clearAllGlobalMappings() {
  118. MutexGuard locked(lock);
  119. state.getGlobalAddressMap(locked).clear();
  120. state.getGlobalAddressReverseMap(locked).clear();
  121. }
  122. /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
  123. /// particular module, because it has been removed from the JIT.
  124. void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
  125. MutexGuard locked(lock);
  126. for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
  127. state.getGlobalAddressMap(locked).erase(FI);
  128. state.getGlobalAddressReverseMap(locked).erase(FI);
  129. }
  130. for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
  131. GI != GE; ++GI) {
  132. state.getGlobalAddressMap(locked).erase(GI);
  133. state.getGlobalAddressReverseMap(locked).erase(GI);
  134. }
  135. }
  136. /// updateGlobalMapping - Replace an existing mapping for GV with a new
  137. /// address. This updates both maps as required. If "Addr" is null, the
  138. /// entry for the global is removed from the mappings.
  139. void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
  140. MutexGuard locked(lock);
  141. std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
  142. // Deleting from the mapping?
  143. if (Addr == 0) {
  144. std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
  145. void *OldVal;
  146. if (I == Map.end())
  147. OldVal = 0;
  148. else {
  149. OldVal = I->second;
  150. Map.erase(I);
  151. }
  152. if (!state.getGlobalAddressReverseMap(locked).empty())
  153. state.getGlobalAddressReverseMap(locked).erase(Addr);
  154. return OldVal;
  155. }
  156. void *&CurVal = Map[GV];
  157. void *OldVal = CurVal;
  158. if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
  159. state.getGlobalAddressReverseMap(locked).erase(CurVal);
  160. CurVal = Addr;
  161. // If we are using the reverse mapping, add it too
  162. if (!state.getGlobalAddressReverseMap(locked).empty()) {
  163. const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
  164. assert((V == 0 || GV == 0) && "GlobalMapping already established!");
  165. V = GV;
  166. }
  167. return OldVal;
  168. }
  169. /// getPointerToGlobalIfAvailable - This returns the address of the specified
  170. /// global value if it is has already been codegen'd, otherwise it returns null.
  171. ///
  172. void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
  173. MutexGuard locked(lock);
  174. std::map<const GlobalValue*, void*>::iterator I =
  175. state.getGlobalAddressMap(locked).find(GV);
  176. return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
  177. }
  178. /// getGlobalValueAtAddress - Return the LLVM global value object that starts
  179. /// at the specified address.
  180. ///
  181. const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
  182. MutexGuard locked(lock);
  183. // If we haven't computed the reverse mapping yet, do so first.
  184. if (state.getGlobalAddressReverseMap(locked).empty()) {
  185. for (std::map<const GlobalValue*, void *>::iterator
  186. I = state.getGlobalAddressMap(locked).begin(),
  187. E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
  188. state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
  189. I->first));
  190. }
  191. std::map<void *, const GlobalValue*>::iterator I =
  192. state.getGlobalAddressReverseMap(locked).find(Addr);
  193. return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
  194. }
  195. // CreateArgv - Turn a vector of strings into a nice argv style array of
  196. // pointers to null terminated strings.
  197. //
  198. static void *CreateArgv(ExecutionEngine *EE,
  199. const std::vector<std::string> &InputArgv) {
  200. unsigned PtrSize = EE->getTargetData()->getPointerSize();
  201. char *Result = new char[(InputArgv.size()+1)*PtrSize];
  202. DOUT << "JIT: ARGV = " << (void*)Result << "\n";
  203. const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
  204. for (unsigned i = 0; i != InputArgv.size(); ++i) {
  205. unsigned Size = InputArgv[i].size()+1;
  206. char *Dest = new char[Size];
  207. DOUT << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n";
  208. std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
  209. Dest[Size-1] = 0;
  210. // Endian safe: Result[i] = (PointerTy)Dest;
  211. EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
  212. SBytePtr);
  213. }
  214. // Null terminate it
  215. EE->StoreValueToMemory(PTOGV(0),
  216. (GenericValue*)(Result+InputArgv.size()*PtrSize),
  217. SBytePtr);
  218. return Result;
  219. }
  220. /// runStaticConstructorsDestructors - This method is used to execute all of
  221. /// the static constructors or destructors for a module, depending on the
  222. /// value of isDtors.
  223. void ExecutionEngine::runStaticConstructorsDestructors(Module *module, bool isDtors) {
  224. const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
  225. // Execute global ctors/dtors for each module in the program.
  226. GlobalVariable *GV = module->getNamedGlobal(Name);
  227. // If this global has internal linkage, or if it has a use, then it must be
  228. // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
  229. // this is the case, don't execute any of the global ctors, __main will do
  230. // it.
  231. if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
  232. // Should be an array of '{ int, void ()* }' structs. The first value is
  233. // the init priority, which we ignore.
  234. ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
  235. if (!InitList) return;
  236. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
  237. if (ConstantStruct *CS =
  238. dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
  239. if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
  240. Constant *FP = CS->getOperand(1);
  241. if (FP->isNullValue())
  242. break; // Found a null terminator, exit.
  243. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
  244. if (CE->isCast())
  245. FP = CE->getOperand(0);
  246. if (Function *F = dyn_cast<Function>(FP)) {
  247. // Execute the ctor/dtor function!
  248. runFunction(F, std::vector<GenericValue>());
  249. }
  250. }
  251. }
  252. /// runStaticConstructorsDestructors - This method is used to execute all of
  253. /// the static constructors or destructors for a program, depending on the
  254. /// value of isDtors.
  255. void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
  256. // Execute global ctors/dtors for each module in the program.
  257. for (unsigned m = 0, e = Modules.size(); m != e; ++m)
  258. runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors);
  259. }
  260. #ifndef NDEBUG
  261. /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
  262. static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
  263. unsigned PtrSize = EE->getTargetData()->getPointerSize();
  264. for (unsigned i = 0; i < PtrSize; ++i)
  265. if (*(i + (uint8_t*)Loc))
  266. return false;
  267. return true;
  268. }
  269. #endif
  270. /// runFunctionAsMain - This is a helper function which wraps runFunction to
  271. /// handle the common task of starting up main with the specified argc, argv,
  272. /// and envp parameters.
  273. int ExecutionEngine::runFunctionAsMain(Function *Fn,
  274. const std::vector<std::string> &argv,
  275. const char * const * envp) {
  276. std::vector<GenericValue> GVArgs;
  277. GenericValue GVArgc;
  278. GVArgc.IntVal = APInt(32, argv.size());
  279. // Check main() type
  280. unsigned NumArgs = Fn->getFunctionType()->getNumParams();
  281. const FunctionType *FTy = Fn->getFunctionType();
  282. const Type* PPInt8Ty =
  283. PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
  284. switch (NumArgs) {
  285. case 3:
  286. if (FTy->getParamType(2) != PPInt8Ty) {
  287. cerr << "Invalid type for third argument of main() supplied\n";
  288. abort();
  289. }
  290. // FALLS THROUGH
  291. case 2:
  292. if (FTy->getParamType(1) != PPInt8Ty) {
  293. cerr << "Invalid type for second argument of main() supplied\n";
  294. abort();
  295. }
  296. // FALLS THROUGH
  297. case 1:
  298. if (FTy->getParamType(0) != Type::Int32Ty) {
  299. cerr << "Invalid type for first argument of main() supplied\n";
  300. abort();
  301. }
  302. // FALLS THROUGH
  303. case 0:
  304. if (!isa<IntegerType>(FTy->getReturnType()) &&
  305. FTy->getReturnType() != Type::VoidTy) {
  306. cerr << "Invalid return type of main() supplied\n";
  307. abort();
  308. }
  309. break;
  310. default:
  311. cerr << "Invalid number of arguments of main() supplied\n";
  312. abort();
  313. }
  314. if (NumArgs) {
  315. GVArgs.push_back(GVArgc); // Arg #0 = argc.
  316. if (NumArgs > 1) {
  317. GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
  318. assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
  319. "argv[0] was null after CreateArgv");
  320. if (NumArgs > 2) {
  321. std::vector<std::string> EnvVars;
  322. for (unsigned i = 0; envp[i]; ++i)
  323. EnvVars.push_back(envp[i]);
  324. GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
  325. }
  326. }
  327. }
  328. return runFunction(Fn, GVArgs).IntVal.getZExtValue();
  329. }
  330. /// If possible, create a JIT, unless the caller specifically requests an
  331. /// Interpreter or there's an error. If even an Interpreter cannot be created,
  332. /// NULL is returned.
  333. ///
  334. ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
  335. bool ForceInterpreter,
  336. std::string *ErrorStr,
  337. CodeGenOpt::Level OptLevel) {
  338. ExecutionEngine *EE = 0;
  339. // Make sure we can resolve symbols in the program as well. The zero arg
  340. // to the function tells DynamicLibrary to load the program, not a library.
  341. if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
  342. return 0;
  343. // Unless the interpreter was explicitly selected, try making a JIT.
  344. if (!ForceInterpreter && JITCtor)
  345. EE = JITCtor(MP, ErrorStr, OptLevel);
  346. // If we can't make a JIT, make an interpreter instead.
  347. if (EE == 0 && InterpCtor)
  348. EE = InterpCtor(MP, ErrorStr, OptLevel);
  349. return EE;
  350. }
  351. ExecutionEngine *ExecutionEngine::create(Module *M) {
  352. return create(new ExistingModuleProvider(M));
  353. }
  354. /// getPointerToGlobal - This returns the address of the specified global
  355. /// value. This may involve code generation if it's a function.
  356. ///
  357. void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
  358. if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
  359. return getPointerToFunction(F);
  360. MutexGuard locked(lock);
  361. void *p = state.getGlobalAddressMap(locked)[GV];
  362. if (p)
  363. return p;
  364. // Global variable might have been added since interpreter started.
  365. if (GlobalVariable *GVar =
  366. const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
  367. EmitGlobalVariable(GVar);
  368. else
  369. assert(0 && "Global hasn't had an address allocated yet!");
  370. return state.getGlobalAddressMap(locked)[GV];
  371. }
  372. /// This function converts a Constant* into a GenericValue. The interesting
  373. /// part is if C is a ConstantExpr.
  374. /// @brief Get a GenericValue for a Constant*
  375. GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
  376. // If its undefined, return the garbage.
  377. if (isa<UndefValue>(C))
  378. return GenericValue();
  379. // If the value is a ConstantExpr
  380. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  381. Constant *Op0 = CE->getOperand(0);
  382. switch (CE->getOpcode()) {
  383. case Instruction::GetElementPtr: {
  384. // Compute the index
  385. GenericValue Result = getConstantValue(Op0);
  386. SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
  387. uint64_t Offset =
  388. TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
  389. char* tmp = (char*) Result.PointerVal;
  390. Result = PTOGV(tmp + Offset);
  391. return Result;
  392. }
  393. case Instruction::Trunc: {
  394. GenericValue GV = getConstantValue(Op0);
  395. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  396. GV.IntVal = GV.IntVal.trunc(BitWidth);
  397. return GV;
  398. }
  399. case Instruction::ZExt: {
  400. GenericValue GV = getConstantValue(Op0);
  401. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  402. GV.IntVal = GV.IntVal.zext(BitWidth);
  403. return GV;
  404. }
  405. case Instruction::SExt: {
  406. GenericValue GV = getConstantValue(Op0);
  407. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  408. GV.IntVal = GV.IntVal.sext(BitWidth);
  409. return GV;
  410. }
  411. case Instruction::FPTrunc: {
  412. // FIXME long double
  413. GenericValue GV = getConstantValue(Op0);
  414. GV.FloatVal = float(GV.DoubleVal);
  415. return GV;
  416. }
  417. case Instruction::FPExt:{
  418. // FIXME long double
  419. GenericValue GV = getConstantValue(Op0);
  420. GV.DoubleVal = double(GV.FloatVal);
  421. return GV;
  422. }
  423. case Instruction::UIToFP: {
  424. GenericValue GV = getConstantValue(Op0);
  425. if (CE->getType() == Type::FloatTy)
  426. GV.FloatVal = float(GV.IntVal.roundToDouble());
  427. else if (CE->getType() == Type::DoubleTy)
  428. GV.DoubleVal = GV.IntVal.roundToDouble();
  429. else if (CE->getType() == Type::X86_FP80Ty) {
  430. const uint64_t zero[] = {0, 0};
  431. APFloat apf = APFloat(APInt(80, 2, zero));
  432. (void)apf.convertFromAPInt(GV.IntVal,
  433. false,
  434. APFloat::rmNearestTiesToEven);
  435. GV.IntVal = apf.bitcastToAPInt();
  436. }
  437. return GV;
  438. }
  439. case Instruction::SIToFP: {
  440. GenericValue GV = getConstantValue(Op0);
  441. if (CE->getType() == Type::FloatTy)
  442. GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
  443. else if (CE->getType() == Type::DoubleTy)
  444. GV.DoubleVal = GV.IntVal.signedRoundToDouble();
  445. else if (CE->getType() == Type::X86_FP80Ty) {
  446. const uint64_t zero[] = { 0, 0};
  447. APFloat apf = APFloat(APInt(80, 2, zero));
  448. (void)apf.convertFromAPInt(GV.IntVal,
  449. true,
  450. APFloat::rmNearestTiesToEven);
  451. GV.IntVal = apf.bitcastToAPInt();
  452. }
  453. return GV;
  454. }
  455. case Instruction::FPToUI: // double->APInt conversion handles sign
  456. case Instruction::FPToSI: {
  457. GenericValue GV = getConstantValue(Op0);
  458. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  459. if (Op0->getType() == Type::FloatTy)
  460. GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
  461. else if (Op0->getType() == Type::DoubleTy)
  462. GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
  463. else if (Op0->getType() == Type::X86_FP80Ty) {
  464. APFloat apf = APFloat(GV.IntVal);
  465. uint64_t v;
  466. bool ignored;
  467. (void)apf.convertToInteger(&v, BitWidth,
  468. CE->getOpcode()==Instruction::FPToSI,
  469. APFloat::rmTowardZero, &ignored);
  470. GV.IntVal = v; // endian?
  471. }
  472. return GV;
  473. }
  474. case Instruction::PtrToInt: {
  475. GenericValue GV = getConstantValue(Op0);
  476. uint32_t PtrWidth = TD->getPointerSizeInBits();
  477. GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
  478. return GV;
  479. }
  480. case Instruction::IntToPtr: {
  481. GenericValue GV = getConstantValue(Op0);
  482. uint32_t PtrWidth = TD->getPointerSizeInBits();
  483. if (PtrWidth != GV.IntVal.getBitWidth())
  484. GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
  485. assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
  486. GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
  487. return GV;
  488. }
  489. case Instruction::BitCast: {
  490. GenericValue GV = getConstantValue(Op0);
  491. const Type* DestTy = CE->getType();
  492. switch (Op0->getType()->getTypeID()) {
  493. default: assert(0 && "Invalid bitcast operand");
  494. case Type::IntegerTyID:
  495. assert(DestTy->isFloatingPoint() && "invalid bitcast");
  496. if (DestTy == Type::FloatTy)
  497. GV.FloatVal = GV.IntVal.bitsToFloat();
  498. else if (DestTy == Type::DoubleTy)
  499. GV.DoubleVal = GV.IntVal.bitsToDouble();
  500. break;
  501. case Type::FloatTyID:
  502. assert(DestTy == Type::Int32Ty && "Invalid bitcast");
  503. GV.IntVal.floatToBits(GV.FloatVal);
  504. break;
  505. case Type::DoubleTyID:
  506. assert(DestTy == Type::Int64Ty && "Invalid bitcast");
  507. GV.IntVal.doubleToBits(GV.DoubleVal);
  508. break;
  509. case Type::PointerTyID:
  510. assert(isa<PointerType>(DestTy) && "Invalid bitcast");
  511. break; // getConstantValue(Op0) above already converted it
  512. }
  513. return GV;
  514. }
  515. case Instruction::Add:
  516. case Instruction::FAdd:
  517. case Instruction::Sub:
  518. case Instruction::FSub:
  519. case Instruction::Mul:
  520. case Instruction::FMul:
  521. case Instruction::UDiv:
  522. case Instruction::SDiv:
  523. case Instruction::URem:
  524. case Instruction::SRem:
  525. case Instruction::And:
  526. case Instruction::Or:
  527. case Instruction::Xor: {
  528. GenericValue LHS = getConstantValue(Op0);
  529. GenericValue RHS = getConstantValue(CE->getOperand(1));
  530. GenericValue GV;
  531. switch (CE->getOperand(0)->getType()->getTypeID()) {
  532. default: assert(0 && "Bad add type!"); abort();
  533. case Type::IntegerTyID:
  534. switch (CE->getOpcode()) {
  535. default: assert(0 && "Invalid integer opcode");
  536. case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
  537. case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
  538. case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
  539. case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
  540. case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
  541. case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
  542. case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
  543. case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
  544. case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
  545. case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
  546. }
  547. break;
  548. case Type::FloatTyID:
  549. switch (CE->getOpcode()) {
  550. default: assert(0 && "Invalid float opcode"); abort();
  551. case Instruction::FAdd:
  552. GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
  553. case Instruction::FSub:
  554. GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
  555. case Instruction::FMul:
  556. GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
  557. case Instruction::FDiv:
  558. GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
  559. case Instruction::FRem:
  560. GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
  561. }
  562. break;
  563. case Type::DoubleTyID:
  564. switch (CE->getOpcode()) {
  565. default: assert(0 && "Invalid double opcode"); abort();
  566. case Instruction::FAdd:
  567. GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
  568. case Instruction::FSub:
  569. GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
  570. case Instruction::FMul:
  571. GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
  572. case Instruction::FDiv:
  573. GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
  574. case Instruction::FRem:
  575. GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
  576. }
  577. break;
  578. case Type::X86_FP80TyID:
  579. case Type::PPC_FP128TyID:
  580. case Type::FP128TyID: {
  581. APFloat apfLHS = APFloat(LHS.IntVal);
  582. switch (CE->getOpcode()) {
  583. default: assert(0 && "Invalid long double opcode");llvm_unreachable();
  584. case Instruction::FAdd:
  585. apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  586. GV.IntVal = apfLHS.bitcastToAPInt();
  587. break;
  588. case Instruction::FSub:
  589. apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  590. GV.IntVal = apfLHS.bitcastToAPInt();
  591. break;
  592. case Instruction::FMul:
  593. apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  594. GV.IntVal = apfLHS.bitcastToAPInt();
  595. break;
  596. case Instruction::FDiv:
  597. apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  598. GV.IntVal = apfLHS.bitcastToAPInt();
  599. break;
  600. case Instruction::FRem:
  601. apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  602. GV.IntVal = apfLHS.bitcastToAPInt();
  603. break;
  604. }
  605. }
  606. break;
  607. }
  608. return GV;
  609. }
  610. default:
  611. break;
  612. }
  613. cerr << "ConstantExpr not handled: " << *CE << "\n";
  614. abort();
  615. }
  616. GenericValue Result;
  617. switch (C->getType()->getTypeID()) {
  618. case Type::FloatTyID:
  619. Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
  620. break;
  621. case Type::DoubleTyID:
  622. Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
  623. break;
  624. case Type::X86_FP80TyID:
  625. case Type::FP128TyID:
  626. case Type::PPC_FP128TyID:
  627. Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
  628. break;
  629. case Type::IntegerTyID:
  630. Result.IntVal = cast<ConstantInt>(C)->getValue();
  631. break;
  632. case Type::PointerTyID:
  633. if (isa<ConstantPointerNull>(C))
  634. Result.PointerVal = 0;
  635. else if (const Function *F = dyn_cast<Function>(C))
  636. Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
  637. else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
  638. Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
  639. else
  640. assert(0 && "Unknown constant pointer type!");
  641. break;
  642. default:
  643. cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
  644. abort();
  645. }
  646. return Result;
  647. }
  648. /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
  649. /// with the integer held in IntVal.
  650. static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
  651. unsigned StoreBytes) {
  652. assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
  653. uint8_t *Src = (uint8_t *)IntVal.getRawData();
  654. if (sys::isLittleEndianHost())
  655. // Little-endian host - the source is ordered from LSB to MSB. Order the
  656. // destination from LSB to MSB: Do a straight copy.
  657. memcpy(Dst, Src, StoreBytes);
  658. else {
  659. // Big-endian host - the source is an array of 64 bit words ordered from
  660. // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
  661. // from MSB to LSB: Reverse the word order, but not the bytes in a word.
  662. while (StoreBytes > sizeof(uint64_t)) {
  663. StoreBytes -= sizeof(uint64_t);
  664. // May not be aligned so use memcpy.
  665. memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
  666. Src += sizeof(uint64_t);
  667. }
  668. memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
  669. }
  670. }
  671. /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
  672. /// is the address of the memory at which to store Val, cast to GenericValue *.
  673. /// It is not a pointer to a GenericValue containing the address at which to
  674. /// store Val.
  675. void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
  676. GenericValue *Ptr, const Type *Ty) {
  677. const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
  678. switch (Ty->getTypeID()) {
  679. case Type::IntegerTyID:
  680. StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
  681. break;
  682. case Type::FloatTyID:
  683. *((float*)Ptr) = Val.FloatVal;
  684. break;
  685. case Type::DoubleTyID:
  686. *((double*)Ptr) = Val.DoubleVal;
  687. break;
  688. case Type::X86_FP80TyID:
  689. memcpy(Ptr, Val.IntVal.getRawData(), 10);
  690. break;
  691. case Type::PointerTyID:
  692. // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
  693. if (StoreBytes != sizeof(PointerTy))
  694. memset(Ptr, 0, StoreBytes);
  695. *((PointerTy*)Ptr) = Val.PointerVal;
  696. break;
  697. default:
  698. cerr << "Cannot store value of type " << *Ty << "!\n";
  699. }
  700. if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
  701. // Host and target are different endian - reverse the stored bytes.
  702. std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
  703. }
  704. /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
  705. /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
  706. static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
  707. assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
  708. uint8_t *Dst = (uint8_t *)IntVal.getRawData();
  709. if (sys::isLittleEndianHost())
  710. // Little-endian host - the destination must be ordered from LSB to MSB.
  711. // The source is ordered from LSB to MSB: Do a straight copy.
  712. memcpy(Dst, Src, LoadBytes);
  713. else {
  714. // Big-endian - the destination is an array of 64 bit words ordered from
  715. // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
  716. // ordered from MSB to LSB: Reverse the word order, but not the bytes in
  717. // a word.
  718. while (LoadBytes > sizeof(uint64_t)) {
  719. LoadBytes -= sizeof(uint64_t);
  720. // May not be aligned so use memcpy.
  721. memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
  722. Dst += sizeof(uint64_t);
  723. }
  724. memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
  725. }
  726. }
  727. /// FIXME: document
  728. ///
  729. void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
  730. GenericValue *Ptr,
  731. const Type *Ty) {
  732. const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
  733. if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian()) {
  734. // Host and target are different endian - reverse copy the stored
  735. // bytes into a buffer, and load from that.
  736. uint8_t *Src = (uint8_t*)Ptr;
  737. uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
  738. std::reverse_copy(Src, Src + LoadBytes, Buf);
  739. Ptr = (GenericValue*)Buf;
  740. }
  741. switch (Ty->getTypeID()) {
  742. case Type::IntegerTyID:
  743. // An APInt with all words initially zero.
  744. Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
  745. LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
  746. break;
  747. case Type::FloatTyID:
  748. Result.FloatVal = *((float*)Ptr);
  749. break;
  750. case Type::DoubleTyID:
  751. Result.DoubleVal = *((double*)Ptr);
  752. break;
  753. case Type::PointerTyID:
  754. Result.PointerVal = *((PointerTy*)Ptr);
  755. break;
  756. case Type::X86_FP80TyID: {
  757. // This is endian dependent, but it will only work on x86 anyway.
  758. // FIXME: Will not trap if loading a signaling NaN.
  759. uint64_t y[2];
  760. memcpy(y, Ptr, 10);
  761. Result.IntVal = APInt(80, 2, y);
  762. break;
  763. }
  764. default:
  765. cerr << "Cannot load value of type " << *Ty << "!\n";
  766. abort();
  767. }
  768. }
  769. // InitializeMemory - Recursive function to apply a Constant value into the
  770. // specified memory location...
  771. //
  772. void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
  773. DOUT << "JIT: Initializing " << Addr << " ";
  774. DEBUG(Init->dump());
  775. if (isa<UndefValue>(Init)) {
  776. return;
  777. } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
  778. unsigned ElementSize =
  779. getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
  780. for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
  781. InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
  782. return;
  783. } else if (isa<ConstantAggregateZero>(Init)) {
  784. memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
  785. return;
  786. } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
  787. unsigned ElementSize =
  788. getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
  789. for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
  790. InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
  791. return;
  792. } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
  793. const StructLayout *SL =
  794. getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
  795. for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
  796. InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
  797. return;
  798. } else if (Init->getType()->isFirstClassType()) {
  799. GenericValue Val = getConstantValue(Init);
  800. StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
  801. return;
  802. }
  803. cerr << "Bad Type: " << *Init->getType() << "\n";
  804. assert(0 && "Unknown constant type to initialize memory with!");
  805. }
  806. /// EmitGlobals - Emit all of the global variables to memory, storing their
  807. /// addresses into GlobalAddress. This must make sure to copy the contents of
  808. /// their initializers into the memory.
  809. ///
  810. void ExecutionEngine::emitGlobals() {
  811. // Loop over all of the global variables in the program, allocating the memory
  812. // to hold them. If there is more than one module, do a prepass over globals
  813. // to figure out how the different modules should link together.
  814. //
  815. std::map<std::pair<std::string, const Type*>,
  816. const GlobalValue*> LinkedGlobalsMap;
  817. if (Modules.size() != 1) {
  818. for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
  819. Module &M = *Modules[m]->getModule();
  820. for (Module::const_global_iterator I = M.global_begin(),
  821. E = M.global_end(); I != E; ++I) {
  822. const GlobalValue *GV = I;
  823. if (GV->hasLocalLinkage() || GV->isDeclaration() ||
  824. GV->hasAppendingLinkage() || !GV->hasName())
  825. continue;// Ignore external globals and globals with internal linkage.
  826. const GlobalValue *&GVEntry =
  827. LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
  828. // If this is the first time we've seen this global, it is the canonical
  829. // version.
  830. if (!GVEntry) {
  831. GVEntry = GV;
  832. continue;
  833. }
  834. // If the existing global is strong, never replace it.
  835. if (GVEntry->hasExternalLinkage() ||
  836. GVEntry->hasDLLImportLinkage() ||
  837. GVEntry->hasDLLExportLinkage())
  838. continue;
  839. // Otherwise, we know it's linkonce/weak, replace it if this is a strong
  840. // symbol. FIXME is this right for common?
  841. if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
  842. GVEntry = GV;
  843. }
  844. }
  845. }
  846. std::vector<const GlobalValue*> NonCanonicalGlobals;
  847. for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
  848. Module &M = *Modules[m]->getModule();
  849. for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
  850. I != E; ++I) {
  851. // In the multi-module case, see what this global maps to.
  852. if (!LinkedGlobalsMap.empty()) {
  853. if (const GlobalValue *GVEntry =
  854. LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
  855. // If something else is the canonical global, ignore this one.
  856. if (GVEntry != &*I) {
  857. NonCanonicalGlobals.push_back(I);
  858. continue;
  859. }
  860. }
  861. }
  862. if (!I->isDeclaration()) {
  863. addGlobalMapping(I, getMemoryForGV(I));
  864. } else {
  865. // External variable reference. Try to use the dynamic loader to
  866. // get a pointer to it.
  867. if (void *SymAddr =
  868. sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
  869. addGlobalMapping(I, SymAddr);
  870. else {
  871. llvm_report_error("Could not resolve external global address: "
  872. +I->getName());
  873. }
  874. }
  875. }
  876. // If there are multiple modules, map the non-canonical globals to their
  877. // canonical location.
  878. if (!NonCanonicalGlobals.empty()) {
  879. for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
  880. const GlobalValue *GV = NonCanonicalGlobals[i];
  881. const GlobalValue *CGV =
  882. LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
  883. void *Ptr = getPointerToGlobalIfAvailable(CGV);
  884. assert(Ptr && "Canonical global wasn't codegen'd!");
  885. addGlobalMapping(GV, Ptr);
  886. }
  887. }
  888. // Now that all of the globals are set up in memory, loop through them all
  889. // and initialize their contents.
  890. for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
  891. I != E; ++I) {
  892. if (!I->isDeclaration()) {
  893. if (!LinkedGlobalsMap.empty()) {
  894. if (const GlobalValue *GVEntry =
  895. LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
  896. if (GVEntry != &*I) // Not the canonical variable.
  897. continue;
  898. }
  899. EmitGlobalVariable(I);
  900. }
  901. }
  902. }
  903. }
  904. // EmitGlobalVariable - This method emits the specified global variable to the
  905. // address specified in GlobalAddresses, or allocates new memory if it's not
  906. // already in the map.
  907. void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
  908. void *GA = getPointerToGlobalIfAvailable(GV);
  909. if (GA == 0) {
  910. // If it's not already specified, allocate memory for the global.
  911. GA = getMemoryForGV(GV);
  912. addGlobalMapping(GV, GA);
  913. }
  914. // Don't initialize if it's thread local, let the client do it.
  915. if (!GV->isThreadLocal())
  916. InitializeMemory(GV->getInitializer(), GA);
  917. const Type *ElTy = GV->getType()->getElementType();
  918. size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
  919. NumInitBytes += (unsigned)GVSize;
  920. ++NumGlobals;
  921. }