lli.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
  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. //
  9. // This utility provides a simple wrapper around the LLVM Execution Engines,
  10. // which allow the direct execution of LLVM programs through a Just-In-Time
  11. // compiler, or through an interpreter if no JIT is available for this platform.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ExecutionUtils.h"
  15. #include "ForwardingMemoryManager.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/Bitcode/BitcodeReader.h"
  19. #include "llvm/CodeGen/CommandFlags.h"
  20. #include "llvm/CodeGen/LinkAllCodegenComponents.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/ExecutionEngine/GenericValue.h"
  23. #include "llvm/ExecutionEngine/Interpreter.h"
  24. #include "llvm/ExecutionEngine/JITEventListener.h"
  25. #include "llvm/ExecutionEngine/JITSymbol.h"
  26. #include "llvm/ExecutionEngine/MCJIT.h"
  27. #include "llvm/ExecutionEngine/ObjectCache.h"
  28. #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
  29. #include "llvm/ExecutionEngine/Orc/DebugUtils.h"
  30. #include "llvm/ExecutionEngine/Orc/ELFNixPlatform.h"
  31. #include "llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h"
  32. #include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
  33. #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"
  34. #include "llvm/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.h"
  35. #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
  36. #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
  37. #include "llvm/ExecutionEngine/Orc/LLJIT.h"
  38. #include "llvm/ExecutionEngine/Orc/MachOPlatform.h"
  39. #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
  40. #include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h"
  41. #include "llvm/ExecutionEngine/Orc/SymbolStringPool.h"
  42. #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
  43. #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
  44. #include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
  45. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  46. #include "llvm/IR/IRBuilder.h"
  47. #include "llvm/IR/LLVMContext.h"
  48. #include "llvm/IR/Module.h"
  49. #include "llvm/IR/Type.h"
  50. #include "llvm/IR/Verifier.h"
  51. #include "llvm/IRReader/IRReader.h"
  52. #include "llvm/Object/Archive.h"
  53. #include "llvm/Object/ObjectFile.h"
  54. #include "llvm/Support/CommandLine.h"
  55. #include "llvm/Support/Debug.h"
  56. #include "llvm/Support/DynamicLibrary.h"
  57. #include "llvm/Support/Format.h"
  58. #include "llvm/Support/InitLLVM.h"
  59. #include "llvm/Support/MathExtras.h"
  60. #include "llvm/Support/Memory.h"
  61. #include "llvm/Support/MemoryBuffer.h"
  62. #include "llvm/Support/Path.h"
  63. #include "llvm/Support/PluginLoader.h"
  64. #include "llvm/Support/Process.h"
  65. #include "llvm/Support/Program.h"
  66. #include "llvm/Support/SourceMgr.h"
  67. #include "llvm/Support/TargetSelect.h"
  68. #include "llvm/Support/WithColor.h"
  69. #include "llvm/Support/raw_ostream.h"
  70. #include "llvm/Transforms/Instrumentation.h"
  71. #include <cerrno>
  72. #include <optional>
  73. #if !defined(_MSC_VER) && !defined(__MINGW32__)
  74. #include <unistd.h>
  75. #else
  76. #include <io.h>
  77. #endif
  78. #ifdef __CYGWIN__
  79. #include <cygwin/version.h>
  80. #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
  81. #define DO_NOTHING_ATEXIT 1
  82. #endif
  83. #endif
  84. using namespace llvm;
  85. static codegen::RegisterCodeGenFlags CGF;
  86. #define DEBUG_TYPE "lli"
  87. namespace {
  88. enum class JITKind { MCJIT, Orc, OrcLazy };
  89. enum class JITLinkerKind { Default, RuntimeDyld, JITLink };
  90. cl::opt<std::string>
  91. InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
  92. cl::list<std::string>
  93. InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
  94. cl::opt<bool> ForceInterpreter("force-interpreter",
  95. cl::desc("Force interpretation: disable JIT"),
  96. cl::init(false));
  97. cl::opt<JITKind> UseJITKind(
  98. "jit-kind", cl::desc("Choose underlying JIT kind."),
  99. cl::init(JITKind::Orc),
  100. cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
  101. clEnumValN(JITKind::Orc, "orc", "Orc JIT"),
  102. clEnumValN(JITKind::OrcLazy, "orc-lazy",
  103. "Orc-based lazy JIT.")));
  104. cl::opt<JITLinkerKind>
  105. JITLinker("jit-linker", cl::desc("Choose the dynamic linker/loader."),
  106. cl::init(JITLinkerKind::Default),
  107. cl::values(clEnumValN(JITLinkerKind::Default, "default",
  108. "Default for platform and JIT-kind"),
  109. clEnumValN(JITLinkerKind::RuntimeDyld, "rtdyld",
  110. "RuntimeDyld"),
  111. clEnumValN(JITLinkerKind::JITLink, "jitlink",
  112. "Orc-specific linker")));
  113. cl::opt<std::string> OrcRuntime("orc-runtime",
  114. cl::desc("Use ORC runtime from given path"),
  115. cl::init(""));
  116. cl::opt<unsigned>
  117. LazyJITCompileThreads("compile-threads",
  118. cl::desc("Choose the number of compile threads "
  119. "(jit-kind=orc-lazy only)"),
  120. cl::init(0));
  121. cl::list<std::string>
  122. ThreadEntryPoints("thread-entry",
  123. cl::desc("calls the given entry-point on a new thread "
  124. "(jit-kind=orc-lazy only)"));
  125. cl::opt<bool> PerModuleLazy(
  126. "per-module-lazy",
  127. cl::desc("Performs lazy compilation on whole module boundaries "
  128. "rather than individual functions"),
  129. cl::init(false));
  130. cl::list<std::string>
  131. JITDylibs("jd",
  132. cl::desc("Specifies the JITDylib to be used for any subsequent "
  133. "-extra-module arguments."));
  134. cl::list<std::string>
  135. Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"));
  136. // The MCJIT supports building for a target address space separate from
  137. // the JIT compilation process. Use a forked process and a copying
  138. // memory manager with IPC to execute using this functionality.
  139. cl::opt<bool> RemoteMCJIT("remote-mcjit",
  140. cl::desc("Execute MCJIT'ed code in a separate process."),
  141. cl::init(false));
  142. // Manually specify the child process for remote execution. This overrides
  143. // the simulated remote execution that allocates address space for child
  144. // execution. The child process will be executed and will communicate with
  145. // lli via stdin/stdout pipes.
  146. cl::opt<std::string>
  147. ChildExecPath("mcjit-remote-process",
  148. cl::desc("Specify the filename of the process to launch "
  149. "for remote MCJIT execution. If none is specified,"
  150. "\n\tremote execution will be simulated in-process."),
  151. cl::value_desc("filename"), cl::init(""));
  152. // Determine optimization level.
  153. cl::opt<char> OptLevel("O",
  154. cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  155. "(default = '-O2')"),
  156. cl::Prefix, cl::init('2'));
  157. cl::opt<std::string>
  158. TargetTriple("mtriple", cl::desc("Override target triple for module"));
  159. cl::opt<std::string>
  160. EntryFunc("entry-function",
  161. cl::desc("Specify the entry function (default = 'main') "
  162. "of the executable"),
  163. cl::value_desc("function"),
  164. cl::init("main"));
  165. cl::list<std::string>
  166. ExtraModules("extra-module",
  167. cl::desc("Extra modules to be loaded"),
  168. cl::value_desc("input bitcode"));
  169. cl::list<std::string>
  170. ExtraObjects("extra-object",
  171. cl::desc("Extra object files to be loaded"),
  172. cl::value_desc("input object"));
  173. cl::list<std::string>
  174. ExtraArchives("extra-archive",
  175. cl::desc("Extra archive files to be loaded"),
  176. cl::value_desc("input archive"));
  177. cl::opt<bool>
  178. EnableCacheManager("enable-cache-manager",
  179. cl::desc("Use cache manager to save/load modules"),
  180. cl::init(false));
  181. cl::opt<std::string>
  182. ObjectCacheDir("object-cache-dir",
  183. cl::desc("Directory to store cached object files "
  184. "(must be user writable)"),
  185. cl::init(""));
  186. cl::opt<std::string>
  187. FakeArgv0("fake-argv0",
  188. cl::desc("Override the 'argv[0]' value passed into the executing"
  189. " program"), cl::value_desc("executable"));
  190. cl::opt<bool>
  191. DisableCoreFiles("disable-core-files", cl::Hidden,
  192. cl::desc("Disable emission of core files if possible"));
  193. cl::opt<bool>
  194. NoLazyCompilation("disable-lazy-compilation",
  195. cl::desc("Disable JIT lazy compilation"),
  196. cl::init(false));
  197. cl::opt<bool>
  198. GenerateSoftFloatCalls("soft-float",
  199. cl::desc("Generate software floating point library calls"),
  200. cl::init(false));
  201. cl::opt<bool> NoProcessSymbols(
  202. "no-process-syms",
  203. cl::desc("Do not resolve lli process symbols in JIT'd code"),
  204. cl::init(false));
  205. enum class LLJITPlatform { Inactive, DetectHost, ORC, GenericIR };
  206. cl::opt<LLJITPlatform>
  207. Platform("lljit-platform", cl::desc("Platform to use with LLJIT"),
  208. cl::init(LLJITPlatform::DetectHost),
  209. cl::values(clEnumValN(LLJITPlatform::DetectHost, "DetectHost",
  210. "Select based on JIT target triple"),
  211. clEnumValN(LLJITPlatform::ORC, "ORC",
  212. "Use ORCPlatform with the ORC runtime"),
  213. clEnumValN(LLJITPlatform::GenericIR, "GenericIR",
  214. "Use LLJITGenericIRPlatform"),
  215. clEnumValN(LLJITPlatform::Inactive, "Inactive",
  216. "Disable platform support explicitly")),
  217. cl::Hidden);
  218. enum class DumpKind {
  219. NoDump,
  220. DumpFuncsToStdOut,
  221. DumpModsToStdOut,
  222. DumpModsToDisk
  223. };
  224. cl::opt<DumpKind> OrcDumpKind(
  225. "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
  226. cl::init(DumpKind::NoDump),
  227. cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
  228. "Don't dump anything."),
  229. clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
  230. "Dump function names to stdout."),
  231. clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
  232. "Dump modules to stdout."),
  233. clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
  234. "Dump modules to the current "
  235. "working directory. (WARNING: "
  236. "will overwrite existing files).")),
  237. cl::Hidden);
  238. cl::list<BuiltinFunctionKind> GenerateBuiltinFunctions(
  239. "generate",
  240. cl::desc("Provide built-in functions for access by JITed code "
  241. "(jit-kind=orc-lazy only)"),
  242. cl::values(clEnumValN(BuiltinFunctionKind::DumpDebugDescriptor,
  243. "__dump_jit_debug_descriptor",
  244. "Dump __jit_debug_descriptor contents to stdout"),
  245. clEnumValN(BuiltinFunctionKind::DumpDebugObjects,
  246. "__dump_jit_debug_objects",
  247. "Dump __jit_debug_descriptor in-memory debug "
  248. "objects as tool output")),
  249. cl::Hidden);
  250. ExitOnError ExitOnErr;
  251. }
  252. LLVM_ATTRIBUTE_USED void linkComponents() {
  253. errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper
  254. << (void *)&llvm_orc_deregisterEHFrameSectionWrapper
  255. << (void *)&llvm_orc_registerJITLoaderGDBWrapper
  256. << (void *)&llvm_orc_registerJITLoaderGDBAllocAction;
  257. }
  258. //===----------------------------------------------------------------------===//
  259. // Object cache
  260. //
  261. // This object cache implementation writes cached objects to disk to the
  262. // directory specified by CacheDir, using a filename provided in the module
  263. // descriptor. The cache tries to load a saved object using that path if the
  264. // file exists. CacheDir defaults to "", in which case objects are cached
  265. // alongside their originating bitcodes.
  266. //
  267. class LLIObjectCache : public ObjectCache {
  268. public:
  269. LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
  270. // Add trailing '/' to cache dir if necessary.
  271. if (!this->CacheDir.empty() &&
  272. this->CacheDir[this->CacheDir.size() - 1] != '/')
  273. this->CacheDir += '/';
  274. }
  275. ~LLIObjectCache() override {}
  276. void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
  277. const std::string &ModuleID = M->getModuleIdentifier();
  278. std::string CacheName;
  279. if (!getCacheFilename(ModuleID, CacheName))
  280. return;
  281. if (!CacheDir.empty()) { // Create user-defined cache dir.
  282. SmallString<128> dir(sys::path::parent_path(CacheName));
  283. sys::fs::create_directories(Twine(dir));
  284. }
  285. std::error_code EC;
  286. raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
  287. outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
  288. outfile.close();
  289. }
  290. std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
  291. const std::string &ModuleID = M->getModuleIdentifier();
  292. std::string CacheName;
  293. if (!getCacheFilename(ModuleID, CacheName))
  294. return nullptr;
  295. // Load the object from the cache filename
  296. ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
  297. MemoryBuffer::getFile(CacheName, /*IsText=*/false,
  298. /*RequiresNullTerminator=*/false);
  299. // If the file isn't there, that's OK.
  300. if (!IRObjectBuffer)
  301. return nullptr;
  302. // MCJIT will want to write into this buffer, and we don't want that
  303. // because the file has probably just been mmapped. Instead we make
  304. // a copy. The filed-based buffer will be released when it goes
  305. // out of scope.
  306. return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
  307. }
  308. private:
  309. std::string CacheDir;
  310. bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
  311. std::string Prefix("file:");
  312. size_t PrefixLength = Prefix.length();
  313. if (ModID.substr(0, PrefixLength) != Prefix)
  314. return false;
  315. std::string CacheSubdir = ModID.substr(PrefixLength);
  316. // Transform "X:\foo" => "/X\foo" for convenience on Windows.
  317. if (is_style_windows(llvm::sys::path::Style::native) &&
  318. isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
  319. CacheSubdir[1] = CacheSubdir[0];
  320. CacheSubdir[0] = '/';
  321. }
  322. CacheName = CacheDir + CacheSubdir;
  323. size_t pos = CacheName.rfind('.');
  324. CacheName.replace(pos, CacheName.length() - pos, ".o");
  325. return true;
  326. }
  327. };
  328. // On Mingw and Cygwin, an external symbol named '__main' is called from the
  329. // generated 'main' function to allow static initialization. To avoid linking
  330. // problems with remote targets (because lli's remote target support does not
  331. // currently handle external linking) we add a secondary module which defines
  332. // an empty '__main' function.
  333. static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
  334. StringRef TargetTripleStr) {
  335. IRBuilder<> Builder(Context);
  336. Triple TargetTriple(TargetTripleStr);
  337. // Create a new module.
  338. std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
  339. M->setTargetTriple(TargetTripleStr);
  340. // Create an empty function named "__main".
  341. Type *ReturnTy;
  342. if (TargetTriple.isArch64Bit())
  343. ReturnTy = Type::getInt64Ty(Context);
  344. else
  345. ReturnTy = Type::getInt32Ty(Context);
  346. Function *Result =
  347. Function::Create(FunctionType::get(ReturnTy, {}, false),
  348. GlobalValue::ExternalLinkage, "__main", M.get());
  349. BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
  350. Builder.SetInsertPoint(BB);
  351. Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
  352. Builder.CreateRet(ReturnVal);
  353. // Add this new module to the ExecutionEngine.
  354. EE.addModule(std::move(M));
  355. }
  356. CodeGenOpt::Level getOptLevel() {
  357. if (auto Level = CodeGenOpt::parseLevel(OptLevel))
  358. return *Level;
  359. WithColor::error(errs(), "lli") << "invalid optimization level.\n";
  360. exit(1);
  361. }
  362. [[noreturn]] static void reportError(SMDiagnostic Err, const char *ProgName) {
  363. Err.print(ProgName, errs());
  364. exit(1);
  365. }
  366. Error loadDylibs();
  367. int runOrcJIT(const char *ProgName);
  368. void disallowOrcOptions();
  369. Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote();
  370. //===----------------------------------------------------------------------===//
  371. // main Driver function
  372. //
  373. int main(int argc, char **argv, char * const *envp) {
  374. InitLLVM X(argc, argv);
  375. if (argc > 1)
  376. ExitOnErr.setBanner(std::string(argv[0]) + ": ");
  377. // If we have a native target, initialize it to ensure it is linked in and
  378. // usable by the JIT.
  379. InitializeNativeTarget();
  380. InitializeNativeTargetAsmPrinter();
  381. InitializeNativeTargetAsmParser();
  382. cl::ParseCommandLineOptions(argc, argv,
  383. "llvm interpreter & dynamic compiler\n");
  384. // If the user doesn't want core files, disable them.
  385. if (DisableCoreFiles)
  386. sys::Process::PreventCoreFiles();
  387. ExitOnErr(loadDylibs());
  388. if (UseJITKind == JITKind::MCJIT)
  389. disallowOrcOptions();
  390. else
  391. return runOrcJIT(argv[0]);
  392. // Old lli implementation based on ExecutionEngine and MCJIT.
  393. LLVMContext Context;
  394. // Load the bitcode...
  395. SMDiagnostic Err;
  396. std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
  397. Module *Mod = Owner.get();
  398. if (!Mod)
  399. reportError(Err, argv[0]);
  400. if (EnableCacheManager) {
  401. std::string CacheName("file:");
  402. CacheName.append(InputFile);
  403. Mod->setModuleIdentifier(CacheName);
  404. }
  405. // If not jitting lazily, load the whole bitcode file eagerly too.
  406. if (NoLazyCompilation) {
  407. // Use *argv instead of argv[0] to work around a wrong GCC warning.
  408. ExitOnError ExitOnErr(std::string(*argv) +
  409. ": bitcode didn't read correctly: ");
  410. ExitOnErr(Mod->materializeAll());
  411. }
  412. std::string ErrorMsg;
  413. EngineBuilder builder(std::move(Owner));
  414. builder.setMArch(codegen::getMArch());
  415. builder.setMCPU(codegen::getCPUStr());
  416. builder.setMAttrs(codegen::getFeatureList());
  417. if (auto RM = codegen::getExplicitRelocModel())
  418. builder.setRelocationModel(*RM);
  419. if (auto CM = codegen::getExplicitCodeModel())
  420. builder.setCodeModel(*CM);
  421. builder.setErrorStr(&ErrorMsg);
  422. builder.setEngineKind(ForceInterpreter
  423. ? EngineKind::Interpreter
  424. : EngineKind::JIT);
  425. // If we are supposed to override the target triple, do so now.
  426. if (!TargetTriple.empty())
  427. Mod->setTargetTriple(Triple::normalize(TargetTriple));
  428. // Enable MCJIT if desired.
  429. RTDyldMemoryManager *RTDyldMM = nullptr;
  430. if (!ForceInterpreter) {
  431. if (RemoteMCJIT)
  432. RTDyldMM = new ForwardingMemoryManager();
  433. else
  434. RTDyldMM = new SectionMemoryManager();
  435. // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
  436. // RTDyldMM: We still use it below, even though we don't own it.
  437. builder.setMCJITMemoryManager(
  438. std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
  439. } else if (RemoteMCJIT) {
  440. WithColor::error(errs(), argv[0])
  441. << "remote process execution does not work with the interpreter.\n";
  442. exit(1);
  443. }
  444. builder.setOptLevel(getOptLevel());
  445. TargetOptions Options =
  446. codegen::InitTargetOptionsFromCodeGenFlags(Triple(TargetTriple));
  447. if (codegen::getFloatABIForCalls() != FloatABI::Default)
  448. Options.FloatABIType = codegen::getFloatABIForCalls();
  449. builder.setTargetOptions(Options);
  450. std::unique_ptr<ExecutionEngine> EE(builder.create());
  451. if (!EE) {
  452. if (!ErrorMsg.empty())
  453. WithColor::error(errs(), argv[0])
  454. << "error creating EE: " << ErrorMsg << "\n";
  455. else
  456. WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
  457. exit(1);
  458. }
  459. std::unique_ptr<LLIObjectCache> CacheManager;
  460. if (EnableCacheManager) {
  461. CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
  462. EE->setObjectCache(CacheManager.get());
  463. }
  464. // Load any additional modules specified on the command line.
  465. for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
  466. std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
  467. if (!XMod)
  468. reportError(Err, argv[0]);
  469. if (EnableCacheManager) {
  470. std::string CacheName("file:");
  471. CacheName.append(ExtraModules[i]);
  472. XMod->setModuleIdentifier(CacheName);
  473. }
  474. EE->addModule(std::move(XMod));
  475. }
  476. for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
  477. Expected<object::OwningBinary<object::ObjectFile>> Obj =
  478. object::ObjectFile::createObjectFile(ExtraObjects[i]);
  479. if (!Obj) {
  480. // TODO: Actually report errors helpfully.
  481. consumeError(Obj.takeError());
  482. reportError(Err, argv[0]);
  483. }
  484. object::OwningBinary<object::ObjectFile> &O = Obj.get();
  485. EE->addObjectFile(std::move(O));
  486. }
  487. for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
  488. ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
  489. MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
  490. if (!ArBufOrErr)
  491. reportError(Err, argv[0]);
  492. std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
  493. Expected<std::unique_ptr<object::Archive>> ArOrErr =
  494. object::Archive::create(ArBuf->getMemBufferRef());
  495. if (!ArOrErr) {
  496. std::string Buf;
  497. raw_string_ostream OS(Buf);
  498. logAllUnhandledErrors(ArOrErr.takeError(), OS);
  499. OS.flush();
  500. errs() << Buf;
  501. exit(1);
  502. }
  503. std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
  504. object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
  505. EE->addArchive(std::move(OB));
  506. }
  507. // If the target is Cygwin/MingW and we are generating remote code, we
  508. // need an extra module to help out with linking.
  509. if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
  510. addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
  511. }
  512. // The following functions have no effect if their respective profiling
  513. // support wasn't enabled in the build configuration.
  514. EE->RegisterJITEventListener(
  515. JITEventListener::createOProfileJITEventListener());
  516. EE->RegisterJITEventListener(
  517. JITEventListener::createIntelJITEventListener());
  518. if (!RemoteMCJIT)
  519. EE->RegisterJITEventListener(
  520. JITEventListener::createPerfJITEventListener());
  521. if (!NoLazyCompilation && RemoteMCJIT) {
  522. WithColor::warning(errs(), argv[0])
  523. << "remote mcjit does not support lazy compilation\n";
  524. NoLazyCompilation = true;
  525. }
  526. EE->DisableLazyCompilation(NoLazyCompilation);
  527. // If the user specifically requested an argv[0] to pass into the program,
  528. // do it now.
  529. if (!FakeArgv0.empty()) {
  530. InputFile = static_cast<std::string>(FakeArgv0);
  531. } else {
  532. // Otherwise, if there is a .bc suffix on the executable strip it off, it
  533. // might confuse the program.
  534. if (StringRef(InputFile).endswith(".bc"))
  535. InputFile.erase(InputFile.length() - 3);
  536. }
  537. // Add the module's name to the start of the vector of arguments to main().
  538. InputArgv.insert(InputArgv.begin(), InputFile);
  539. // Call the main function from M as if its signature were:
  540. // int main (int argc, char **argv, const char **envp)
  541. // using the contents of Args to determine argc & argv, and the contents of
  542. // EnvVars to determine envp.
  543. //
  544. Function *EntryFn = Mod->getFunction(EntryFunc);
  545. if (!EntryFn) {
  546. WithColor::error(errs(), argv[0])
  547. << '\'' << EntryFunc << "\' function not found in module.\n";
  548. return -1;
  549. }
  550. // Reset errno to zero on entry to main.
  551. errno = 0;
  552. int Result = -1;
  553. // Sanity check use of remote-jit: LLI currently only supports use of the
  554. // remote JIT on Unix platforms.
  555. if (RemoteMCJIT) {
  556. #ifndef LLVM_ON_UNIX
  557. WithColor::warning(errs(), argv[0])
  558. << "host does not support external remote targets.\n";
  559. WithColor::note() << "defaulting to local execution\n";
  560. return -1;
  561. #else
  562. if (ChildExecPath.empty()) {
  563. WithColor::error(errs(), argv[0])
  564. << "-remote-mcjit requires -mcjit-remote-process.\n";
  565. exit(1);
  566. } else if (!sys::fs::can_execute(ChildExecPath)) {
  567. WithColor::error(errs(), argv[0])
  568. << "unable to find usable child executable: '" << ChildExecPath
  569. << "'\n";
  570. return -1;
  571. }
  572. #endif
  573. }
  574. std::unique_ptr<orc::ExecutorProcessControl> EPC =
  575. RemoteMCJIT ? ExitOnErr(launchRemote())
  576. : ExitOnErr(orc::SelfExecutorProcessControl::Create());
  577. if (!RemoteMCJIT) {
  578. // If the program doesn't explicitly call exit, we will need the Exit
  579. // function later on to make an explicit call, so get the function now.
  580. FunctionCallee Exit = Mod->getOrInsertFunction(
  581. "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context));
  582. // Run static constructors.
  583. if (!ForceInterpreter) {
  584. // Give MCJIT a chance to apply relocations and set page permissions.
  585. EE->finalizeObject();
  586. }
  587. EE->runStaticConstructorsDestructors(false);
  588. // Trigger compilation separately so code regions that need to be
  589. // invalidated will be known.
  590. (void)EE->getPointerToFunction(EntryFn);
  591. // Clear instruction cache before code will be executed.
  592. if (RTDyldMM)
  593. static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
  594. // Run main.
  595. Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
  596. // Run static destructors.
  597. EE->runStaticConstructorsDestructors(true);
  598. // If the program didn't call exit explicitly, we should call it now.
  599. // This ensures that any atexit handlers get called correctly.
  600. if (Function *ExitF =
  601. dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) {
  602. if (ExitF->getFunctionType() == Exit.getFunctionType()) {
  603. std::vector<GenericValue> Args;
  604. GenericValue ResultGV;
  605. ResultGV.IntVal = APInt(32, Result);
  606. Args.push_back(ResultGV);
  607. EE->runFunction(ExitF, Args);
  608. WithColor::error(errs(), argv[0])
  609. << "exit(" << Result << ") returned!\n";
  610. abort();
  611. }
  612. }
  613. WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n";
  614. abort();
  615. } else {
  616. // else == "if (RemoteMCJIT)"
  617. // Remote target MCJIT doesn't (yet) support static constructors. No reason
  618. // it couldn't. This is a limitation of the LLI implementation, not the
  619. // MCJIT itself. FIXME.
  620. // Create a remote memory manager.
  621. auto RemoteMM = ExitOnErr(
  622. orc::EPCGenericRTDyldMemoryManager::CreateWithDefaultBootstrapSymbols(
  623. *EPC));
  624. // Forward MCJIT's memory manager calls to the remote memory manager.
  625. static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
  626. std::move(RemoteMM));
  627. // Forward MCJIT's symbol resolution calls to the remote.
  628. static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
  629. ExitOnErr(RemoteResolver::Create(*EPC)));
  630. // Grab the target address of the JIT'd main function on the remote and call
  631. // it.
  632. // FIXME: argv and envp handling.
  633. auto Entry =
  634. orc::ExecutorAddr(EE->getFunctionAddress(EntryFn->getName().str()));
  635. EE->finalizeObject();
  636. LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
  637. << format("%llx", Entry.getValue()) << "\n");
  638. Result = ExitOnErr(EPC->runAsMain(Entry, {}));
  639. // Like static constructors, the remote target MCJIT support doesn't handle
  640. // this yet. It could. FIXME.
  641. // Delete the EE - we need to tear it down *before* we terminate the session
  642. // with the remote, otherwise it'll crash when it tries to release resources
  643. // on a remote that has already been disconnected.
  644. EE.reset();
  645. // Signal the remote target that we're done JITing.
  646. ExitOnErr(EPC->disconnect());
  647. }
  648. return Result;
  649. }
  650. static std::function<void(Module &)> createDebugDumper() {
  651. switch (OrcDumpKind) {
  652. case DumpKind::NoDump:
  653. return [](Module &M) {};
  654. case DumpKind::DumpFuncsToStdOut:
  655. return [](Module &M) {
  656. printf("[ ");
  657. for (const auto &F : M) {
  658. if (F.isDeclaration())
  659. continue;
  660. if (F.hasName()) {
  661. std::string Name(std::string(F.getName()));
  662. printf("%s ", Name.c_str());
  663. } else
  664. printf("<anon> ");
  665. }
  666. printf("]\n");
  667. };
  668. case DumpKind::DumpModsToStdOut:
  669. return [](Module &M) {
  670. outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";
  671. };
  672. case DumpKind::DumpModsToDisk:
  673. return [](Module &M) {
  674. std::error_code EC;
  675. raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC,
  676. sys::fs::OF_TextWithCRLF);
  677. if (EC) {
  678. errs() << "Couldn't open " << M.getModuleIdentifier()
  679. << " for dumping.\nError:" << EC.message() << "\n";
  680. exit(1);
  681. }
  682. Out << M;
  683. };
  684. }
  685. llvm_unreachable("Unknown DumpKind");
  686. }
  687. Error loadDylibs() {
  688. for (const auto &Dylib : Dylibs) {
  689. std::string ErrMsg;
  690. if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
  691. return make_error<StringError>(ErrMsg, inconvertibleErrorCode());
  692. }
  693. return Error::success();
  694. }
  695. static void exitOnLazyCallThroughFailure() { exit(1); }
  696. Expected<orc::ThreadSafeModule>
  697. loadModule(StringRef Path, orc::ThreadSafeContext TSCtx) {
  698. SMDiagnostic Err;
  699. auto M = parseIRFile(Path, Err, *TSCtx.getContext());
  700. if (!M) {
  701. std::string ErrMsg;
  702. {
  703. raw_string_ostream ErrMsgStream(ErrMsg);
  704. Err.print("lli", ErrMsgStream);
  705. }
  706. return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
  707. }
  708. if (EnableCacheManager)
  709. M->setModuleIdentifier("file:" + M->getModuleIdentifier());
  710. return orc::ThreadSafeModule(std::move(M), std::move(TSCtx));
  711. }
  712. int runOrcJIT(const char *ProgName) {
  713. // Start setting up the JIT environment.
  714. // Parse the main module.
  715. orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
  716. auto MainModule = ExitOnErr(loadModule(InputFile, TSCtx));
  717. // Get TargetTriple and DataLayout from the main module if they're explicitly
  718. // set.
  719. std::optional<Triple> TT;
  720. std::optional<DataLayout> DL;
  721. MainModule.withModuleDo([&](Module &M) {
  722. if (!M.getTargetTriple().empty())
  723. TT = Triple(M.getTargetTriple());
  724. if (!M.getDataLayout().isDefault())
  725. DL = M.getDataLayout();
  726. });
  727. orc::LLLazyJITBuilder Builder;
  728. Builder.setJITTargetMachineBuilder(
  729. TT ? orc::JITTargetMachineBuilder(*TT)
  730. : ExitOnErr(orc::JITTargetMachineBuilder::detectHost()));
  731. TT = Builder.getJITTargetMachineBuilder()->getTargetTriple();
  732. if (DL)
  733. Builder.setDataLayout(DL);
  734. if (!codegen::getMArch().empty())
  735. Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(
  736. codegen::getMArch());
  737. Builder.getJITTargetMachineBuilder()
  738. ->setCPU(codegen::getCPUStr())
  739. .addFeatures(codegen::getFeatureList())
  740. .setRelocationModel(codegen::getExplicitRelocModel())
  741. .setCodeModel(codegen::getExplicitCodeModel());
  742. // FIXME: Setting a dummy call-through manager in non-lazy mode prevents the
  743. // JIT builder to instantiate a default (which would fail with an error for
  744. // unsupported architectures).
  745. if (UseJITKind != JITKind::OrcLazy) {
  746. auto ES = std::make_unique<orc::ExecutionSession>(
  747. ExitOnErr(orc::SelfExecutorProcessControl::Create()));
  748. Builder.setLazyCallthroughManager(
  749. std::make_unique<orc::LazyCallThroughManager>(*ES, 0, nullptr));
  750. Builder.setExecutionSession(std::move(ES));
  751. }
  752. Builder.setLazyCompileFailureAddr(
  753. orc::ExecutorAddr::fromPtr(exitOnLazyCallThroughFailure));
  754. Builder.setNumCompileThreads(LazyJITCompileThreads);
  755. // If the object cache is enabled then set a custom compile function
  756. // creator to use the cache.
  757. std::unique_ptr<LLIObjectCache> CacheManager;
  758. if (EnableCacheManager) {
  759. CacheManager = std::make_unique<LLIObjectCache>(ObjectCacheDir);
  760. Builder.setCompileFunctionCreator(
  761. [&](orc::JITTargetMachineBuilder JTMB)
  762. -> Expected<std::unique_ptr<orc::IRCompileLayer::IRCompiler>> {
  763. if (LazyJITCompileThreads > 0)
  764. return std::make_unique<orc::ConcurrentIRCompiler>(std::move(JTMB),
  765. CacheManager.get());
  766. auto TM = JTMB.createTargetMachine();
  767. if (!TM)
  768. return TM.takeError();
  769. return std::make_unique<orc::TMOwningSimpleCompiler>(std::move(*TM),
  770. CacheManager.get());
  771. });
  772. }
  773. // Set up LLJIT platform.
  774. LLJITPlatform P = Platform;
  775. if (P == LLJITPlatform::DetectHost) {
  776. if (JITLinker == JITLinkerKind::JITLink && !OrcRuntime.empty() &&
  777. (TT->isOSBinFormatMachO() || TT->isOSBinFormatELF()))
  778. P = LLJITPlatform::ORC;
  779. else
  780. P = LLJITPlatform::GenericIR;
  781. }
  782. switch (P) {
  783. case LLJITPlatform::ORC:
  784. Builder.setPlatformSetUp(orc::setUpOrcPlatform);
  785. break;
  786. case LLJITPlatform::GenericIR:
  787. // Nothing to do: LLJITBuilder will use this by default.
  788. break;
  789. case LLJITPlatform::Inactive:
  790. Builder.setPlatformSetUp(orc::setUpInactivePlatform);
  791. break;
  792. default:
  793. llvm_unreachable("Unrecognized platform value");
  794. }
  795. std::unique_ptr<orc::ExecutorProcessControl> EPC = nullptr;
  796. if (JITLinker == JITLinkerKind::JITLink) {
  797. EPC = ExitOnErr(orc::SelfExecutorProcessControl::Create(
  798. std::make_shared<orc::SymbolStringPool>()));
  799. Builder.setObjectLinkingLayerCreator([&EPC, &P](orc::ExecutionSession &ES,
  800. const Triple &TT) {
  801. auto L = std::make_unique<orc::ObjectLinkingLayer>(ES, EPC->getMemMgr());
  802. if (P != LLJITPlatform::ORC) {
  803. L->addPlugin(std::make_unique<orc::EHFrameRegistrationPlugin>(
  804. ES, ExitOnErr(orc::EPCEHFrameRegistrar::Create(ES))));
  805. L->addPlugin(std::make_unique<orc::DebugObjectManagerPlugin>(
  806. ES, ExitOnErr(orc::createJITLoaderGDBRegistrar(ES))));
  807. }
  808. return L;
  809. });
  810. }
  811. auto J = ExitOnErr(Builder.create());
  812. auto *ObjLayer = &J->getObjLinkingLayer();
  813. if (auto *RTDyldObjLayer = dyn_cast<orc::RTDyldObjectLinkingLayer>(ObjLayer))
  814. RTDyldObjLayer->registerJITEventListener(
  815. *JITEventListener::createGDBRegistrationListener());
  816. if (PerModuleLazy)
  817. J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
  818. auto Dump = createDebugDumper();
  819. J->getIRTransformLayer().setTransform(
  820. [&](orc::ThreadSafeModule TSM,
  821. const orc::MaterializationResponsibility &R) {
  822. TSM.withModuleDo([&](Module &M) {
  823. if (verifyModule(M, &dbgs())) {
  824. dbgs() << "Bad module: " << &M << "\n";
  825. exit(1);
  826. }
  827. Dump(M);
  828. });
  829. return TSM;
  830. });
  831. orc::MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout());
  832. // Unless they've been explicitly disabled, make process symbols available to
  833. // JIT'd code.
  834. if (!NoProcessSymbols)
  835. J->getMainJITDylib().addGenerator(
  836. ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(
  837. J->getDataLayout().getGlobalPrefix(),
  838. [MainName = Mangle("main")](const orc::SymbolStringPtr &Name) {
  839. return Name != MainName;
  840. })));
  841. if (GenerateBuiltinFunctions.size() > 0)
  842. J->getMainJITDylib().addGenerator(
  843. std::make_unique<LLIBuiltinFunctionGenerator>(GenerateBuiltinFunctions,
  844. Mangle));
  845. if (P == LLJITPlatform::ORC) {
  846. if (auto *OLL = llvm::dyn_cast<llvm::orc::ObjectLinkingLayer>(ObjLayer)) {
  847. auto &ES = J->getExecutionSession();
  848. if (TT->isOSBinFormatMachO()) {
  849. if (auto P = llvm::orc::MachOPlatform::Create(
  850. ES, *OLL, J->getMainJITDylib(), OrcRuntime.c_str()))
  851. ES.setPlatform(std::move(*P));
  852. else
  853. ExitOnErr(P.takeError());
  854. } else if (TT->isOSBinFormatELF()) {
  855. if (auto P = llvm::orc::ELFNixPlatform::Create(
  856. ES, *OLL, J->getMainJITDylib(), OrcRuntime.c_str()))
  857. ES.setPlatform(std::move(*P));
  858. else
  859. ExitOnErr(P.takeError());
  860. } else {
  861. errs() << "No ORC platform support\n";
  862. exit(1);
  863. }
  864. } else {
  865. errs() << "ORC platform requires JITLink\n";
  866. exit(1);
  867. }
  868. }
  869. // Regular modules are greedy: They materialize as a whole and trigger
  870. // materialization for all required symbols recursively. Lazy modules go
  871. // through partitioning and they replace outgoing calls with reexport stubs
  872. // that resolve on call-through.
  873. auto AddModule = [&](orc::JITDylib &JD, orc::ThreadSafeModule M) {
  874. return UseJITKind == JITKind::OrcLazy ? J->addLazyIRModule(JD, std::move(M))
  875. : J->addIRModule(JD, std::move(M));
  876. };
  877. // Add the main module.
  878. ExitOnErr(AddModule(J->getMainJITDylib(), std::move(MainModule)));
  879. // Create JITDylibs and add any extra modules.
  880. {
  881. // Create JITDylibs, keep a map from argument index to dylib. We will use
  882. // -extra-module argument indexes to determine what dylib to use for each
  883. // -extra-module.
  884. std::map<unsigned, orc::JITDylib *> IdxToDylib;
  885. IdxToDylib[0] = &J->getMainJITDylib();
  886. for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
  887. JDItr != JDEnd; ++JDItr) {
  888. orc::JITDylib *JD = J->getJITDylibByName(*JDItr);
  889. if (!JD) {
  890. JD = &ExitOnErr(J->createJITDylib(*JDItr));
  891. J->getMainJITDylib().addToLinkOrder(*JD);
  892. JD->addToLinkOrder(J->getMainJITDylib());
  893. }
  894. IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD;
  895. }
  896. for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
  897. EMItr != EMEnd; ++EMItr) {
  898. auto M = ExitOnErr(loadModule(*EMItr, TSCtx));
  899. auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
  900. assert(EMIdx != 0 && "ExtraModule should have index > 0");
  901. auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
  902. auto &JD = *JDItr->second;
  903. ExitOnErr(AddModule(JD, std::move(M)));
  904. }
  905. for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();
  906. EAItr != EAEnd; ++EAItr) {
  907. auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin());
  908. assert(EAIdx != 0 && "ExtraArchive should have index > 0");
  909. auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx));
  910. auto &JD = *JDItr->second;
  911. JD.addGenerator(ExitOnErr(orc::StaticLibraryDefinitionGenerator::Load(
  912. J->getObjLinkingLayer(), EAItr->c_str(), *TT)));
  913. }
  914. }
  915. // Add the objects.
  916. for (auto &ObjPath : ExtraObjects) {
  917. auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
  918. ExitOnErr(J->addObjectFile(std::move(Obj)));
  919. }
  920. // Run any static constructors.
  921. ExitOnErr(J->initialize(J->getMainJITDylib()));
  922. // Run any -thread-entry points.
  923. std::vector<std::thread> AltEntryThreads;
  924. for (auto &ThreadEntryPoint : ThreadEntryPoints) {
  925. auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
  926. typedef void (*EntryPointPtr)();
  927. auto EntryPoint = EntryPointSym.toPtr<EntryPointPtr>();
  928. AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
  929. }
  930. // Resolve and run the main function.
  931. auto MainAddr = ExitOnErr(J->lookup(EntryFunc));
  932. int Result;
  933. if (EPC) {
  934. // ExecutorProcessControl-based execution with JITLink.
  935. Result = ExitOnErr(EPC->runAsMain(MainAddr, InputArgv));
  936. } else {
  937. // Manual in-process execution with RuntimeDyld.
  938. using MainFnTy = int(int, char *[]);
  939. auto MainFn = MainAddr.toPtr<MainFnTy *>();
  940. Result = orc::runAsMain(MainFn, InputArgv, StringRef(InputFile));
  941. }
  942. // Wait for -entry-point threads.
  943. for (auto &AltEntryThread : AltEntryThreads)
  944. AltEntryThread.join();
  945. // Run destructors.
  946. ExitOnErr(J->deinitialize(J->getMainJITDylib()));
  947. return Result;
  948. }
  949. void disallowOrcOptions() {
  950. // Make sure nobody used an orc-lazy specific option accidentally.
  951. if (LazyJITCompileThreads != 0) {
  952. errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
  953. exit(1);
  954. }
  955. if (!ThreadEntryPoints.empty()) {
  956. errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
  957. exit(1);
  958. }
  959. if (PerModuleLazy) {
  960. errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
  961. exit(1);
  962. }
  963. }
  964. Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote() {
  965. #ifndef LLVM_ON_UNIX
  966. llvm_unreachable("launchRemote not supported on non-Unix platforms");
  967. #else
  968. int PipeFD[2][2];
  969. pid_t ChildPID;
  970. // Create two pipes.
  971. if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
  972. perror("Error creating pipe: ");
  973. ChildPID = fork();
  974. if (ChildPID == 0) {
  975. // In the child...
  976. // Close the parent ends of the pipes
  977. close(PipeFD[0][1]);
  978. close(PipeFD[1][0]);
  979. // Execute the child process.
  980. std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
  981. {
  982. ChildPath.reset(new char[ChildExecPath.size() + 1]);
  983. std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
  984. ChildPath[ChildExecPath.size()] = '\0';
  985. std::string ChildInStr = utostr(PipeFD[0][0]);
  986. ChildIn.reset(new char[ChildInStr.size() + 1]);
  987. std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
  988. ChildIn[ChildInStr.size()] = '\0';
  989. std::string ChildOutStr = utostr(PipeFD[1][1]);
  990. ChildOut.reset(new char[ChildOutStr.size() + 1]);
  991. std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
  992. ChildOut[ChildOutStr.size()] = '\0';
  993. }
  994. char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
  995. int rc = execv(ChildExecPath.c_str(), args);
  996. if (rc != 0)
  997. perror("Error executing child process: ");
  998. llvm_unreachable("Error executing child process");
  999. }
  1000. // else we're the parent...
  1001. // Close the child ends of the pipes
  1002. close(PipeFD[0][0]);
  1003. close(PipeFD[1][1]);
  1004. // Return a SimpleRemoteEPC instance connected to our end of the pipes.
  1005. return orc::SimpleRemoteEPC::Create<orc::FDSimpleRemoteEPCTransport>(
  1006. std::make_unique<llvm::orc::InPlaceTaskDispatcher>(),
  1007. llvm::orc::SimpleRemoteEPC::Setup(), PipeFD[1][0], PipeFD[0][1]);
  1008. #endif
  1009. }