JIT.cpp 23 KB

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