JIT.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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/ADT/SmallPtrSet.h"
  16. #include "llvm/CodeGen/JITCodeEmitter.h"
  17. #include "llvm/CodeGen/MachineCodeInfo.h"
  18. #include "llvm/Config/config.h"
  19. #include "llvm/ExecutionEngine/GenericValue.h"
  20. #include "llvm/ExecutionEngine/JITEventListener.h"
  21. #include "llvm/ExecutionEngine/JITMemoryManager.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/DerivedTypes.h"
  25. #include "llvm/IR/Function.h"
  26. #include "llvm/IR/GlobalVariable.h"
  27. #include "llvm/IR/Instructions.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/Support/Dwarf.h"
  30. #include "llvm/Support/DynamicLibrary.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/ManagedStatic.h"
  33. #include "llvm/Support/MutexGuard.h"
  34. #include "llvm/Target/TargetJITInfo.h"
  35. #include "llvm/Target/TargetMachine.h"
  36. using namespace llvm;
  37. #ifdef __APPLE__
  38. // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
  39. // of atexit). It passes the address of linker generated symbol __dso_handle
  40. // to the function.
  41. // This configuration change happened at version 5330.
  42. # include <AvailabilityMacros.h>
  43. # if defined(MAC_OS_X_VERSION_10_4) && \
  44. ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
  45. (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
  46. __APPLE_CC__ >= 5330))
  47. # ifndef HAVE___DSO_HANDLE
  48. # define HAVE___DSO_HANDLE 1
  49. # endif
  50. # endif
  51. #endif
  52. #if HAVE___DSO_HANDLE
  53. extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
  54. #endif
  55. namespace {
  56. static struct RegisterJIT {
  57. RegisterJIT() { JIT::Register(); }
  58. } JITRegistrator;
  59. }
  60. extern "C" void LLVMLinkInJIT() {
  61. }
  62. /// createJIT - This is the factory method for creating a JIT for the current
  63. /// machine, it does not fall back to the interpreter. This takes ownership
  64. /// of the module.
  65. ExecutionEngine *JIT::createJIT(Module *M,
  66. std::string *ErrorStr,
  67. JITMemoryManager *JMM,
  68. bool GVsWithCode,
  69. TargetMachine *TM) {
  70. // Try to register the program as a source of symbols to resolve against.
  71. //
  72. // FIXME: Don't do this here.
  73. sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
  74. // If the target supports JIT code generation, create the JIT.
  75. if (TargetJITInfo *TJ = TM->getJITInfo()) {
  76. return new JIT(M, *TM, *TJ, JMM, GVsWithCode);
  77. } else {
  78. if (ErrorStr)
  79. *ErrorStr = "target does not support JIT code generation";
  80. return nullptr;
  81. }
  82. }
  83. namespace {
  84. /// This class supports the global getPointerToNamedFunction(), which allows
  85. /// bugpoint or gdb users to search for a function by name without any context.
  86. class JitPool {
  87. SmallPtrSet<JIT*, 1> JITs; // Optimize for process containing just 1 JIT.
  88. mutable std::recursive_mutex Lock;
  89. public:
  90. void Add(JIT *jit) {
  91. std::lock_guard<std::recursive_mutex> guard(Lock);
  92. JITs.insert(jit);
  93. }
  94. void Remove(JIT *jit) {
  95. std::lock_guard<std::recursive_mutex> guard(Lock);
  96. JITs.erase(jit);
  97. }
  98. void *getPointerToNamedFunction(const char *Name) const {
  99. std::lock_guard<std::recursive_mutex> guard(Lock);
  100. assert(JITs.size() != 0 && "No Jit registered");
  101. //search function in every instance of JIT
  102. for (SmallPtrSet<JIT*, 1>::const_iterator Jit = JITs.begin(),
  103. end = JITs.end();
  104. Jit != end; ++Jit) {
  105. if (Function *F = (*Jit)->FindFunctionNamed(Name))
  106. return (*Jit)->getPointerToFunction(F);
  107. }
  108. // The function is not available : fallback on the first created (will
  109. // search in symbol of the current program/library)
  110. return (*JITs.begin())->getPointerToNamedFunction(Name);
  111. }
  112. };
  113. ManagedStatic<JitPool> AllJits;
  114. }
  115. extern "C" {
  116. // getPointerToNamedFunction - This function is used as a global wrapper to
  117. // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
  118. // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
  119. // need to resolve function(s) that are being mis-codegenerated, so we need to
  120. // resolve their addresses at runtime, and this is the way to do it.
  121. void *getPointerToNamedFunction(const char *Name) {
  122. return AllJits->getPointerToNamedFunction(Name);
  123. }
  124. }
  125. JIT::JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
  126. JITMemoryManager *jmm, bool GVsWithCode)
  127. : ExecutionEngine(M), TM(tm), TJI(tji),
  128. JMM(jmm ? jmm : JITMemoryManager::CreateDefaultMemManager()),
  129. AllocateGVsWithCode(GVsWithCode), isAlreadyCodeGenerating(false) {
  130. setDataLayout(TM.getDataLayout());
  131. jitstate = new JITState(M);
  132. // Initialize JCE
  133. JCE = createEmitter(*this, JMM, TM);
  134. // Register in global list of all JITs.
  135. AllJits->Add(this);
  136. // Add target data
  137. std::lock_guard<std::recursive_mutex> locked(lock);
  138. FunctionPassManager &PM = jitstate->getPM();
  139. M->setDataLayout(TM.getDataLayout());
  140. PM.add(new DataLayoutPass(M));
  141. // Turn the machine code intermediate representation into bytes in memory that
  142. // may be executed.
  143. if (TM.addPassesToEmitMachineCode(PM, *JCE, !getVerifyModules())) {
  144. report_fatal_error("Target does not support machine code emission!");
  145. }
  146. // Initialize passes.
  147. PM.doInitialization();
  148. }
  149. JIT::~JIT() {
  150. // Cleanup.
  151. AllJits->Remove(this);
  152. delete jitstate;
  153. delete JCE;
  154. // JMM is a ownership of JCE, so we no need delete JMM here.
  155. delete &TM;
  156. }
  157. /// addModule - Add a new Module to the JIT. If we previously removed the last
  158. /// Module, we need re-initialize jitstate with a valid Module.
  159. void JIT::addModule(Module *M) {
  160. std::lock_guard<std::recursive_mutex> locked(lock);
  161. if (Modules.empty()) {
  162. assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
  163. jitstate = new JITState(M);
  164. FunctionPassManager &PM = jitstate->getPM();
  165. M->setDataLayout(TM.getDataLayout());
  166. PM.add(new DataLayoutPass(M));
  167. // Turn the machine code intermediate representation into bytes in memory
  168. // that may be executed.
  169. if (TM.addPassesToEmitMachineCode(PM, *JCE, !getVerifyModules())) {
  170. report_fatal_error("Target does not support machine code emission!");
  171. }
  172. // Initialize passes.
  173. PM.doInitialization();
  174. }
  175. ExecutionEngine::addModule(M);
  176. }
  177. /// removeModule - If we are removing the last Module, invalidate the jitstate
  178. /// since the PassManager it contains references a released Module.
  179. bool JIT::removeModule(Module *M) {
  180. bool result = ExecutionEngine::removeModule(M);
  181. std::lock_guard<std::recursive_mutex> locked(lock);
  182. if (jitstate && jitstate->getModule() == M) {
  183. delete jitstate;
  184. jitstate = nullptr;
  185. }
  186. if (!jitstate && !Modules.empty()) {
  187. jitstate = new JITState(Modules[0]);
  188. FunctionPassManager &PM = jitstate->getPM();
  189. M->setDataLayout(TM.getDataLayout());
  190. PM.add(new DataLayoutPass(M));
  191. // Turn the machine code intermediate representation into bytes in memory
  192. // that may be executed.
  193. if (TM.addPassesToEmitMachineCode(PM, *JCE, !getVerifyModules())) {
  194. report_fatal_error("Target does not support machine code emission!");
  195. }
  196. // Initialize passes.
  197. PM.doInitialization();
  198. }
  199. return result;
  200. }
  201. /// run - Start execution with the specified function and arguments.
  202. ///
  203. GenericValue JIT::runFunction(Function *F,
  204. const std::vector<GenericValue> &ArgValues) {
  205. assert(F && "Function *F was null at entry to run()");
  206. void *FPtr = getPointerToFunction(F);
  207. assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
  208. FunctionType *FTy = F->getFunctionType();
  209. Type *RetTy = FTy->getReturnType();
  210. assert((FTy->getNumParams() == ArgValues.size() ||
  211. (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
  212. "Wrong number of arguments passed into function!");
  213. assert(FTy->getNumParams() == ArgValues.size() &&
  214. "This doesn't support passing arguments through varargs (yet)!");
  215. // Handle some common cases first. These cases correspond to common `main'
  216. // prototypes.
  217. if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
  218. switch (ArgValues.size()) {
  219. case 3:
  220. if (FTy->getParamType(0)->isIntegerTy(32) &&
  221. FTy->getParamType(1)->isPointerTy() &&
  222. FTy->getParamType(2)->isPointerTy()) {
  223. int (*PF)(int, char **, const char **) =
  224. (int(*)(int, char **, const char **))(intptr_t)FPtr;
  225. // Call the function.
  226. GenericValue rv;
  227. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
  228. (char **)GVTOP(ArgValues[1]),
  229. (const char **)GVTOP(ArgValues[2])));
  230. return rv;
  231. }
  232. break;
  233. case 2:
  234. if (FTy->getParamType(0)->isIntegerTy(32) &&
  235. FTy->getParamType(1)->isPointerTy()) {
  236. int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
  237. // Call the function.
  238. GenericValue rv;
  239. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
  240. (char **)GVTOP(ArgValues[1])));
  241. return rv;
  242. }
  243. break;
  244. case 1:
  245. if (FTy->getParamType(0)->isIntegerTy(32)) {
  246. GenericValue rv;
  247. int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
  248. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
  249. return rv;
  250. }
  251. if (FTy->getParamType(0)->isPointerTy()) {
  252. GenericValue rv;
  253. int (*PF)(char *) = (int(*)(char *))(intptr_t)FPtr;
  254. rv.IntVal = APInt(32, PF((char*)GVTOP(ArgValues[0])));
  255. return rv;
  256. }
  257. break;
  258. }
  259. }
  260. // Handle cases where no arguments are passed first.
  261. if (ArgValues.empty()) {
  262. GenericValue rv;
  263. switch (RetTy->getTypeID()) {
  264. default: llvm_unreachable("Unknown return type for function call!");
  265. case Type::IntegerTyID: {
  266. unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
  267. if (BitWidth == 1)
  268. rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
  269. else if (BitWidth <= 8)
  270. rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
  271. else if (BitWidth <= 16)
  272. rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
  273. else if (BitWidth <= 32)
  274. rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
  275. else if (BitWidth <= 64)
  276. rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
  277. else
  278. llvm_unreachable("Integer types > 64 bits not supported");
  279. return rv;
  280. }
  281. case Type::VoidTyID:
  282. rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
  283. return rv;
  284. case Type::FloatTyID:
  285. rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
  286. return rv;
  287. case Type::DoubleTyID:
  288. rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
  289. return rv;
  290. case Type::X86_FP80TyID:
  291. case Type::FP128TyID:
  292. case Type::PPC_FP128TyID:
  293. llvm_unreachable("long double not supported yet");
  294. case Type::PointerTyID:
  295. return PTOGV(((void*(*)())(intptr_t)FPtr)());
  296. }
  297. }
  298. // Okay, this is not one of our quick and easy cases. Because we don't have a
  299. // full FFI, we have to codegen a nullary stub function that just calls the
  300. // function we are interested in, passing in constants for all of the
  301. // arguments. Make this function and return.
  302. // First, create the function.
  303. FunctionType *STy=FunctionType::get(RetTy, false);
  304. Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
  305. F->getParent());
  306. // Insert a basic block.
  307. BasicBlock *StubBB = BasicBlock::Create(F->getContext(), "", Stub);
  308. // Convert all of the GenericValue arguments over to constants. Note that we
  309. // currently don't support varargs.
  310. SmallVector<Value*, 8> Args;
  311. for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
  312. Constant *C = nullptr;
  313. Type *ArgTy = FTy->getParamType(i);
  314. const GenericValue &AV = ArgValues[i];
  315. switch (ArgTy->getTypeID()) {
  316. default: llvm_unreachable("Unknown argument type for function call!");
  317. case Type::IntegerTyID:
  318. C = ConstantInt::get(F->getContext(), AV.IntVal);
  319. break;
  320. case Type::FloatTyID:
  321. C = ConstantFP::get(F->getContext(), APFloat(AV.FloatVal));
  322. break;
  323. case Type::DoubleTyID:
  324. C = ConstantFP::get(F->getContext(), APFloat(AV.DoubleVal));
  325. break;
  326. case Type::PPC_FP128TyID:
  327. case Type::X86_FP80TyID:
  328. case Type::FP128TyID:
  329. C = ConstantFP::get(F->getContext(), APFloat(ArgTy->getFltSemantics(),
  330. AV.IntVal));
  331. break;
  332. case Type::PointerTyID:
  333. void *ArgPtr = GVTOP(AV);
  334. if (sizeof(void*) == 4)
  335. C = ConstantInt::get(Type::getInt32Ty(F->getContext()),
  336. (int)(intptr_t)ArgPtr);
  337. else
  338. C = ConstantInt::get(Type::getInt64Ty(F->getContext()),
  339. (intptr_t)ArgPtr);
  340. // Cast the integer to pointer
  341. C = ConstantExpr::getIntToPtr(C, ArgTy);
  342. break;
  343. }
  344. Args.push_back(C);
  345. }
  346. CallInst *TheCall = CallInst::Create(F, Args, "", StubBB);
  347. TheCall->setCallingConv(F->getCallingConv());
  348. TheCall->setTailCall();
  349. if (!TheCall->getType()->isVoidTy())
  350. // Return result of the call.
  351. ReturnInst::Create(F->getContext(), TheCall, StubBB);
  352. else
  353. ReturnInst::Create(F->getContext(), StubBB); // Just return void.
  354. // Finally, call our nullary stub function.
  355. GenericValue Result = runFunction(Stub, std::vector<GenericValue>());
  356. // Erase it, since no other function can have a reference to it.
  357. Stub->eraseFromParent();
  358. // And return the result.
  359. return Result;
  360. }
  361. void JIT::RegisterJITEventListener(JITEventListener *L) {
  362. if (!L)
  363. return;
  364. std::lock_guard<std::recursive_mutex> locked(lock);
  365. EventListeners.push_back(L);
  366. }
  367. void JIT::UnregisterJITEventListener(JITEventListener *L) {
  368. if (!L)
  369. return;
  370. std::lock_guard<std::recursive_mutex> locked(lock);
  371. std::vector<JITEventListener*>::reverse_iterator I=
  372. std::find(EventListeners.rbegin(), EventListeners.rend(), L);
  373. if (I != EventListeners.rend()) {
  374. std::swap(*I, EventListeners.back());
  375. EventListeners.pop_back();
  376. }
  377. }
  378. void JIT::NotifyFunctionEmitted(
  379. const Function &F,
  380. void *Code, size_t Size,
  381. const JITEvent_EmittedFunctionDetails &Details) {
  382. std::lock_guard<std::recursive_mutex> locked(lock);
  383. for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
  384. EventListeners[I]->NotifyFunctionEmitted(F, Code, Size, Details);
  385. }
  386. }
  387. void JIT::NotifyFreeingMachineCode(void *OldPtr) {
  388. std::lock_guard<std::recursive_mutex> locked(lock);
  389. for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
  390. EventListeners[I]->NotifyFreeingMachineCode(OldPtr);
  391. }
  392. }
  393. /// runJITOnFunction - Run the FunctionPassManager full of
  394. /// just-in-time compilation passes on F, hopefully filling in
  395. /// GlobalAddress[F] with the address of F's machine code.
  396. ///
  397. void JIT::runJITOnFunction(Function *F, MachineCodeInfo *MCI) {
  398. std::lock_guard<std::recursive_mutex> locked(lock);
  399. class MCIListener : public JITEventListener {
  400. MachineCodeInfo *const MCI;
  401. public:
  402. MCIListener(MachineCodeInfo *mci) : MCI(mci) {}
  403. void NotifyFunctionEmitted(const Function &, void *Code, size_t Size,
  404. const EmittedFunctionDetails &) override {
  405. MCI->setAddress(Code);
  406. MCI->setSize(Size);
  407. }
  408. };
  409. MCIListener MCIL(MCI);
  410. if (MCI)
  411. RegisterJITEventListener(&MCIL);
  412. runJITOnFunctionUnlocked(F);
  413. if (MCI)
  414. UnregisterJITEventListener(&MCIL);
  415. }
  416. void JIT::runJITOnFunctionUnlocked(Function *F) {
  417. assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
  418. jitTheFunctionUnlocked(F);
  419. // If the function referred to another function that had not yet been
  420. // read from bitcode, and we are jitting non-lazily, emit it now.
  421. while (!jitstate->getPendingFunctions().empty()) {
  422. Function *PF = jitstate->getPendingFunctions().back();
  423. jitstate->getPendingFunctions().pop_back();
  424. assert(!PF->hasAvailableExternallyLinkage() &&
  425. "Externally-defined function should not be in pending list.");
  426. jitTheFunctionUnlocked(PF);
  427. // Now that the function has been jitted, ask the JITEmitter to rewrite
  428. // the stub with real address of the function.
  429. updateFunctionStubUnlocked(PF);
  430. }
  431. }
  432. void JIT::jitTheFunctionUnlocked(Function *F) {
  433. isAlreadyCodeGenerating = true;
  434. jitstate->getPM().run(*F);
  435. isAlreadyCodeGenerating = false;
  436. // clear basic block addresses after this function is done
  437. getBasicBlockAddressMap().clear();
  438. }
  439. /// getPointerToFunction - This method is used to get the address of the
  440. /// specified function, compiling it if necessary.
  441. ///
  442. void *JIT::getPointerToFunction(Function *F) {
  443. if (void *Addr = getPointerToGlobalIfAvailable(F))
  444. return Addr; // Check if function already code gen'd
  445. std::lock_guard<std::recursive_mutex> locked(lock);
  446. // Now that this thread owns the lock, make sure we read in the function if it
  447. // exists in this Module.
  448. std::string ErrorMsg;
  449. if (F->Materialize(&ErrorMsg)) {
  450. report_fatal_error("Error reading function '" + F->getName()+
  451. "' from bitcode file: " + ErrorMsg);
  452. }
  453. // ... and check if another thread has already code gen'd the function.
  454. if (void *Addr = getPointerToGlobalIfAvailable(F))
  455. return Addr;
  456. if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
  457. bool AbortOnFailure = !F->hasExternalWeakLinkage();
  458. void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
  459. addGlobalMapping(F, Addr);
  460. return Addr;
  461. }
  462. runJITOnFunctionUnlocked(F);
  463. void *Addr = getPointerToGlobalIfAvailable(F);
  464. assert(Addr && "Code generation didn't add function to GlobalAddress table!");
  465. return Addr;
  466. }
  467. void JIT::addPointerToBasicBlock(const BasicBlock *BB, void *Addr) {
  468. std::lock_guard<std::recursive_mutex> locked(lock);
  469. BasicBlockAddressMapTy::iterator I =
  470. getBasicBlockAddressMap().find(BB);
  471. if (I == getBasicBlockAddressMap().end()) {
  472. getBasicBlockAddressMap()[BB] = Addr;
  473. } else {
  474. // ignore repeats: some BBs can be split into few MBBs?
  475. }
  476. }
  477. void JIT::clearPointerToBasicBlock(const BasicBlock *BB) {
  478. std::lock_guard<std::recursive_mutex> locked(lock);
  479. getBasicBlockAddressMap().erase(BB);
  480. }
  481. void *JIT::getPointerToBasicBlock(BasicBlock *BB) {
  482. // make sure it's function is compiled by JIT
  483. (void)getPointerToFunction(BB->getParent());
  484. // resolve basic block address
  485. std::lock_guard<std::recursive_mutex> locked(lock);
  486. BasicBlockAddressMapTy::iterator I =
  487. getBasicBlockAddressMap().find(BB);
  488. if (I != getBasicBlockAddressMap().end()) {
  489. return I->second;
  490. } else {
  491. llvm_unreachable("JIT does not have BB address for address-of-label, was"
  492. " it eliminated by optimizer?");
  493. }
  494. }
  495. void *JIT::getPointerToNamedFunction(const std::string &Name,
  496. bool AbortOnFailure){
  497. if (!isSymbolSearchingDisabled()) {
  498. void *ptr = JMM->getPointerToNamedFunction(Name, false);
  499. if (ptr)
  500. return ptr;
  501. }
  502. /// If a LazyFunctionCreator is installed, use it to get/create the function.
  503. if (LazyFunctionCreator)
  504. if (void *RP = LazyFunctionCreator(Name))
  505. return RP;
  506. if (AbortOnFailure) {
  507. report_fatal_error("Program used external function '"+Name+
  508. "' which could not be resolved!");
  509. }
  510. return nullptr;
  511. }
  512. /// getOrEmitGlobalVariable - Return the address of the specified global
  513. /// variable, possibly emitting it to memory if needed. This is used by the
  514. /// Emitter.
  515. void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
  516. std::lock_guard<std::recursive_mutex> locked(lock);
  517. void *Ptr = getPointerToGlobalIfAvailable(GV);
  518. if (Ptr) return Ptr;
  519. // If the global is external, just remember the address.
  520. if (GV->isDeclaration() || GV->hasAvailableExternallyLinkage()) {
  521. #if HAVE___DSO_HANDLE
  522. if (GV->getName() == "__dso_handle")
  523. return (void*)&__dso_handle;
  524. #endif
  525. Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName());
  526. if (!Ptr) {
  527. report_fatal_error("Could not resolve external global address: "
  528. +GV->getName());
  529. }
  530. addGlobalMapping(GV, Ptr);
  531. } else {
  532. // If the global hasn't been emitted to memory yet, allocate space and
  533. // emit it into memory.
  534. Ptr = getMemoryForGV(GV);
  535. addGlobalMapping(GV, Ptr);
  536. EmitGlobalVariable(GV); // Initialize the variable.
  537. }
  538. return Ptr;
  539. }
  540. /// recompileAndRelinkFunction - This method is used to force a function
  541. /// which has already been compiled, to be compiled again, possibly
  542. /// after it has been modified. Then the entry to the old copy is overwritten
  543. /// with a branch to the new copy. If there was no old copy, this acts
  544. /// just like JIT::getPointerToFunction().
  545. ///
  546. void *JIT::recompileAndRelinkFunction(Function *F) {
  547. void *OldAddr = getPointerToGlobalIfAvailable(F);
  548. // If it's not already compiled there is no reason to patch it up.
  549. if (!OldAddr) return getPointerToFunction(F);
  550. // Delete the old function mapping.
  551. addGlobalMapping(F, nullptr);
  552. // Recodegen the function
  553. runJITOnFunction(F);
  554. // Update state, forward the old function to the new function.
  555. void *Addr = getPointerToGlobalIfAvailable(F);
  556. assert(Addr && "Code generation didn't add function to GlobalAddress table!");
  557. TJI.replaceMachineCodeForFunction(OldAddr, Addr);
  558. return Addr;
  559. }
  560. /// getMemoryForGV - This method abstracts memory allocation of global
  561. /// variable so that the JIT can allocate thread local variables depending
  562. /// on the target.
  563. ///
  564. char* JIT::getMemoryForGV(const GlobalVariable* GV) {
  565. char *Ptr;
  566. // GlobalVariable's which are not "constant" will cause trouble in a server
  567. // situation. It's returned in the same block of memory as code which may
  568. // not be writable.
  569. if (isGVCompilationDisabled() && !GV->isConstant()) {
  570. report_fatal_error("Compilation of non-internal GlobalValue is disabled!");
  571. }
  572. // Some applications require globals and code to live together, so they may
  573. // be allocated into the same buffer, but in general globals are allocated
  574. // through the memory manager which puts them near the code but not in the
  575. // same buffer.
  576. Type *GlobalType = GV->getType()->getElementType();
  577. size_t S = getDataLayout()->getTypeAllocSize(GlobalType);
  578. size_t A = getDataLayout()->getPreferredAlignment(GV);
  579. if (GV->isThreadLocal()) {
  580. std::lock_guard<std::recursive_mutex> locked(lock);
  581. Ptr = TJI.allocateThreadLocalMemory(S);
  582. } else if (TJI.allocateSeparateGVMemory()) {
  583. if (A <= 8) {
  584. Ptr = (char*)malloc(S);
  585. } else {
  586. // Allocate S+A bytes of memory, then use an aligned pointer within that
  587. // space.
  588. Ptr = (char*)malloc(S+A);
  589. unsigned MisAligned = ((intptr_t)Ptr & (A-1));
  590. Ptr = Ptr + (MisAligned ? (A-MisAligned) : 0);
  591. }
  592. } else if (AllocateGVsWithCode) {
  593. Ptr = (char*)JCE->allocateSpace(S, A);
  594. } else {
  595. Ptr = (char*)JCE->allocateGlobal(S, A);
  596. }
  597. return Ptr;
  598. }
  599. void JIT::addPendingFunction(Function *F) {
  600. std::lock_guard<std::recursive_mutex> locked(lock);
  601. jitstate->getPendingFunctions().push_back(F);
  602. }
  603. JITEventListener::~JITEventListener() {}