LLJIT.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. //===--------- LLJIT.cpp - An ORC-based JIT for compiling LLVM IR ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/ExecutionEngine/Orc/LLJIT.h"
  9. #include "llvm/ExecutionEngine/JITLink/EHFrameSupport.h"
  10. #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
  11. #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"
  12. #include "llvm/ExecutionEngine/Orc/ExecutorProcessControl.h"
  13. #include "llvm/ExecutionEngine/Orc/MachOPlatform.h"
  14. #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
  15. #include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h"
  16. #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
  17. #include "llvm/ExecutionEngine/Orc/Shared/OrcError.h"
  18. #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
  19. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  20. #include "llvm/IR/GlobalVariable.h"
  21. #include "llvm/IR/IRBuilder.h"
  22. #include "llvm/IR/Mangler.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/Support/DynamicLibrary.h"
  25. #include <map>
  26. #define DEBUG_TYPE "orc"
  27. using namespace llvm;
  28. using namespace llvm::orc;
  29. namespace {
  30. /// Adds helper function decls and wrapper functions that call the helper with
  31. /// some additional prefix arguments.
  32. ///
  33. /// E.g. For wrapper "foo" with type i8(i8, i64), helper "bar", and prefix
  34. /// args i32 4 and i16 12345, this function will add:
  35. ///
  36. /// declare i8 @bar(i32, i16, i8, i64)
  37. ///
  38. /// define i8 @foo(i8, i64) {
  39. /// entry:
  40. /// %2 = call i8 @bar(i32 4, i16 12345, i8 %0, i64 %1)
  41. /// ret i8 %2
  42. /// }
  43. ///
  44. Function *addHelperAndWrapper(Module &M, StringRef WrapperName,
  45. FunctionType *WrapperFnType,
  46. GlobalValue::VisibilityTypes WrapperVisibility,
  47. StringRef HelperName,
  48. ArrayRef<Value *> HelperPrefixArgs) {
  49. std::vector<Type *> HelperArgTypes;
  50. for (auto *Arg : HelperPrefixArgs)
  51. HelperArgTypes.push_back(Arg->getType());
  52. for (auto *T : WrapperFnType->params())
  53. HelperArgTypes.push_back(T);
  54. auto *HelperFnType =
  55. FunctionType::get(WrapperFnType->getReturnType(), HelperArgTypes, false);
  56. auto *HelperFn = Function::Create(HelperFnType, GlobalValue::ExternalLinkage,
  57. HelperName, M);
  58. auto *WrapperFn = Function::Create(
  59. WrapperFnType, GlobalValue::ExternalLinkage, WrapperName, M);
  60. WrapperFn->setVisibility(WrapperVisibility);
  61. auto *EntryBlock = BasicBlock::Create(M.getContext(), "entry", WrapperFn);
  62. IRBuilder<> IB(EntryBlock);
  63. std::vector<Value *> HelperArgs;
  64. for (auto *Arg : HelperPrefixArgs)
  65. HelperArgs.push_back(Arg);
  66. for (auto &Arg : WrapperFn->args())
  67. HelperArgs.push_back(&Arg);
  68. auto *HelperResult = IB.CreateCall(HelperFn, HelperArgs);
  69. if (HelperFn->getReturnType()->isVoidTy())
  70. IB.CreateRetVoid();
  71. else
  72. IB.CreateRet(HelperResult);
  73. return WrapperFn;
  74. }
  75. class ORCPlatformSupport : public LLJIT::PlatformSupport {
  76. public:
  77. ORCPlatformSupport(orc::LLJIT &J) : J(J) {}
  78. Error initialize(orc::JITDylib &JD) override {
  79. using llvm::orc::shared::SPSExecutorAddr;
  80. using llvm::orc::shared::SPSString;
  81. using SPSDLOpenSig = SPSExecutorAddr(SPSString, int32_t);
  82. enum dlopen_mode : int32_t {
  83. ORC_RT_RTLD_LAZY = 0x1,
  84. ORC_RT_RTLD_NOW = 0x2,
  85. ORC_RT_RTLD_LOCAL = 0x4,
  86. ORC_RT_RTLD_GLOBAL = 0x8
  87. };
  88. if (auto WrapperAddr = J.lookup("__orc_rt_jit_dlopen_wrapper")) {
  89. return J.getExecutionSession().callSPSWrapper<SPSDLOpenSig>(
  90. *WrapperAddr, DSOHandles[&JD], JD.getName(),
  91. int32_t(ORC_RT_RTLD_LAZY));
  92. } else
  93. return WrapperAddr.takeError();
  94. }
  95. Error deinitialize(orc::JITDylib &JD) override {
  96. using llvm::orc::shared::SPSExecutorAddr;
  97. using SPSDLCloseSig = int32_t(SPSExecutorAddr);
  98. if (auto WrapperAddr = J.lookup("__orc_rt_jit_dlclose_wrapper")) {
  99. int32_t result;
  100. auto E = J.getExecutionSession().callSPSWrapper<SPSDLCloseSig>(
  101. *WrapperAddr, result, DSOHandles[&JD]);
  102. if (E)
  103. return E;
  104. else if (result)
  105. return make_error<StringError>("dlclose failed",
  106. inconvertibleErrorCode());
  107. DSOHandles.erase(&JD);
  108. } else
  109. return WrapperAddr.takeError();
  110. return Error::success();
  111. }
  112. private:
  113. orc::LLJIT &J;
  114. DenseMap<orc::JITDylib *, orc::ExecutorAddr> DSOHandles;
  115. };
  116. class GenericLLVMIRPlatformSupport;
  117. /// orc::Platform component of Generic LLVM IR Platform support.
  118. /// Just forwards calls to the GenericLLVMIRPlatformSupport class below.
  119. class GenericLLVMIRPlatform : public Platform {
  120. public:
  121. GenericLLVMIRPlatform(GenericLLVMIRPlatformSupport &S) : S(S) {}
  122. Error setupJITDylib(JITDylib &JD) override;
  123. Error teardownJITDylib(JITDylib &JD) override;
  124. Error notifyAdding(ResourceTracker &RT,
  125. const MaterializationUnit &MU) override;
  126. Error notifyRemoving(ResourceTracker &RT) override {
  127. // Noop -- Nothing to do (yet).
  128. return Error::success();
  129. }
  130. private:
  131. GenericLLVMIRPlatformSupport &S;
  132. };
  133. /// This transform parses llvm.global_ctors to produce a single initialization
  134. /// function for the module, records the function, then deletes
  135. /// llvm.global_ctors.
  136. class GlobalCtorDtorScraper {
  137. public:
  138. GlobalCtorDtorScraper(GenericLLVMIRPlatformSupport &PS,
  139. StringRef InitFunctionPrefix,
  140. StringRef DeInitFunctionPrefix)
  141. : PS(PS), InitFunctionPrefix(InitFunctionPrefix),
  142. DeInitFunctionPrefix(DeInitFunctionPrefix) {}
  143. Expected<ThreadSafeModule> operator()(ThreadSafeModule TSM,
  144. MaterializationResponsibility &R);
  145. private:
  146. GenericLLVMIRPlatformSupport &PS;
  147. StringRef InitFunctionPrefix;
  148. StringRef DeInitFunctionPrefix;
  149. };
  150. /// Generic IR Platform Support
  151. ///
  152. /// Scrapes llvm.global_ctors and llvm.global_dtors and replaces them with
  153. /// specially named 'init' and 'deinit'. Injects definitions / interposes for
  154. /// some runtime API, including __cxa_atexit, dlopen, and dlclose.
  155. class GenericLLVMIRPlatformSupport : public LLJIT::PlatformSupport {
  156. public:
  157. GenericLLVMIRPlatformSupport(LLJIT &J)
  158. : J(J), InitFunctionPrefix(J.mangle("__orc_init_func.")),
  159. DeInitFunctionPrefix(J.mangle("__orc_deinit_func.")) {
  160. getExecutionSession().setPlatform(
  161. std::make_unique<GenericLLVMIRPlatform>(*this));
  162. setInitTransform(J, GlobalCtorDtorScraper(*this, InitFunctionPrefix,
  163. DeInitFunctionPrefix));
  164. SymbolMap StdInterposes;
  165. StdInterposes[J.mangleAndIntern("__lljit.platform_support_instance")] =
  166. JITEvaluatedSymbol(pointerToJITTargetAddress(this),
  167. JITSymbolFlags::Exported);
  168. StdInterposes[J.mangleAndIntern("__lljit.cxa_atexit_helper")] =
  169. JITEvaluatedSymbol(pointerToJITTargetAddress(registerCxaAtExitHelper),
  170. JITSymbolFlags());
  171. cantFail(
  172. J.getMainJITDylib().define(absoluteSymbols(std::move(StdInterposes))));
  173. cantFail(setupJITDylib(J.getMainJITDylib()));
  174. cantFail(J.addIRModule(J.getMainJITDylib(), createPlatformRuntimeModule()));
  175. }
  176. ExecutionSession &getExecutionSession() { return J.getExecutionSession(); }
  177. /// Adds a module that defines the __dso_handle global.
  178. Error setupJITDylib(JITDylib &JD) {
  179. // Add per-jitdylib standard interposes.
  180. SymbolMap PerJDInterposes;
  181. PerJDInterposes[J.mangleAndIntern("__lljit.run_atexits_helper")] =
  182. JITEvaluatedSymbol(pointerToJITTargetAddress(runAtExitsHelper),
  183. JITSymbolFlags());
  184. PerJDInterposes[J.mangleAndIntern("__lljit.atexit_helper")] =
  185. JITEvaluatedSymbol(pointerToJITTargetAddress(registerAtExitHelper),
  186. JITSymbolFlags());
  187. cantFail(JD.define(absoluteSymbols(std::move(PerJDInterposes))));
  188. auto Ctx = std::make_unique<LLVMContext>();
  189. auto M = std::make_unique<Module>("__standard_lib", *Ctx);
  190. M->setDataLayout(J.getDataLayout());
  191. auto *Int64Ty = Type::getInt64Ty(*Ctx);
  192. auto *DSOHandle = new GlobalVariable(
  193. *M, Int64Ty, true, GlobalValue::ExternalLinkage,
  194. ConstantInt::get(Int64Ty, reinterpret_cast<uintptr_t>(&JD)),
  195. "__dso_handle");
  196. DSOHandle->setVisibility(GlobalValue::DefaultVisibility);
  197. DSOHandle->setInitializer(
  198. ConstantInt::get(Int64Ty, pointerToJITTargetAddress(&JD)));
  199. auto *GenericIRPlatformSupportTy =
  200. StructType::create(*Ctx, "lljit.GenericLLJITIRPlatformSupport");
  201. auto *PlatformInstanceDecl = new GlobalVariable(
  202. *M, GenericIRPlatformSupportTy, true, GlobalValue::ExternalLinkage,
  203. nullptr, "__lljit.platform_support_instance");
  204. auto *VoidTy = Type::getVoidTy(*Ctx);
  205. addHelperAndWrapper(
  206. *M, "__lljit_run_atexits", FunctionType::get(VoidTy, {}, false),
  207. GlobalValue::HiddenVisibility, "__lljit.run_atexits_helper",
  208. {PlatformInstanceDecl, DSOHandle});
  209. auto *IntTy = Type::getIntNTy(*Ctx, sizeof(int) * CHAR_BIT);
  210. auto *AtExitCallbackTy = FunctionType::get(VoidTy, {}, false);
  211. auto *AtExitCallbackPtrTy = PointerType::getUnqual(AtExitCallbackTy);
  212. addHelperAndWrapper(*M, "atexit",
  213. FunctionType::get(IntTy, {AtExitCallbackPtrTy}, false),
  214. GlobalValue::HiddenVisibility, "__lljit.atexit_helper",
  215. {PlatformInstanceDecl, DSOHandle});
  216. return J.addIRModule(JD, ThreadSafeModule(std::move(M), std::move(Ctx)));
  217. }
  218. Error notifyAdding(ResourceTracker &RT, const MaterializationUnit &MU) {
  219. auto &JD = RT.getJITDylib();
  220. if (auto &InitSym = MU.getInitializerSymbol())
  221. InitSymbols[&JD].add(InitSym, SymbolLookupFlags::WeaklyReferencedSymbol);
  222. else {
  223. // If there's no identified init symbol attached, but there is a symbol
  224. // with the GenericIRPlatform::InitFunctionPrefix, then treat that as
  225. // an init function. Add the symbol to both the InitSymbols map (which
  226. // will trigger a lookup to materialize the module) and the InitFunctions
  227. // map (which holds the names of the symbols to execute).
  228. for (auto &KV : MU.getSymbols())
  229. if ((*KV.first).startswith(InitFunctionPrefix)) {
  230. InitSymbols[&JD].add(KV.first,
  231. SymbolLookupFlags::WeaklyReferencedSymbol);
  232. InitFunctions[&JD].add(KV.first);
  233. } else if ((*KV.first).startswith(DeInitFunctionPrefix)) {
  234. DeInitFunctions[&JD].add(KV.first);
  235. }
  236. }
  237. return Error::success();
  238. }
  239. Error initialize(JITDylib &JD) override {
  240. LLVM_DEBUG({
  241. dbgs() << "GenericLLVMIRPlatformSupport getting initializers to run\n";
  242. });
  243. if (auto Initializers = getInitializers(JD)) {
  244. LLVM_DEBUG(
  245. { dbgs() << "GenericLLVMIRPlatformSupport running initializers\n"; });
  246. for (auto InitFnAddr : *Initializers) {
  247. LLVM_DEBUG({
  248. dbgs() << " Running init " << formatv("{0:x16}", InitFnAddr)
  249. << "...\n";
  250. });
  251. auto *InitFn = jitTargetAddressToFunction<void (*)()>(InitFnAddr);
  252. InitFn();
  253. }
  254. } else
  255. return Initializers.takeError();
  256. return Error::success();
  257. }
  258. Error deinitialize(JITDylib &JD) override {
  259. LLVM_DEBUG({
  260. dbgs() << "GenericLLVMIRPlatformSupport getting deinitializers to run\n";
  261. });
  262. if (auto Deinitializers = getDeinitializers(JD)) {
  263. LLVM_DEBUG({
  264. dbgs() << "GenericLLVMIRPlatformSupport running deinitializers\n";
  265. });
  266. for (auto DeinitFnAddr : *Deinitializers) {
  267. LLVM_DEBUG({
  268. dbgs() << " Running deinit " << formatv("{0:x16}", DeinitFnAddr)
  269. << "...\n";
  270. });
  271. auto *DeinitFn = jitTargetAddressToFunction<void (*)()>(DeinitFnAddr);
  272. DeinitFn();
  273. }
  274. } else
  275. return Deinitializers.takeError();
  276. return Error::success();
  277. }
  278. void registerInitFunc(JITDylib &JD, SymbolStringPtr InitName) {
  279. getExecutionSession().runSessionLocked([&]() {
  280. InitFunctions[&JD].add(InitName);
  281. });
  282. }
  283. void registerDeInitFunc(JITDylib &JD, SymbolStringPtr DeInitName) {
  284. getExecutionSession().runSessionLocked(
  285. [&]() { DeInitFunctions[&JD].add(DeInitName); });
  286. }
  287. private:
  288. Expected<std::vector<JITTargetAddress>> getInitializers(JITDylib &JD) {
  289. if (auto Err = issueInitLookups(JD))
  290. return std::move(Err);
  291. DenseMap<JITDylib *, SymbolLookupSet> LookupSymbols;
  292. std::vector<JITDylibSP> DFSLinkOrder;
  293. if (auto Err = getExecutionSession().runSessionLocked([&]() -> Error {
  294. if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder())
  295. DFSLinkOrder = std::move(*DFSLinkOrderOrErr);
  296. else
  297. return DFSLinkOrderOrErr.takeError();
  298. for (auto &NextJD : DFSLinkOrder) {
  299. auto IFItr = InitFunctions.find(NextJD.get());
  300. if (IFItr != InitFunctions.end()) {
  301. LookupSymbols[NextJD.get()] = std::move(IFItr->second);
  302. InitFunctions.erase(IFItr);
  303. }
  304. }
  305. return Error::success();
  306. }))
  307. return std::move(Err);
  308. LLVM_DEBUG({
  309. dbgs() << "JITDylib init order is [ ";
  310. for (auto &JD : llvm::reverse(DFSLinkOrder))
  311. dbgs() << "\"" << JD->getName() << "\" ";
  312. dbgs() << "]\n";
  313. dbgs() << "Looking up init functions:\n";
  314. for (auto &KV : LookupSymbols)
  315. dbgs() << " \"" << KV.first->getName() << "\": " << KV.second << "\n";
  316. });
  317. auto &ES = getExecutionSession();
  318. auto LookupResult = Platform::lookupInitSymbols(ES, LookupSymbols);
  319. if (!LookupResult)
  320. return LookupResult.takeError();
  321. std::vector<JITTargetAddress> Initializers;
  322. while (!DFSLinkOrder.empty()) {
  323. auto &NextJD = *DFSLinkOrder.back();
  324. DFSLinkOrder.pop_back();
  325. auto InitsItr = LookupResult->find(&NextJD);
  326. if (InitsItr == LookupResult->end())
  327. continue;
  328. for (auto &KV : InitsItr->second)
  329. Initializers.push_back(KV.second.getAddress());
  330. }
  331. return Initializers;
  332. }
  333. Expected<std::vector<JITTargetAddress>> getDeinitializers(JITDylib &JD) {
  334. auto &ES = getExecutionSession();
  335. auto LLJITRunAtExits = J.mangleAndIntern("__lljit_run_atexits");
  336. DenseMap<JITDylib *, SymbolLookupSet> LookupSymbols;
  337. std::vector<JITDylibSP> DFSLinkOrder;
  338. if (auto Err = ES.runSessionLocked([&]() -> Error {
  339. if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder())
  340. DFSLinkOrder = std::move(*DFSLinkOrderOrErr);
  341. else
  342. return DFSLinkOrderOrErr.takeError();
  343. for (auto &NextJD : DFSLinkOrder) {
  344. auto &JDLookupSymbols = LookupSymbols[NextJD.get()];
  345. auto DIFItr = DeInitFunctions.find(NextJD.get());
  346. if (DIFItr != DeInitFunctions.end()) {
  347. LookupSymbols[NextJD.get()] = std::move(DIFItr->second);
  348. DeInitFunctions.erase(DIFItr);
  349. }
  350. JDLookupSymbols.add(LLJITRunAtExits,
  351. SymbolLookupFlags::WeaklyReferencedSymbol);
  352. }
  353. return Error::success();
  354. }))
  355. return std::move(Err);
  356. LLVM_DEBUG({
  357. dbgs() << "JITDylib deinit order is [ ";
  358. for (auto &JD : DFSLinkOrder)
  359. dbgs() << "\"" << JD->getName() << "\" ";
  360. dbgs() << "]\n";
  361. dbgs() << "Looking up deinit functions:\n";
  362. for (auto &KV : LookupSymbols)
  363. dbgs() << " \"" << KV.first->getName() << "\": " << KV.second << "\n";
  364. });
  365. auto LookupResult = Platform::lookupInitSymbols(ES, LookupSymbols);
  366. if (!LookupResult)
  367. return LookupResult.takeError();
  368. std::vector<JITTargetAddress> DeInitializers;
  369. for (auto &NextJD : DFSLinkOrder) {
  370. auto DeInitsItr = LookupResult->find(NextJD.get());
  371. assert(DeInitsItr != LookupResult->end() &&
  372. "Every JD should have at least __lljit_run_atexits");
  373. auto RunAtExitsItr = DeInitsItr->second.find(LLJITRunAtExits);
  374. if (RunAtExitsItr != DeInitsItr->second.end())
  375. DeInitializers.push_back(RunAtExitsItr->second.getAddress());
  376. for (auto &KV : DeInitsItr->second)
  377. if (KV.first != LLJITRunAtExits)
  378. DeInitializers.push_back(KV.second.getAddress());
  379. }
  380. return DeInitializers;
  381. }
  382. /// Issue lookups for all init symbols required to initialize JD (and any
  383. /// JITDylibs that it depends on).
  384. Error issueInitLookups(JITDylib &JD) {
  385. DenseMap<JITDylib *, SymbolLookupSet> RequiredInitSymbols;
  386. std::vector<JITDylibSP> DFSLinkOrder;
  387. if (auto Err = getExecutionSession().runSessionLocked([&]() -> Error {
  388. if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder())
  389. DFSLinkOrder = std::move(*DFSLinkOrderOrErr);
  390. else
  391. return DFSLinkOrderOrErr.takeError();
  392. for (auto &NextJD : DFSLinkOrder) {
  393. auto ISItr = InitSymbols.find(NextJD.get());
  394. if (ISItr != InitSymbols.end()) {
  395. RequiredInitSymbols[NextJD.get()] = std::move(ISItr->second);
  396. InitSymbols.erase(ISItr);
  397. }
  398. }
  399. return Error::success();
  400. }))
  401. return Err;
  402. return Platform::lookupInitSymbols(getExecutionSession(),
  403. RequiredInitSymbols)
  404. .takeError();
  405. }
  406. static void registerCxaAtExitHelper(void *Self, void (*F)(void *), void *Ctx,
  407. void *DSOHandle) {
  408. LLVM_DEBUG({
  409. dbgs() << "Registering cxa atexit function " << (void *)F << " for JD "
  410. << (*static_cast<JITDylib **>(DSOHandle))->getName() << "\n";
  411. });
  412. static_cast<GenericLLVMIRPlatformSupport *>(Self)->AtExitMgr.registerAtExit(
  413. F, Ctx, DSOHandle);
  414. }
  415. static void registerAtExitHelper(void *Self, void *DSOHandle, void (*F)()) {
  416. LLVM_DEBUG({
  417. dbgs() << "Registering atexit function " << (void *)F << " for JD "
  418. << (*static_cast<JITDylib **>(DSOHandle))->getName() << "\n";
  419. });
  420. static_cast<GenericLLVMIRPlatformSupport *>(Self)->AtExitMgr.registerAtExit(
  421. reinterpret_cast<void (*)(void *)>(F), nullptr, DSOHandle);
  422. }
  423. static void runAtExitsHelper(void *Self, void *DSOHandle) {
  424. LLVM_DEBUG({
  425. dbgs() << "Running atexit functions for JD "
  426. << (*static_cast<JITDylib **>(DSOHandle))->getName() << "\n";
  427. });
  428. static_cast<GenericLLVMIRPlatformSupport *>(Self)->AtExitMgr.runAtExits(
  429. DSOHandle);
  430. }
  431. // Constructs an LLVM IR module containing platform runtime globals,
  432. // functions, and interposes.
  433. ThreadSafeModule createPlatformRuntimeModule() {
  434. auto Ctx = std::make_unique<LLVMContext>();
  435. auto M = std::make_unique<Module>("__standard_lib", *Ctx);
  436. M->setDataLayout(J.getDataLayout());
  437. auto *GenericIRPlatformSupportTy =
  438. StructType::create(*Ctx, "lljit.GenericLLJITIRPlatformSupport");
  439. auto *PlatformInstanceDecl = new GlobalVariable(
  440. *M, GenericIRPlatformSupportTy, true, GlobalValue::ExternalLinkage,
  441. nullptr, "__lljit.platform_support_instance");
  442. auto *Int8Ty = Type::getInt8Ty(*Ctx);
  443. auto *IntTy = Type::getIntNTy(*Ctx, sizeof(int) * CHAR_BIT);
  444. auto *VoidTy = Type::getVoidTy(*Ctx);
  445. auto *BytePtrTy = PointerType::getUnqual(Int8Ty);
  446. auto *CxaAtExitCallbackTy = FunctionType::get(VoidTy, {BytePtrTy}, false);
  447. auto *CxaAtExitCallbackPtrTy = PointerType::getUnqual(CxaAtExitCallbackTy);
  448. addHelperAndWrapper(
  449. *M, "__cxa_atexit",
  450. FunctionType::get(IntTy, {CxaAtExitCallbackPtrTy, BytePtrTy, BytePtrTy},
  451. false),
  452. GlobalValue::DefaultVisibility, "__lljit.cxa_atexit_helper",
  453. {PlatformInstanceDecl});
  454. return ThreadSafeModule(std::move(M), std::move(Ctx));
  455. }
  456. LLJIT &J;
  457. std::string InitFunctionPrefix;
  458. std::string DeInitFunctionPrefix;
  459. DenseMap<JITDylib *, SymbolLookupSet> InitSymbols;
  460. DenseMap<JITDylib *, SymbolLookupSet> InitFunctions;
  461. DenseMap<JITDylib *, SymbolLookupSet> DeInitFunctions;
  462. ItaniumCXAAtExitSupport AtExitMgr;
  463. };
  464. Error GenericLLVMIRPlatform::setupJITDylib(JITDylib &JD) {
  465. return S.setupJITDylib(JD);
  466. }
  467. Error GenericLLVMIRPlatform::teardownJITDylib(JITDylib &JD) {
  468. return Error::success();
  469. }
  470. Error GenericLLVMIRPlatform::notifyAdding(ResourceTracker &RT,
  471. const MaterializationUnit &MU) {
  472. return S.notifyAdding(RT, MU);
  473. }
  474. Expected<ThreadSafeModule>
  475. GlobalCtorDtorScraper::operator()(ThreadSafeModule TSM,
  476. MaterializationResponsibility &R) {
  477. auto Err = TSM.withModuleDo([&](Module &M) -> Error {
  478. auto &Ctx = M.getContext();
  479. auto *GlobalCtors = M.getNamedGlobal("llvm.global_ctors");
  480. auto *GlobalDtors = M.getNamedGlobal("llvm.global_dtors");
  481. auto RegisterCOrDtors = [&](GlobalVariable *GlobalCOrDtors,
  482. bool isCtor) -> Error {
  483. // If there's no llvm.global_c/dtor or it's just a decl then skip.
  484. if (!GlobalCOrDtors || GlobalCOrDtors->isDeclaration())
  485. return Error::success();
  486. std::string InitOrDeInitFunctionName;
  487. if (isCtor)
  488. raw_string_ostream(InitOrDeInitFunctionName)
  489. << InitFunctionPrefix << M.getModuleIdentifier();
  490. else
  491. raw_string_ostream(InitOrDeInitFunctionName)
  492. << DeInitFunctionPrefix << M.getModuleIdentifier();
  493. MangleAndInterner Mangle(PS.getExecutionSession(), M.getDataLayout());
  494. auto InternedInitOrDeInitName = Mangle(InitOrDeInitFunctionName);
  495. if (auto Err = R.defineMaterializing(
  496. {{InternedInitOrDeInitName, JITSymbolFlags::Callable}}))
  497. return Err;
  498. auto *InitOrDeInitFunc = Function::Create(
  499. FunctionType::get(Type::getVoidTy(Ctx), {}, false),
  500. GlobalValue::ExternalLinkage, InitOrDeInitFunctionName, &M);
  501. InitOrDeInitFunc->setVisibility(GlobalValue::HiddenVisibility);
  502. std::vector<std::pair<Function *, unsigned>> InitsOrDeInits;
  503. auto COrDtors = isCtor ? getConstructors(M) : getDestructors(M);
  504. for (auto E : COrDtors)
  505. InitsOrDeInits.push_back(std::make_pair(E.Func, E.Priority));
  506. llvm::sort(InitsOrDeInits, llvm::less_second());
  507. auto *InitOrDeInitFuncEntryBlock =
  508. BasicBlock::Create(Ctx, "entry", InitOrDeInitFunc);
  509. IRBuilder<> IB(InitOrDeInitFuncEntryBlock);
  510. for (auto &KV : InitsOrDeInits)
  511. IB.CreateCall(KV.first);
  512. IB.CreateRetVoid();
  513. if (isCtor)
  514. PS.registerInitFunc(R.getTargetJITDylib(), InternedInitOrDeInitName);
  515. else
  516. PS.registerDeInitFunc(R.getTargetJITDylib(), InternedInitOrDeInitName);
  517. GlobalCOrDtors->eraseFromParent();
  518. return Error::success();
  519. };
  520. if (auto Err = RegisterCOrDtors(GlobalCtors, true))
  521. return Err;
  522. if (auto Err = RegisterCOrDtors(GlobalDtors, false))
  523. return Err;
  524. return Error::success();
  525. });
  526. if (Err)
  527. return std::move(Err);
  528. return std::move(TSM);
  529. }
  530. /// Inactive Platform Support
  531. ///
  532. /// Explicitly disables platform support. JITDylibs are not scanned for special
  533. /// init/deinit symbols. No runtime API interposes are injected.
  534. class InactivePlatformSupport : public LLJIT::PlatformSupport {
  535. public:
  536. InactivePlatformSupport() = default;
  537. Error initialize(JITDylib &JD) override {
  538. LLVM_DEBUG(dbgs() << "InactivePlatformSupport: no initializers running for "
  539. << JD.getName() << "\n");
  540. return Error::success();
  541. }
  542. Error deinitialize(JITDylib &JD) override {
  543. LLVM_DEBUG(
  544. dbgs() << "InactivePlatformSupport: no deinitializers running for "
  545. << JD.getName() << "\n");
  546. return Error::success();
  547. }
  548. };
  549. } // end anonymous namespace
  550. namespace llvm {
  551. namespace orc {
  552. void LLJIT::PlatformSupport::setInitTransform(
  553. LLJIT &J, IRTransformLayer::TransformFunction T) {
  554. J.InitHelperTransformLayer->setTransform(std::move(T));
  555. }
  556. LLJIT::PlatformSupport::~PlatformSupport() = default;
  557. Error LLJITBuilderState::prepareForConstruction() {
  558. LLVM_DEBUG(dbgs() << "Preparing to create LLJIT instance...\n");
  559. if (!JTMB) {
  560. LLVM_DEBUG({
  561. dbgs() << " No explicitly set JITTargetMachineBuilder. "
  562. "Detecting host...\n";
  563. });
  564. if (auto JTMBOrErr = JITTargetMachineBuilder::detectHost())
  565. JTMB = std::move(*JTMBOrErr);
  566. else
  567. return JTMBOrErr.takeError();
  568. }
  569. LLVM_DEBUG({
  570. dbgs() << " JITTargetMachineBuilder is "
  571. << JITTargetMachineBuilderPrinter(*JTMB, " ")
  572. << " Pre-constructed ExecutionSession: " << (ES ? "Yes" : "No")
  573. << "\n"
  574. << " DataLayout: ";
  575. if (DL)
  576. dbgs() << DL->getStringRepresentation() << "\n";
  577. else
  578. dbgs() << "None (will be created by JITTargetMachineBuilder)\n";
  579. dbgs() << " Custom object-linking-layer creator: "
  580. << (CreateObjectLinkingLayer ? "Yes" : "No") << "\n"
  581. << " Custom compile-function creator: "
  582. << (CreateCompileFunction ? "Yes" : "No") << "\n"
  583. << " Custom platform-setup function: "
  584. << (SetUpPlatform ? "Yes" : "No") << "\n"
  585. << " Number of compile threads: " << NumCompileThreads;
  586. if (!NumCompileThreads)
  587. dbgs() << " (code will be compiled on the execution thread)\n";
  588. else
  589. dbgs() << "\n";
  590. });
  591. // If neither ES nor EPC has been set then create an EPC instance.
  592. if (!ES && !EPC) {
  593. LLVM_DEBUG({
  594. dbgs() << "ExecutorProcessControl not specified, "
  595. "Creating SelfExecutorProcessControl instance\n";
  596. });
  597. if (auto EPCOrErr = SelfExecutorProcessControl::Create())
  598. EPC = std::move(*EPCOrErr);
  599. else
  600. return EPCOrErr.takeError();
  601. } else
  602. LLVM_DEBUG({
  603. dbgs() << "Using explicitly specified ExecutorProcessControl instance "
  604. << EPC.get() << "\n";
  605. });
  606. // If the client didn't configure any linker options then auto-configure the
  607. // JIT linker.
  608. if (!CreateObjectLinkingLayer) {
  609. auto &TT = JTMB->getTargetTriple();
  610. if (TT.getArch() == Triple::riscv64 ||
  611. TT.getArch() == Triple::loongarch64 ||
  612. (TT.isOSBinFormatMachO() &&
  613. (TT.getArch() == Triple::aarch64 || TT.getArch() == Triple::x86_64))) {
  614. JTMB->setRelocationModel(Reloc::PIC_);
  615. JTMB->setCodeModel(CodeModel::Small);
  616. CreateObjectLinkingLayer =
  617. [](ExecutionSession &ES,
  618. const Triple &) -> Expected<std::unique_ptr<ObjectLayer>> {
  619. auto ObjLinkingLayer = std::make_unique<ObjectLinkingLayer>(ES);
  620. if (auto EHFrameRegistrar = EPCEHFrameRegistrar::Create(ES))
  621. ObjLinkingLayer->addPlugin(
  622. std::make_unique<EHFrameRegistrationPlugin>(
  623. ES, std::move(*EHFrameRegistrar)));
  624. else
  625. return EHFrameRegistrar.takeError();
  626. return std::move(ObjLinkingLayer);
  627. };
  628. }
  629. }
  630. return Error::success();
  631. }
  632. LLJIT::~LLJIT() {
  633. if (CompileThreads)
  634. CompileThreads->wait();
  635. if (auto Err = ES->endSession())
  636. ES->reportError(std::move(Err));
  637. }
  638. Error LLJIT::addIRModule(ResourceTrackerSP RT, ThreadSafeModule TSM) {
  639. assert(TSM && "Can not add null module");
  640. if (auto Err =
  641. TSM.withModuleDo([&](Module &M) { return applyDataLayout(M); }))
  642. return Err;
  643. return InitHelperTransformLayer->add(std::move(RT), std::move(TSM));
  644. }
  645. Error LLJIT::addIRModule(JITDylib &JD, ThreadSafeModule TSM) {
  646. return addIRModule(JD.getDefaultResourceTracker(), std::move(TSM));
  647. }
  648. Error LLJIT::addObjectFile(ResourceTrackerSP RT,
  649. std::unique_ptr<MemoryBuffer> Obj) {
  650. assert(Obj && "Can not add null object");
  651. return ObjTransformLayer->add(std::move(RT), std::move(Obj));
  652. }
  653. Error LLJIT::addObjectFile(JITDylib &JD, std::unique_ptr<MemoryBuffer> Obj) {
  654. return addObjectFile(JD.getDefaultResourceTracker(), std::move(Obj));
  655. }
  656. Expected<ExecutorAddr> LLJIT::lookupLinkerMangled(JITDylib &JD,
  657. SymbolStringPtr Name) {
  658. if (auto Sym = ES->lookup(
  659. makeJITDylibSearchOrder(&JD, JITDylibLookupFlags::MatchAllSymbols),
  660. Name))
  661. return ExecutorAddr(Sym->getAddress());
  662. else
  663. return Sym.takeError();
  664. }
  665. Expected<std::unique_ptr<ObjectLayer>>
  666. LLJIT::createObjectLinkingLayer(LLJITBuilderState &S, ExecutionSession &ES) {
  667. // If the config state provided an ObjectLinkingLayer factory then use it.
  668. if (S.CreateObjectLinkingLayer)
  669. return S.CreateObjectLinkingLayer(ES, S.JTMB->getTargetTriple());
  670. // Otherwise default to creating an RTDyldObjectLinkingLayer that constructs
  671. // a new SectionMemoryManager for each object.
  672. auto GetMemMgr = []() { return std::make_unique<SectionMemoryManager>(); };
  673. auto Layer =
  674. std::make_unique<RTDyldObjectLinkingLayer>(ES, std::move(GetMemMgr));
  675. if (S.JTMB->getTargetTriple().isOSBinFormatCOFF()) {
  676. Layer->setOverrideObjectFlagsWithResponsibilityFlags(true);
  677. Layer->setAutoClaimResponsibilityForObjectSymbols(true);
  678. }
  679. if (S.JTMB->getTargetTriple().isOSBinFormatELF() &&
  680. (S.JTMB->getTargetTriple().getArch() == Triple::ArchType::ppc64 ||
  681. S.JTMB->getTargetTriple().getArch() == Triple::ArchType::ppc64le))
  682. Layer->setAutoClaimResponsibilityForObjectSymbols(true);
  683. // FIXME: Explicit conversion to std::unique_ptr<ObjectLayer> added to silence
  684. // errors from some GCC / libstdc++ bots. Remove this conversion (i.e.
  685. // just return ObjLinkingLayer) once those bots are upgraded.
  686. return std::unique_ptr<ObjectLayer>(std::move(Layer));
  687. }
  688. Expected<std::unique_ptr<IRCompileLayer::IRCompiler>>
  689. LLJIT::createCompileFunction(LLJITBuilderState &S,
  690. JITTargetMachineBuilder JTMB) {
  691. /// If there is a custom compile function creator set then use it.
  692. if (S.CreateCompileFunction)
  693. return S.CreateCompileFunction(std::move(JTMB));
  694. // Otherwise default to creating a SimpleCompiler, or ConcurrentIRCompiler,
  695. // depending on the number of threads requested.
  696. if (S.NumCompileThreads > 0)
  697. return std::make_unique<ConcurrentIRCompiler>(std::move(JTMB));
  698. auto TM = JTMB.createTargetMachine();
  699. if (!TM)
  700. return TM.takeError();
  701. return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM));
  702. }
  703. LLJIT::LLJIT(LLJITBuilderState &S, Error &Err)
  704. : DL(""), TT(S.JTMB->getTargetTriple()) {
  705. ErrorAsOutParameter _(&Err);
  706. assert(!(S.EPC && S.ES) && "EPC and ES should not both be set");
  707. if (S.EPC) {
  708. ES = std::make_unique<ExecutionSession>(std::move(S.EPC));
  709. } else if (S.ES)
  710. ES = std::move(S.ES);
  711. else {
  712. if (auto EPC = SelfExecutorProcessControl::Create()) {
  713. ES = std::make_unique<ExecutionSession>(std::move(*EPC));
  714. } else {
  715. Err = EPC.takeError();
  716. return;
  717. }
  718. }
  719. if (auto MainOrErr = this->ES->createJITDylib("main"))
  720. Main = &*MainOrErr;
  721. else {
  722. Err = MainOrErr.takeError();
  723. return;
  724. }
  725. if (S.DL)
  726. DL = std::move(*S.DL);
  727. else if (auto DLOrErr = S.JTMB->getDefaultDataLayoutForTarget())
  728. DL = std::move(*DLOrErr);
  729. else {
  730. Err = DLOrErr.takeError();
  731. return;
  732. }
  733. auto ObjLayer = createObjectLinkingLayer(S, *ES);
  734. if (!ObjLayer) {
  735. Err = ObjLayer.takeError();
  736. return;
  737. }
  738. ObjLinkingLayer = std::move(*ObjLayer);
  739. ObjTransformLayer =
  740. std::make_unique<ObjectTransformLayer>(*ES, *ObjLinkingLayer);
  741. {
  742. auto CompileFunction = createCompileFunction(S, std::move(*S.JTMB));
  743. if (!CompileFunction) {
  744. Err = CompileFunction.takeError();
  745. return;
  746. }
  747. CompileLayer = std::make_unique<IRCompileLayer>(
  748. *ES, *ObjTransformLayer, std::move(*CompileFunction));
  749. TransformLayer = std::make_unique<IRTransformLayer>(*ES, *CompileLayer);
  750. InitHelperTransformLayer =
  751. std::make_unique<IRTransformLayer>(*ES, *TransformLayer);
  752. }
  753. if (S.NumCompileThreads > 0) {
  754. InitHelperTransformLayer->setCloneToNewContextOnEmit(true);
  755. CompileThreads =
  756. std::make_unique<ThreadPool>(hardware_concurrency(S.NumCompileThreads));
  757. ES->setDispatchTask([this](std::unique_ptr<Task> T) {
  758. // FIXME: We should be able to use move-capture here, but ThreadPool's
  759. // AsyncTaskTys are std::functions rather than unique_functions
  760. // (because MSVC's std::packaged_tasks don't support move-only types).
  761. // Fix this when all the above gets sorted out.
  762. CompileThreads->async([UnownedT = T.release()]() mutable {
  763. std::unique_ptr<Task> T(UnownedT);
  764. T->run();
  765. });
  766. });
  767. }
  768. if (S.SetUpPlatform)
  769. Err = S.SetUpPlatform(*this);
  770. else
  771. setUpGenericLLVMIRPlatform(*this);
  772. }
  773. std::string LLJIT::mangle(StringRef UnmangledName) const {
  774. std::string MangledName;
  775. {
  776. raw_string_ostream MangledNameStream(MangledName);
  777. Mangler::getNameWithPrefix(MangledNameStream, UnmangledName, DL);
  778. }
  779. return MangledName;
  780. }
  781. Error LLJIT::applyDataLayout(Module &M) {
  782. if (M.getDataLayout().isDefault())
  783. M.setDataLayout(DL);
  784. if (M.getDataLayout() != DL)
  785. return make_error<StringError>(
  786. "Added modules have incompatible data layouts: " +
  787. M.getDataLayout().getStringRepresentation() + " (module) vs " +
  788. DL.getStringRepresentation() + " (jit)",
  789. inconvertibleErrorCode());
  790. return Error::success();
  791. }
  792. Error setUpOrcPlatform(LLJIT& J) {
  793. LLVM_DEBUG(
  794. { dbgs() << "Setting up orc platform support for LLJIT\n"; });
  795. J.setPlatformSupport(std::make_unique<ORCPlatformSupport>(J));
  796. return Error::success();
  797. }
  798. void setUpGenericLLVMIRPlatform(LLJIT &J) {
  799. LLVM_DEBUG(
  800. { dbgs() << "Setting up GenericLLVMIRPlatform support for LLJIT\n"; });
  801. J.setPlatformSupport(std::make_unique<GenericLLVMIRPlatformSupport>(J));
  802. }
  803. Error setUpInactivePlatform(LLJIT &J) {
  804. LLVM_DEBUG(
  805. { dbgs() << "Explicitly deactivated platform support for LLJIT\n"; });
  806. J.setPlatformSupport(std::make_unique<InactivePlatformSupport>());
  807. return Error::success();
  808. }
  809. Error LLLazyJITBuilderState::prepareForConstruction() {
  810. if (auto Err = LLJITBuilderState::prepareForConstruction())
  811. return Err;
  812. TT = JTMB->getTargetTriple();
  813. return Error::success();
  814. }
  815. Error LLLazyJIT::addLazyIRModule(JITDylib &JD, ThreadSafeModule TSM) {
  816. assert(TSM && "Can not add null module");
  817. if (auto Err = TSM.withModuleDo(
  818. [&](Module &M) -> Error { return applyDataLayout(M); }))
  819. return Err;
  820. return CODLayer->add(JD, std::move(TSM));
  821. }
  822. LLLazyJIT::LLLazyJIT(LLLazyJITBuilderState &S, Error &Err) : LLJIT(S, Err) {
  823. // If LLJIT construction failed then bail out.
  824. if (Err)
  825. return;
  826. ErrorAsOutParameter _(&Err);
  827. /// Take/Create the lazy-compile callthrough manager.
  828. if (S.LCTMgr)
  829. LCTMgr = std::move(S.LCTMgr);
  830. else {
  831. if (auto LCTMgrOrErr = createLocalLazyCallThroughManager(
  832. S.TT, *ES, S.LazyCompileFailureAddr.getValue()))
  833. LCTMgr = std::move(*LCTMgrOrErr);
  834. else {
  835. Err = LCTMgrOrErr.takeError();
  836. return;
  837. }
  838. }
  839. // Take/Create the indirect stubs manager builder.
  840. auto ISMBuilder = std::move(S.ISMBuilder);
  841. // If none was provided, try to build one.
  842. if (!ISMBuilder)
  843. ISMBuilder = createLocalIndirectStubsManagerBuilder(S.TT);
  844. // No luck. Bail out.
  845. if (!ISMBuilder) {
  846. Err = make_error<StringError>("Could not construct "
  847. "IndirectStubsManagerBuilder for target " +
  848. S.TT.str(),
  849. inconvertibleErrorCode());
  850. return;
  851. }
  852. // Create the COD layer.
  853. CODLayer = std::make_unique<CompileOnDemandLayer>(
  854. *ES, *InitHelperTransformLayer, *LCTMgr, std::move(ISMBuilder));
  855. if (S.NumCompileThreads > 0)
  856. CODLayer->setCloneToNewContextOnEmit(true);
  857. }
  858. // In-process LLJIT uses eh-frame section wrappers via EPC, so we need to force
  859. // them to be linked in.
  860. LLVM_ATTRIBUTE_USED void linkComponents() {
  861. errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper
  862. << (void *)&llvm_orc_deregisterEHFrameSectionWrapper;
  863. }
  864. } // End namespace orc.
  865. } // End namespace llvm.