JIT.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
  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 tool implements a just-in-time compiler for LLVM, allowing direct
  11. // execution of LLVM bitcode in an efficient manner.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "JIT.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/Function.h"
  18. #include "llvm/GlobalVariable.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/ModuleProvider.h"
  21. #include "llvm/CodeGen/JITCodeEmitter.h"
  22. #include "llvm/CodeGen/MachineCodeInfo.h"
  23. #include "llvm/ExecutionEngine/GenericValue.h"
  24. #include "llvm/ExecutionEngine/JITEventListener.h"
  25. #include "llvm/Target/TargetData.h"
  26. #include "llvm/Target/TargetMachine.h"
  27. #include "llvm/Target/TargetJITInfo.h"
  28. #include "llvm/Support/Dwarf.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/MutexGuard.h"
  31. #include "llvm/System/DynamicLibrary.h"
  32. #include "llvm/Config/config.h"
  33. using namespace llvm;
  34. #ifdef __APPLE__
  35. // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
  36. // of atexit). It passes the address of linker generated symbol __dso_handle
  37. // to the function.
  38. // This configuration change happened at version 5330.
  39. # include <AvailabilityMacros.h>
  40. # if defined(MAC_OS_X_VERSION_10_4) && \
  41. ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
  42. (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
  43. __APPLE_CC__ >= 5330))
  44. # ifndef HAVE___DSO_HANDLE
  45. # define HAVE___DSO_HANDLE 1
  46. # endif
  47. # endif
  48. #endif
  49. #if HAVE___DSO_HANDLE
  50. extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
  51. #endif
  52. namespace {
  53. static struct RegisterJIT {
  54. RegisterJIT() { JIT::Register(); }
  55. } JITRegistrator;
  56. }
  57. extern "C" void LLVMLinkInJIT() {
  58. }
  59. #if defined(__GNUC__) && !defined(__ARM__EABI__)
  60. // libgcc defines the __register_frame function to dynamically register new
  61. // dwarf frames for exception handling. This functionality is not portable
  62. // across compilers and is only provided by GCC. We use the __register_frame
  63. // function here so that code generated by the JIT cooperates with the unwinding
  64. // runtime of libgcc. When JITting with exception handling enable, LLVM
  65. // generates dwarf frames and registers it to libgcc with __register_frame.
  66. //
  67. // The __register_frame function works with Linux.
  68. //
  69. // Unfortunately, this functionality seems to be in libgcc after the unwinding
  70. // library of libgcc for darwin was written. The code for darwin overwrites the
  71. // value updated by __register_frame with a value fetched with "keymgr".
  72. // "keymgr" is an obsolete functionality, which should be rewritten some day.
  73. // In the meantime, since "keymgr" is on all libgccs shipped with apple-gcc, we
  74. // need a workaround in LLVM which uses the "keymgr" to dynamically modify the
  75. // values of an opaque key, used by libgcc to find dwarf tables.
  76. extern "C" void __register_frame(void*);
  77. #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
  78. # define USE_KEYMGR 1
  79. #else
  80. # define USE_KEYMGR 0
  81. #endif
  82. #if USE_KEYMGR
  83. namespace {
  84. // LibgccObject - This is the structure defined in libgcc. There is no #include
  85. // provided for this structure, so we also define it here. libgcc calls it
  86. // "struct object". The structure is undocumented in libgcc.
  87. struct LibgccObject {
  88. void *unused1;
  89. void *unused2;
  90. void *unused3;
  91. /// frame - Pointer to the exception table.
  92. void *frame;
  93. /// encoding - The encoding of the object?
  94. union {
  95. struct {
  96. unsigned long sorted : 1;
  97. unsigned long from_array : 1;
  98. unsigned long mixed_encoding : 1;
  99. unsigned long encoding : 8;
  100. unsigned long count : 21;
  101. } b;
  102. size_t i;
  103. } encoding;
  104. /// fde_end - libgcc defines this field only if some macro is defined. We
  105. /// include this field even if it may not there, to make libgcc happy.
  106. char *fde_end;
  107. /// next - At least we know it's a chained list!
  108. struct LibgccObject *next;
  109. };
  110. // "kemgr" stuff. Apparently, all frame tables are stored there.
  111. extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
  112. extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
  113. #define KEYMGR_GCC3_DW2_OBJ_LIST 302 /* Dwarf2 object list */
  114. /// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
  115. /// probably contains all dwarf tables that are loaded.
  116. struct LibgccObjectInfo {
  117. /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
  118. ///
  119. struct LibgccObject* seenObjects;
  120. /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
  121. ///
  122. struct LibgccObject* unseenObjects;
  123. unsigned unused[2];
  124. };
  125. /// darwin_register_frame - Since __register_frame does not work with darwin's
  126. /// libgcc,we provide our own function, which "tricks" libgcc by modifying the
  127. /// "Dwarf2 object list" key.
  128. void DarwinRegisterFrame(void* FrameBegin) {
  129. // Get the key.
  130. LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
  131. _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
  132. assert(LOI && "This should be preallocated by the runtime");
  133. // Allocate a new LibgccObject to represent this frame. Deallocation of this
  134. // object may be impossible: since darwin code in libgcc was written after
  135. // the ability to dynamically register frames, things may crash if we
  136. // deallocate it.
  137. struct LibgccObject* ob = (struct LibgccObject*)
  138. malloc(sizeof(struct LibgccObject));
  139. // Do like libgcc for the values of the field.
  140. ob->unused1 = (void *)-1;
  141. ob->unused2 = 0;
  142. ob->unused3 = 0;
  143. ob->frame = FrameBegin;
  144. ob->encoding.i = 0;
  145. ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
  146. // Put the info on both places, as libgcc uses the first or the the second
  147. // field. Note that we rely on having two pointers here. If fde_end was a
  148. // char, things would get complicated.
  149. ob->fde_end = (char*)LOI->unseenObjects;
  150. ob->next = LOI->unseenObjects;
  151. // Update the key's unseenObjects list.
  152. LOI->unseenObjects = ob;
  153. // Finally update the "key". Apparently, libgcc requires it.
  154. _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
  155. LOI);
  156. }
  157. }
  158. #endif // __APPLE__
  159. #endif // __GNUC__
  160. /// createJIT - This is the factory method for creating a JIT for the current
  161. /// machine, it does not fall back to the interpreter. This takes ownership
  162. /// of the module provider.
  163. ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
  164. std::string *ErrorStr,
  165. JITMemoryManager *JMM,
  166. CodeGenOpt::Level OptLevel,
  167. bool GVsWithCode) {
  168. ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, OptLevel,
  169. GVsWithCode);
  170. if (!EE) return 0;
  171. // Make sure we can resolve symbols in the program as well. The zero arg
  172. // to the function tells DynamicLibrary to load the program, not a library.
  173. sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
  174. return EE;
  175. }
  176. JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
  177. JITMemoryManager *JMM, CodeGenOpt::Level OptLevel, bool GVsWithCode)
  178. : ExecutionEngine(MP), TM(tm), TJI(tji), AllocateGVsWithCode(GVsWithCode) {
  179. setTargetData(TM.getTargetData());
  180. jitstate = new JITState(MP);
  181. // Initialize JCE
  182. JCE = createEmitter(*this, JMM);
  183. // Add target data
  184. MutexGuard locked(lock);
  185. FunctionPassManager &PM = jitstate->getPM(locked);
  186. PM.add(new TargetData(*TM.getTargetData()));
  187. // Turn the machine code intermediate representation into bytes in memory that
  188. // may be executed.
  189. if (TM.addPassesToEmitMachineCode(PM, *JCE, OptLevel)) {
  190. llvm_report_error("Target does not support machine code emission!");
  191. }
  192. // Register routine for informing unwinding runtime about new EH frames
  193. #if defined(__GNUC__) && !defined(__ARM_EABI__)
  194. #if USE_KEYMGR
  195. struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
  196. _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
  197. // The key is created on demand, and libgcc creates it the first time an
  198. // exception occurs. Since we need the key to register frames, we create
  199. // it now.
  200. if (!LOI)
  201. LOI = (LibgccObjectInfo*)calloc(sizeof(struct LibgccObjectInfo), 1);
  202. _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST, LOI);
  203. InstallExceptionTableRegister(DarwinRegisterFrame);
  204. #else
  205. InstallExceptionTableRegister(__register_frame);
  206. #endif // __APPLE__
  207. #endif // __GNUC__
  208. // Initialize passes.
  209. PM.doInitialization();
  210. }
  211. JIT::~JIT() {
  212. delete jitstate;
  213. delete JCE;
  214. delete &TM;
  215. }
  216. /// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
  217. /// removed the last ModuleProvider, we need re-initialize jitstate with a valid
  218. /// ModuleProvider.
  219. void JIT::addModuleProvider(ModuleProvider *MP) {
  220. MutexGuard locked(lock);
  221. if (Modules.empty()) {
  222. assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
  223. jitstate = new JITState(MP);
  224. FunctionPassManager &PM = jitstate->getPM(locked);
  225. PM.add(new TargetData(*TM.getTargetData()));
  226. // Turn the machine code intermediate representation into bytes in memory
  227. // that may be executed.
  228. if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
  229. llvm_report_error("Target does not support machine code emission!");
  230. }
  231. // Initialize passes.
  232. PM.doInitialization();
  233. }
  234. ExecutionEngine::addModuleProvider(MP);
  235. }
  236. /// removeModuleProvider - If we are removing the last ModuleProvider,
  237. /// invalidate the jitstate since the PassManager it contains references a
  238. /// released ModuleProvider.
  239. Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
  240. Module *result = ExecutionEngine::removeModuleProvider(MP, E);
  241. MutexGuard locked(lock);
  242. if (jitstate->getMP() == MP) {
  243. delete jitstate;
  244. jitstate = 0;
  245. }
  246. if (!jitstate && !Modules.empty()) {
  247. jitstate = new JITState(Modules[0]);
  248. FunctionPassManager &PM = jitstate->getPM(locked);
  249. PM.add(new TargetData(*TM.getTargetData()));
  250. // Turn the machine code intermediate representation into bytes in memory
  251. // that may be executed.
  252. if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
  253. llvm_report_error("Target does not support machine code emission!");
  254. }
  255. // Initialize passes.
  256. PM.doInitialization();
  257. }
  258. return result;
  259. }
  260. /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
  261. /// and deletes the ModuleProvider and owned Module. Avoids materializing
  262. /// the underlying module.
  263. void JIT::deleteModuleProvider(ModuleProvider *MP, std::string *E) {
  264. ExecutionEngine::deleteModuleProvider(MP, E);
  265. MutexGuard locked(lock);
  266. if (jitstate->getMP() == MP) {
  267. delete jitstate;
  268. jitstate = 0;
  269. }
  270. if (!jitstate && !Modules.empty()) {
  271. jitstate = new JITState(Modules[0]);
  272. FunctionPassManager &PM = jitstate->getPM(locked);
  273. PM.add(new TargetData(*TM.getTargetData()));
  274. // Turn the machine code intermediate representation into bytes in memory
  275. // that may be executed.
  276. if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
  277. llvm_report_error("Target does not support machine code emission!");
  278. }
  279. // Initialize passes.
  280. PM.doInitialization();
  281. }
  282. }
  283. /// run - Start execution with the specified function and arguments.
  284. ///
  285. GenericValue JIT::runFunction(Function *F,
  286. const std::vector<GenericValue> &ArgValues) {
  287. assert(F && "Function *F was null at entry to run()");
  288. void *FPtr = getPointerToFunction(F);
  289. assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
  290. const FunctionType *FTy = F->getFunctionType();
  291. const Type *RetTy = FTy->getReturnType();
  292. assert((FTy->getNumParams() == ArgValues.size() ||
  293. (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
  294. "Wrong number of arguments passed into function!");
  295. assert(FTy->getNumParams() == ArgValues.size() &&
  296. "This doesn't support passing arguments through varargs (yet)!");
  297. // Handle some common cases first. These cases correspond to common `main'
  298. // prototypes.
  299. if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
  300. switch (ArgValues.size()) {
  301. case 3:
  302. if (FTy->getParamType(0) == Type::Int32Ty &&
  303. isa<PointerType>(FTy->getParamType(1)) &&
  304. isa<PointerType>(FTy->getParamType(2))) {
  305. int (*PF)(int, char **, const char **) =
  306. (int(*)(int, char **, const char **))(intptr_t)FPtr;
  307. // Call the function.
  308. GenericValue rv;
  309. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
  310. (char **)GVTOP(ArgValues[1]),
  311. (const char **)GVTOP(ArgValues[2])));
  312. return rv;
  313. }
  314. break;
  315. case 2:
  316. if (FTy->getParamType(0) == Type::Int32Ty &&
  317. isa<PointerType>(FTy->getParamType(1))) {
  318. int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
  319. // Call the function.
  320. GenericValue rv;
  321. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
  322. (char **)GVTOP(ArgValues[1])));
  323. return rv;
  324. }
  325. break;
  326. case 1:
  327. if (FTy->getNumParams() == 1 &&
  328. FTy->getParamType(0) == Type::Int32Ty) {
  329. GenericValue rv;
  330. int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
  331. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
  332. return rv;
  333. }
  334. break;
  335. }
  336. }
  337. // Handle cases where no arguments are passed first.
  338. if (ArgValues.empty()) {
  339. GenericValue rv;
  340. switch (RetTy->getTypeID()) {
  341. default: LLVM_UNREACHABLE("Unknown return type for function call!");
  342. case Type::IntegerTyID: {
  343. unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
  344. if (BitWidth == 1)
  345. rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
  346. else if (BitWidth <= 8)
  347. rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
  348. else if (BitWidth <= 16)
  349. rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
  350. else if (BitWidth <= 32)
  351. rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
  352. else if (BitWidth <= 64)
  353. rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
  354. else
  355. LLVM_UNREACHABLE("Integer types > 64 bits not supported");
  356. return rv;
  357. }
  358. case Type::VoidTyID:
  359. rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
  360. return rv;
  361. case Type::FloatTyID:
  362. rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
  363. return rv;
  364. case Type::DoubleTyID:
  365. rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
  366. return rv;
  367. case Type::X86_FP80TyID:
  368. case Type::FP128TyID:
  369. case Type::PPC_FP128TyID:
  370. LLVM_UNREACHABLE("long double not supported yet");
  371. return rv;
  372. case Type::PointerTyID:
  373. return PTOGV(((void*(*)())(intptr_t)FPtr)());
  374. }
  375. }
  376. // Okay, this is not one of our quick and easy cases. Because we don't have a
  377. // full FFI, we have to codegen a nullary stub function that just calls the
  378. // function we are interested in, passing in constants for all of the
  379. // arguments. Make this function and return.
  380. // First, create the function.
  381. FunctionType *STy=FunctionType::get(RetTy, false);
  382. Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
  383. F->getParent());
  384. // Insert a basic block.
  385. BasicBlock *StubBB = BasicBlock::Create("", Stub);
  386. // Convert all of the GenericValue arguments over to constants. Note that we
  387. // currently don't support varargs.
  388. SmallVector<Value*, 8> Args;
  389. for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
  390. Constant *C = 0;
  391. const Type *ArgTy = FTy->getParamType(i);
  392. const GenericValue &AV = ArgValues[i];
  393. switch (ArgTy->getTypeID()) {
  394. default: LLVM_UNREACHABLE("Unknown argument type for function call!");
  395. case Type::IntegerTyID:
  396. C = ConstantInt::get(AV.IntVal);
  397. break;
  398. case Type::FloatTyID:
  399. C = ConstantFP::get(APFloat(AV.FloatVal));
  400. break;
  401. case Type::DoubleTyID:
  402. C = ConstantFP::get(APFloat(AV.DoubleVal));
  403. break;
  404. case Type::PPC_FP128TyID:
  405. case Type::X86_FP80TyID:
  406. case Type::FP128TyID:
  407. C = ConstantFP::get(APFloat(AV.IntVal));
  408. break;
  409. case Type::PointerTyID:
  410. void *ArgPtr = GVTOP(AV);
  411. if (sizeof(void*) == 4)
  412. C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
  413. else
  414. C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
  415. C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
  416. break;
  417. }
  418. Args.push_back(C);
  419. }
  420. CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
  421. "", StubBB);
  422. TheCall->setCallingConv(F->getCallingConv());
  423. TheCall->setTailCall();
  424. if (TheCall->getType() != Type::VoidTy)
  425. ReturnInst::Create(TheCall, StubBB); // Return result of the call.
  426. else
  427. ReturnInst::Create(StubBB); // Just return void.
  428. // Finally, return the value returned by our nullary stub function.
  429. return runFunction(Stub, std::vector<GenericValue>());
  430. }
  431. void JIT::RegisterJITEventListener(JITEventListener *L) {
  432. if (L == NULL)
  433. return;
  434. MutexGuard locked(lock);
  435. EventListeners.push_back(L);
  436. }
  437. void JIT::UnregisterJITEventListener(JITEventListener *L) {
  438. if (L == NULL)
  439. return;
  440. MutexGuard locked(lock);
  441. std::vector<JITEventListener*>::reverse_iterator I=
  442. std::find(EventListeners.rbegin(), EventListeners.rend(), L);
  443. if (I != EventListeners.rend()) {
  444. std::swap(*I, EventListeners.back());
  445. EventListeners.pop_back();
  446. }
  447. }
  448. void JIT::NotifyFunctionEmitted(
  449. const Function &F,
  450. void *Code, size_t Size,
  451. const JITEvent_EmittedFunctionDetails &Details) {
  452. MutexGuard locked(lock);
  453. for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
  454. EventListeners[I]->NotifyFunctionEmitted(F, Code, Size, Details);
  455. }
  456. }
  457. void JIT::NotifyFreeingMachineCode(const Function &F, void *OldPtr) {
  458. MutexGuard locked(lock);
  459. for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
  460. EventListeners[I]->NotifyFreeingMachineCode(F, OldPtr);
  461. }
  462. }
  463. /// runJITOnFunction - Run the FunctionPassManager full of
  464. /// just-in-time compilation passes on F, hopefully filling in
  465. /// GlobalAddress[F] with the address of F's machine code.
  466. ///
  467. void JIT::runJITOnFunction(Function *F, MachineCodeInfo *MCI) {
  468. MutexGuard locked(lock);
  469. class MCIListener : public JITEventListener {
  470. MachineCodeInfo *const MCI;
  471. public:
  472. MCIListener(MachineCodeInfo *mci) : MCI(mci) {}
  473. virtual void NotifyFunctionEmitted(const Function &,
  474. void *Code, size_t Size,
  475. const EmittedFunctionDetails &) {
  476. MCI->setAddress(Code);
  477. MCI->setSize(Size);
  478. }
  479. };
  480. MCIListener MCIL(MCI);
  481. RegisterJITEventListener(&MCIL);
  482. runJITOnFunctionUnlocked(F, locked);
  483. UnregisterJITEventListener(&MCIL);
  484. }
  485. void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
  486. static bool isAlreadyCodeGenerating = false;
  487. assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
  488. // JIT the function
  489. isAlreadyCodeGenerating = true;
  490. jitstate->getPM(locked).run(*F);
  491. isAlreadyCodeGenerating = false;
  492. // If the function referred to another function that had not yet been
  493. // read from bitcode, but we are jitting non-lazily, emit it now.
  494. while (!jitstate->getPendingFunctions(locked).empty()) {
  495. Function *PF = jitstate->getPendingFunctions(locked).back();
  496. jitstate->getPendingFunctions(locked).pop_back();
  497. // JIT the function
  498. isAlreadyCodeGenerating = true;
  499. jitstate->getPM(locked).run(*PF);
  500. isAlreadyCodeGenerating = false;
  501. // Now that the function has been jitted, ask the JITEmitter to rewrite
  502. // the stub with real address of the function.
  503. updateFunctionStub(PF);
  504. }
  505. // If the JIT is configured to emit info so that dlsym can be used to
  506. // rewrite stubs to external globals, do so now.
  507. if (areDlsymStubsEnabled() && isLazyCompilationDisabled())
  508. updateDlsymStubTable();
  509. }
  510. /// getPointerToFunction - This method is used to get the address of the
  511. /// specified function, compiling it if neccesary.
  512. ///
  513. void *JIT::getPointerToFunction(Function *F) {
  514. if (void *Addr = getPointerToGlobalIfAvailable(F))
  515. return Addr; // Check if function already code gen'd
  516. MutexGuard locked(lock);
  517. // Now that this thread owns the lock, check if another thread has already
  518. // code gen'd the function.
  519. if (void *Addr = getPointerToGlobalIfAvailable(F))
  520. return Addr;
  521. // Make sure we read in the function if it exists in this Module.
  522. if (F->hasNotBeenReadFromBitcode()) {
  523. // Determine the module provider this function is provided by.
  524. Module *M = F->getParent();
  525. ModuleProvider *MP = 0;
  526. for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
  527. if (Modules[i]->getModule() == M) {
  528. MP = Modules[i];
  529. break;
  530. }
  531. }
  532. assert(MP && "Function isn't in a module we know about!");
  533. std::string ErrorMsg;
  534. if (MP->materializeFunction(F, &ErrorMsg)) {
  535. llvm_report_error("Error reading function '" + F->getName()+
  536. "' from bitcode file: " + ErrorMsg);
  537. }
  538. // Now retry to get the address.
  539. if (void *Addr = getPointerToGlobalIfAvailable(F))
  540. return Addr;
  541. }
  542. if (F->isDeclaration()) {
  543. bool AbortOnFailure =
  544. !areDlsymStubsEnabled() && !F->hasExternalWeakLinkage();
  545. void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
  546. addGlobalMapping(F, Addr);
  547. return Addr;
  548. }
  549. runJITOnFunctionUnlocked(F, locked);
  550. void *Addr = getPointerToGlobalIfAvailable(F);
  551. assert(Addr && "Code generation didn't add function to GlobalAddress table!");
  552. return Addr;
  553. }
  554. /// getOrEmitGlobalVariable - Return the address of the specified global
  555. /// variable, possibly emitting it to memory if needed. This is used by the
  556. /// Emitter.
  557. void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
  558. MutexGuard locked(lock);
  559. void *Ptr = getPointerToGlobalIfAvailable(GV);
  560. if (Ptr) return Ptr;
  561. // If the global is external, just remember the address.
  562. if (GV->isDeclaration()) {
  563. #if HAVE___DSO_HANDLE
  564. if (GV->getName() == "__dso_handle")
  565. return (void*)&__dso_handle;
  566. #endif
  567. Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
  568. if (Ptr == 0 && !areDlsymStubsEnabled()) {
  569. llvm_report_error("Could not resolve external global address: "
  570. +GV->getName());
  571. }
  572. addGlobalMapping(GV, Ptr);
  573. } else {
  574. // If the global hasn't been emitted to memory yet, allocate space and
  575. // emit it into memory.
  576. Ptr = getMemoryForGV(GV);
  577. addGlobalMapping(GV, Ptr);
  578. EmitGlobalVariable(GV); // Initialize the variable.
  579. }
  580. return Ptr;
  581. }
  582. /// recompileAndRelinkFunction - This method is used to force a function
  583. /// which has already been compiled, to be compiled again, possibly
  584. /// after it has been modified. Then the entry to the old copy is overwritten
  585. /// with a branch to the new copy. If there was no old copy, this acts
  586. /// just like JIT::getPointerToFunction().
  587. ///
  588. void *JIT::recompileAndRelinkFunction(Function *F) {
  589. void *OldAddr = getPointerToGlobalIfAvailable(F);
  590. // If it's not already compiled there is no reason to patch it up.
  591. if (OldAddr == 0) { return getPointerToFunction(F); }
  592. // Delete the old function mapping.
  593. addGlobalMapping(F, 0);
  594. // Recodegen the function
  595. runJITOnFunction(F);
  596. // Update state, forward the old function to the new function.
  597. void *Addr = getPointerToGlobalIfAvailable(F);
  598. assert(Addr && "Code generation didn't add function to GlobalAddress table!");
  599. TJI.replaceMachineCodeForFunction(OldAddr, Addr);
  600. return Addr;
  601. }
  602. /// getMemoryForGV - This method abstracts memory allocation of global
  603. /// variable so that the JIT can allocate thread local variables depending
  604. /// on the target.
  605. ///
  606. char* JIT::getMemoryForGV(const GlobalVariable* GV) {
  607. char *Ptr;
  608. // GlobalVariable's which are not "constant" will cause trouble in a server
  609. // situation. It's returned in the same block of memory as code which may
  610. // not be writable.
  611. if (isGVCompilationDisabled() && !GV->isConstant()) {
  612. llvm_report_error("Compilation of non-internal GlobalValue is disabled!");
  613. }
  614. // Some applications require globals and code to live together, so they may
  615. // be allocated into the same buffer, but in general globals are allocated
  616. // through the memory manager which puts them near the code but not in the
  617. // same buffer.
  618. const Type *GlobalType = GV->getType()->getElementType();
  619. size_t S = getTargetData()->getTypeAllocSize(GlobalType);
  620. size_t A = getTargetData()->getPreferredAlignment(GV);
  621. if (GV->isThreadLocal()) {
  622. MutexGuard locked(lock);
  623. Ptr = TJI.allocateThreadLocalMemory(S);
  624. } else if (TJI.allocateSeparateGVMemory()) {
  625. if (A <= 8) {
  626. Ptr = (char*)malloc(S);
  627. } else {
  628. // Allocate S+A bytes of memory, then use an aligned pointer within that
  629. // space.
  630. Ptr = (char*)malloc(S+A);
  631. unsigned MisAligned = ((intptr_t)Ptr & (A-1));
  632. Ptr = Ptr + (MisAligned ? (A-MisAligned) : 0);
  633. }
  634. } else if (AllocateGVsWithCode) {
  635. Ptr = (char*)JCE->allocateSpace(S, A);
  636. } else {
  637. Ptr = (char*)JCE->allocateGlobal(S, A);
  638. }
  639. return Ptr;
  640. }
  641. void JIT::addPendingFunction(Function *F) {
  642. MutexGuard locked(lock);
  643. jitstate->getPendingFunctions(locked).push_back(F);
  644. }
  645. JITEventListener::~JITEventListener() {}