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
15#include "ForwardingMemoryManager.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Bitcode/BitcodeReader.h"
18#include "llvm/CodeGen/CommandFlags.h"
19#include "llvm/CodeGen/LinkAllCodegenComponents.h"
20#include "llvm/Config/llvm-config.h"
21#include "llvm/ExecutionEngine/GenericValue.h"
22#include "llvm/ExecutionEngine/Interpreter.h"
23#include "llvm/ExecutionEngine/JITEventListener.h"
24#include "llvm/ExecutionEngine/JITSymbol.h"
25#include "llvm/ExecutionEngine/MCJIT.h"
26#include "llvm/ExecutionEngine/ObjectCache.h"
27#include "llvm/ExecutionEngine/Orc/AbsoluteSymbols.h"
28#include "llvm/ExecutionEngine/Orc/DebugUtils.h"
29#include "llvm/ExecutionEngine/Orc/Debugging/DebuggerSupport.h"
30#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
31#include "llvm/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.h"
32#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
33#include "llvm/ExecutionEngine/Orc/IRPartitionLayer.h"
34#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
35#include "llvm/ExecutionEngine/Orc/LLJIT.h"
36#include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h"
37#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
38#include "llvm/ExecutionEngine/Orc/SelfExecutorProcessControl.h"
39#include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h"
40#include "llvm/ExecutionEngine/Orc/SymbolStringPool.h"
41#include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
42#include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
43#include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
44#include "llvm/ExecutionEngine/SectionMemoryManager.h"
45#include "llvm/IR/IRBuilder.h"
46#include "llvm/IR/LLVMContext.h"
47#include "llvm/IR/Module.h"
48#include "llvm/IR/Type.h"
49#include "llvm/IR/Verifier.h"
50#include "llvm/IRReader/IRReader.h"
51#include "llvm/Object/Archive.h"
52#include "llvm/Object/ObjectFile.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.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/Process.h"
64#include "llvm/Support/Program.h"
65#include "llvm/Support/SourceMgr.h"
66#include "llvm/Support/TargetSelect.h"
67#include "llvm/Support/ToolOutputFile.h"
68#include "llvm/Support/WithColor.h"
69#include "llvm/Support/raw_ostream.h"
70#include "llvm/TargetParser/Triple.h"
71#include <cerrno>
72#include <optional>
73
74#if !defined(_MSC_VER) && !defined(__MINGW32__)
75#include <unistd.h>
76#else
77#include <io.h>
78#endif
79
80#ifdef __CYGWIN__
81#include <cygwin/version.h>
82#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
83#define DO_NOTHING_ATEXIT 1
84#endif
85#endif
86
87using namespace llvm;
88
89static codegen::RegisterCodeGenFlags CGF;
90
91#define DEBUG_TYPE "lli"
92
93namespace {
94enum class JITKind { MCJIT, Orc, OrcLazy };
95enum class JITLinkerKind { Default, RuntimeDyld, JITLink };
96} // namespace
97
98static cl::opt<std::string> InputFile(cl::desc("<input bitcode>"),
99 cl::Positional, cl::init(Val: "-"));
100
101static cl::list<std::string> InputArgv(cl::ConsumeAfter,
102 cl::desc("<program arguments>..."));
103
104static cl::opt<bool>
105 ForceInterpreter("force-interpreter",
106 cl::desc("Force interpretation: disable JIT"),
107 cl::init(Val: false));
108
109static cl::opt<JITKind>
110 UseJITKind("jit-kind", cl::desc("Choose underlying JIT kind."),
111 cl::init(Val: JITKind::Orc),
112 cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
113 clEnumValN(JITKind::Orc, "orc", "Orc JIT"),
114 clEnumValN(JITKind::OrcLazy, "orc-lazy",
115 "Orc-based lazy JIT.")));
116
117static cl::opt<JITLinkerKind> JITLinker(
118 "jit-linker", cl::desc("Choose the dynamic linker/loader."),
119 cl::init(Val: JITLinkerKind::Default),
120 cl::values(clEnumValN(JITLinkerKind::Default, "default",
121 "Default for platform and JIT-kind"),
122 clEnumValN(JITLinkerKind::RuntimeDyld, "rtdyld", "RuntimeDyld"),
123 clEnumValN(JITLinkerKind::JITLink, "jitlink",
124 "Orc-specific linker")));
125static cl::opt<std::string>
126 OrcRuntime("orc-runtime", cl::desc("Use ORC runtime from given path"),
127 cl::init(Val: ""));
128
129static cl::opt<unsigned>
130 LazyJITCompileThreads("compile-threads",
131 cl::desc("Choose the number of compile threads "
132 "(jit-kind=orc-lazy only)"),
133 cl::init(Val: 0));
134
135static cl::list<std::string>
136 ThreadEntryPoints("thread-entry",
137 cl::desc("calls the given entry-point on a new thread "
138 "(jit-kind=orc-lazy only)"));
139
140static cl::opt<bool> PerModuleLazy(
141 "per-module-lazy",
142 cl::desc("Performs lazy compilation on whole module boundaries "
143 "rather than individual functions"),
144 cl::init(Val: false));
145
146static cl::list<std::string>
147 JITDylibs("jd",
148 cl::desc("Specifies the JITDylib to be used for any subsequent "
149 "-extra-module arguments."));
150
151static cl::list<std::string>
152 Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"));
153
154// The MCJIT supports building for a target address space separate from
155// the JIT compilation process. Use a forked process and a copying
156// memory manager with IPC to execute using this functionality.
157static cl::opt<bool>
158 RemoteMCJIT("remote-mcjit",
159 cl::desc("Execute MCJIT'ed code in a separate process."),
160 cl::init(Val: false));
161
162// Manually specify the child process for remote execution. This overrides
163// the simulated remote execution that allocates address space for child
164// execution. The child process will be executed and will communicate with
165// lli via stdin/stdout pipes.
166static cl::opt<std::string> ChildExecPath(
167 "mcjit-remote-process",
168 cl::desc("Specify the filename of the process to launch "
169 "for remote MCJIT execution. If none is specified,"
170 "\n\tremote execution will be simulated in-process."),
171 cl::value_desc("filename"), cl::init(Val: ""));
172
173// Determine optimization level.
174static cl::opt<char>
175 OptLevel("O",
176 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
177 "(default = '-O2')"),
178 cl::Prefix, cl::init(Val: '2'));
179
180static cl::opt<std::string>
181 TargetTriple("mtriple", cl::desc("Override target triple for module"));
182
183static cl::opt<std::string>
184 EntryFunc("entry-function",
185 cl::desc("Specify the entry function (default = 'main') "
186 "of the executable"),
187 cl::value_desc("function"), cl::init(Val: "main"));
188
189static cl::list<std::string>
190 ExtraModules("extra-module", cl::desc("Extra modules to be loaded"),
191 cl::value_desc("input bitcode"));
192
193static cl::list<std::string>
194 ExtraObjects("extra-object", cl::desc("Extra object files to be loaded"),
195 cl::value_desc("input object"));
196
197static cl::list<std::string>
198 ExtraArchives("extra-archive", cl::desc("Extra archive files to be loaded"),
199 cl::value_desc("input archive"));
200
201static cl::opt<bool>
202 EnableCacheManager("enable-cache-manager",
203 cl::desc("Use cache manager to save/load modules"),
204 cl::init(Val: false));
205
206static cl::opt<std::string>
207 ObjectCacheDir("object-cache-dir",
208 cl::desc("Directory to store cached object files "
209 "(must be user writable)"),
210 cl::init(Val: ""));
211
212static cl::opt<std::string>
213 FakeArgv0("fake-argv0",
214 cl::desc("Override the 'argv[0]' value passed into the executing"
215 " program"),
216 cl::value_desc("executable"));
217
218static cl::opt<bool>
219 DisableCoreFiles("disable-core-files", cl::Hidden,
220 cl::desc("Disable emission of core files if possible"));
221
222static cl::opt<bool> NoLazyCompilation("disable-lazy-compilation",
223 cl::desc("Disable JIT lazy compilation"),
224 cl::init(Val: false));
225
226static cl::opt<bool> GenerateSoftFloatCalls(
227 "soft-float", cl::desc("Generate software floating point library calls"),
228 cl::init(Val: false));
229
230static cl::opt<bool> NoProcessSymbols(
231 "no-process-syms",
232 cl::desc("Do not resolve lli process symbols in JIT'd code"),
233 cl::init(Val: false));
234
235enum class LLJITPlatform { Inactive, Auto, ExecutorNative, GenericIR };
236
237static cl::opt<LLJITPlatform> Platform(
238 "lljit-platform", cl::desc("Platform to use with LLJIT"),
239 cl::init(Val: LLJITPlatform::Auto),
240 cl::values(clEnumValN(LLJITPlatform::Auto, "Auto",
241 "Like 'ExecutorNative' if ORC runtime "
242 "provided, otherwise like 'GenericIR'"),
243 clEnumValN(LLJITPlatform::ExecutorNative, "ExecutorNative",
244 "Use the native platform for the executor."
245 "Requires -orc-runtime"),
246 clEnumValN(LLJITPlatform::GenericIR, "GenericIR",
247 "Use LLJITGenericIRPlatform"),
248 clEnumValN(LLJITPlatform::Inactive, "Inactive",
249 "Disable platform support explicitly")),
250 cl::Hidden);
251
252enum class DumpKind {
253 NoDump,
254 DumpFuncsToStdOut,
255 DumpModsToStdOut,
256 DumpModsToDisk,
257 DumpDebugDescriptor,
258 DumpDebugObjects,
259};
260
261static cl::opt<DumpKind> OrcDumpKind(
262 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
263 cl::init(Val: DumpKind::NoDump),
264 cl::values(clEnumValN(DumpKind::NoDump, "no-dump", "Don't dump anything."),
265 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
266 "Dump function names to stdout."),
267 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
268 "Dump modules to stdout."),
269 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
270 "Dump modules to the current "
271 "working directory. (WARNING: "
272 "will overwrite existing files)."),
273 clEnumValN(DumpKind::DumpDebugDescriptor, "jit-debug-descriptor",
274 "Dump __jit_debug_descriptor contents to stdout"),
275 clEnumValN(DumpKind::DumpDebugObjects, "jit-debug-objects",
276 "Dump __jit_debug_descriptor in-memory debug "
277 "objects as tool output")),
278 cl::Hidden);
279
280static ExitOnError ExitOnErr;
281
282LLVM_ATTRIBUTE_USED static void linkComponents() {
283 errs() << (void *)&llvm_orc_registerEHFrameSectionAllocAction
284 << (void *)&llvm_orc_deregisterEHFrameSectionAllocAction
285 << (void *)&llvm_orc_registerJITLoaderGDBAllocAction;
286}
287
288namespace {
289//===----------------------------------------------------------------------===//
290// Object cache
291//
292// This object cache implementation writes cached objects to disk to the
293// directory specified by CacheDir, using a filename provided in the module
294// descriptor. The cache tries to load a saved object using that path if the
295// file exists. CacheDir defaults to "", in which case objects are cached
296// alongside their originating bitcodes.
297//
298class LLIObjectCache : public ObjectCache {
299public:
300 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
301 // Add trailing '/' to cache dir if necessary.
302 if (!this->CacheDir.empty() &&
303 this->CacheDir[this->CacheDir.size() - 1] != '/')
304 this->CacheDir += '/';
305 }
306 ~LLIObjectCache() override = default;
307
308 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
309 const std::string &ModuleID = M->getModuleIdentifier();
310 std::string CacheName;
311 if (!getCacheFilename(ModID: ModuleID, CacheName))
312 return;
313 if (!CacheDir.empty()) { // Create user-defined cache dir.
314 SmallString<128> dir(sys::path::parent_path(path: CacheName));
315 sys::fs::create_directories(path: Twine(dir));
316 }
317
318 std::error_code EC;
319 raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
320 outfile.write(Ptr: Obj.getBufferStart(), Size: Obj.getBufferSize());
321 outfile.close();
322 }
323
324 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
325 const std::string &ModuleID = M->getModuleIdentifier();
326 std::string CacheName;
327 if (!getCacheFilename(ModID: ModuleID, CacheName))
328 return nullptr;
329 // Load the object from the cache filename
330 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
331 MemoryBuffer::getFile(Filename: CacheName, /*IsText=*/false,
332 /*RequiresNullTerminator=*/false);
333 // If the file isn't there, that's OK.
334 if (!IRObjectBuffer)
335 return nullptr;
336 // MCJIT will want to write into this buffer, and we don't want that
337 // because the file has probably just been mmapped. Instead we make
338 // a copy. The filed-based buffer will be released when it goes
339 // out of scope.
340 return MemoryBuffer::getMemBufferCopy(InputData: IRObjectBuffer.get()->getBuffer());
341 }
342
343private:
344 std::string CacheDir;
345
346 bool getCacheFilename(StringRef ModID, std::string &CacheName) {
347 if (!ModID.consume_front(Prefix: "file:"))
348 return false;
349
350 std::string CacheSubdir = std::string(ModID);
351 // Transform "X:\foo" => "/X\foo" for convenience on Windows.
352 if (is_style_windows(S: llvm::sys::path::Style::native) &&
353 isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
354 CacheSubdir[1] = CacheSubdir[0];
355 CacheSubdir[0] = '/';
356 }
357
358 CacheName = CacheDir + CacheSubdir;
359 size_t pos = CacheName.rfind(c: '.');
360 CacheName.replace(pos: pos, n1: CacheName.length() - pos, s: ".o");
361 return true;
362 }
363};
364} // namespace
365
366// On Mingw and Cygwin, an external symbol named '__main' is called from the
367// generated 'main' function to allow static initialization. To avoid linking
368// problems with remote targets (because lli's remote target support does not
369// currently handle external linking) we add a secondary module which defines
370// an empty '__main' function.
371static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
372 const Triple &TargetTriple) {
373 IRBuilder<> Builder(Context);
374
375 // Create a new module.
376 std::unique_ptr<Module> M = std::make_unique<Module>(args: "CygMingHelper", args&: Context);
377 M->setTargetTriple(TargetTriple);
378
379 // Create an empty function named "__main".
380 Type *ReturnTy;
381 if (TargetTriple.isArch64Bit())
382 ReturnTy = Type::getInt64Ty(C&: Context);
383 else
384 ReturnTy = Type::getInt32Ty(C&: Context);
385 Function *Result =
386 Function::Create(Ty: FunctionType::get(Result: ReturnTy, Params: {}, isVarArg: false),
387 Linkage: GlobalValue::ExternalLinkage, N: "__main", M: M.get());
388
389 BasicBlock *BB = BasicBlock::Create(Context, Name: "__main", Parent: Result);
390 Builder.SetInsertPoint(BB);
391 Value *ReturnVal = ConstantInt::get(Ty: ReturnTy, V: 0);
392 Builder.CreateRet(V: ReturnVal);
393
394 // Add this new module to the ExecutionEngine.
395 EE.addModule(M: std::move(M));
396}
397
398static CodeGenOptLevel getOptLevel() {
399 if (auto Level = CodeGenOpt::parseLevel(C: OptLevel))
400 return *Level;
401 WithColor::error(OS&: errs(), Prefix: "lli") << "invalid optimization level.\n";
402 exit(status: 1);
403}
404
405[[noreturn]] static void reportError(SMDiagnostic Err, const char *ProgName) {
406 Err.print(ProgName, S&: errs());
407 exit(status: 1);
408}
409
410static Error loadDylibs();
411static int runOrcJIT(const char *ProgName);
412static void disallowOrcOptions();
413static Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote();
414
415//===----------------------------------------------------------------------===//
416// main Driver function
417//
418int main(int argc, char **argv, char * const *envp) {
419 InitLLVM X(argc, argv);
420
421 if (argc > 1)
422 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
423
424 // If we have a native target, initialize it to ensure it is linked in and
425 // usable by the JIT.
426 InitializeNativeTarget();
427 InitializeNativeTargetAsmPrinter();
428 InitializeNativeTargetAsmParser();
429
430 cl::ParseCommandLineOptions(argc, argv,
431 Overview: "llvm interpreter & dynamic compiler\n");
432
433 // If the user doesn't want core files, disable them.
434 if (DisableCoreFiles)
435 sys::Process::PreventCoreFiles();
436
437 ExitOnErr(loadDylibs());
438
439 if (EntryFunc.empty()) {
440 WithColor::error(OS&: errs(), Prefix: argv[0])
441 << "--entry-function name cannot be empty\n";
442 exit(status: 1);
443 }
444
445 if (UseJITKind == JITKind::MCJIT || ForceInterpreter)
446 disallowOrcOptions();
447 else
448 return runOrcJIT(ProgName: argv[0]);
449
450 // Old lli implementation based on ExecutionEngine and MCJIT.
451 LLVMContext Context;
452
453 // Load the bitcode...
454 SMDiagnostic Err;
455 std::unique_ptr<Module> Owner = parseIRFile(Filename: InputFile, Err, Context);
456 Module *Mod = Owner.get();
457 if (!Mod)
458 reportError(Err, ProgName: argv[0]);
459
460 if (EnableCacheManager) {
461 std::string CacheName("file:");
462 CacheName.append(str: InputFile);
463 Mod->setModuleIdentifier(CacheName);
464 }
465
466 // If not jitting lazily, load the whole bitcode file eagerly too.
467 if (NoLazyCompilation) {
468 // Use *argv instead of argv[0] to work around a wrong GCC warning.
469 ExitOnError ExitOnErr(std::string(*argv) +
470 ": bitcode didn't read correctly: ");
471 ExitOnErr(Mod->materializeAll());
472 }
473
474 std::string ErrorMsg;
475 EngineBuilder builder(std::move(Owner));
476 builder.setMArch(codegen::getMArch());
477 builder.setMCPU(codegen::getCPUStr());
478 builder.setMAttrs(codegen::getFeatureList());
479 if (auto RM = codegen::getExplicitRelocModel())
480 builder.setRelocationModel(*RM);
481 if (auto CM = codegen::getExplicitCodeModel())
482 builder.setCodeModel(*CM);
483 builder.setErrorStr(&ErrorMsg);
484 builder.setEngineKind(ForceInterpreter
485 ? EngineKind::Interpreter
486 : EngineKind::JIT);
487
488 // If we are supposed to override the target triple, do so now.
489 if (!TargetTriple.empty())
490 Mod->setTargetTriple(Triple(Triple::normalize(Str: TargetTriple)));
491
492 // Enable MCJIT if desired.
493 RTDyldMemoryManager *RTDyldMM = nullptr;
494 if (!ForceInterpreter) {
495 if (RemoteMCJIT)
496 RTDyldMM = new ForwardingMemoryManager();
497 else
498 RTDyldMM = new SectionMemoryManager();
499
500 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
501 // RTDyldMM: We still use it below, even though we don't own it.
502 builder.setMCJITMemoryManager(
503 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
504 } else if (RemoteMCJIT) {
505 WithColor::error(OS&: errs(), Prefix: argv[0])
506 << "remote process execution does not work with the interpreter.\n";
507 exit(status: 1);
508 }
509
510 builder.setOptLevel(getOptLevel());
511
512 TargetOptions Options =
513 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple(TargetTriple));
514 if (codegen::getFloatABIForCalls() != FloatABI::Default)
515 Options.FloatABIType = codegen::getFloatABIForCalls();
516
517 builder.setTargetOptions(Options);
518
519 std::unique_ptr<ExecutionEngine> EE(builder.create());
520 if (!EE) {
521 if (!ErrorMsg.empty())
522 WithColor::error(OS&: errs(), Prefix: argv[0])
523 << "error creating EE: " << ErrorMsg << "\n";
524 else
525 WithColor::error(OS&: errs(), Prefix: argv[0]) << "unknown error creating EE!\n";
526 exit(status: 1);
527 }
528
529 std::unique_ptr<LLIObjectCache> CacheManager;
530 if (EnableCacheManager) {
531 CacheManager.reset(p: new LLIObjectCache(ObjectCacheDir));
532 EE->setObjectCache(CacheManager.get());
533 }
534
535 // Load any additional modules specified on the command line.
536 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
537 std::unique_ptr<Module> XMod = parseIRFile(Filename: ExtraModules[i], Err, Context);
538 if (!XMod)
539 reportError(Err, ProgName: argv[0]);
540 if (EnableCacheManager) {
541 std::string CacheName("file:");
542 CacheName.append(str: ExtraModules[i]);
543 XMod->setModuleIdentifier(CacheName);
544 }
545 EE->addModule(M: std::move(XMod));
546 }
547
548 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
549 Expected<object::OwningBinary<object::ObjectFile>> Obj =
550 object::ObjectFile::createObjectFile(ObjectPath: ExtraObjects[i]);
551 if (!Obj) {
552 // TODO: Actually report errors helpfully.
553 consumeError(Err: Obj.takeError());
554 reportError(Err, ProgName: argv[0]);
555 }
556 object::OwningBinary<object::ObjectFile> &O = Obj.get();
557 EE->addObjectFile(O: std::move(O));
558 }
559
560 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
561 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
562 MemoryBuffer::getFileOrSTDIN(Filename: ExtraArchives[i]);
563 if (!ArBufOrErr)
564 reportError(Err, ProgName: argv[0]);
565 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
566
567 Expected<std::unique_ptr<object::Archive>> ArOrErr =
568 object::Archive::create(Source: ArBuf->getMemBufferRef());
569 if (!ArOrErr) {
570 std::string Buf;
571 raw_string_ostream OS(Buf);
572 logAllUnhandledErrors(E: ArOrErr.takeError(), OS);
573 errs() << Buf;
574 exit(status: 1);
575 }
576 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
577
578 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
579
580 EE->addArchive(A: std::move(OB));
581 }
582
583 // If the target is Cygwin/MingW and we are generating remote code, we
584 // need an extra module to help out with linking.
585 if (RemoteMCJIT && Mod->getTargetTriple().isOSCygMing()) {
586 addCygMingExtraModule(EE&: *EE, Context, TargetTriple: Mod->getTargetTriple());
587 }
588
589 // The following functions have no effect if their respective profiling
590 // support wasn't enabled in the build configuration.
591 EE->RegisterJITEventListener(
592 JITEventListener::createOProfileJITEventListener());
593 EE->RegisterJITEventListener(
594 JITEventListener::createIntelJITEventListener());
595 if (!RemoteMCJIT)
596 EE->RegisterJITEventListener(
597 JITEventListener::createPerfJITEventListener());
598
599 if (!NoLazyCompilation && RemoteMCJIT) {
600 WithColor::warning(OS&: errs(), Prefix: argv[0])
601 << "remote mcjit does not support lazy compilation\n";
602 NoLazyCompilation = true;
603 }
604 EE->DisableLazyCompilation(Disabled: NoLazyCompilation);
605
606 // If the user specifically requested an argv[0] to pass into the program,
607 // do it now.
608 if (!FakeArgv0.empty()) {
609 InputFile = static_cast<std::string>(FakeArgv0);
610 } else {
611 // Otherwise, if there is a .bc suffix on the executable strip it off, it
612 // might confuse the program.
613 if (StringRef(InputFile).ends_with(Suffix: ".bc"))
614 InputFile.erase(pos: InputFile.length() - 3);
615 }
616
617 // Add the module's name to the start of the vector of arguments to main().
618 InputArgv.insert(pos: InputArgv.begin(), value: InputFile);
619
620 // Call the main function from M as if its signature were:
621 // int main (int argc, char **argv, const char **envp)
622 // using the contents of Args to determine argc & argv, and the contents of
623 // EnvVars to determine envp.
624 //
625 Function *EntryFn = Mod->getFunction(Name: EntryFunc);
626 if (!EntryFn) {
627 WithColor::error(OS&: errs(), Prefix: argv[0])
628 << '\'' << EntryFunc << "\' function not found in module.\n";
629 return -1;
630 }
631
632 // Reset errno to zero on entry to main.
633 errno = 0;
634
635 int Result = -1;
636
637 // Sanity check use of remote-jit: LLI currently only supports use of the
638 // remote JIT on Unix platforms.
639 if (RemoteMCJIT) {
640#ifndef LLVM_ON_UNIX
641 WithColor::warning(errs(), argv[0])
642 << "host does not support external remote targets.\n";
643 WithColor::note() << "defaulting to local execution\n";
644 return -1;
645#else
646 if (ChildExecPath.empty()) {
647 WithColor::error(OS&: errs(), Prefix: argv[0])
648 << "-remote-mcjit requires -mcjit-remote-process.\n";
649 exit(status: 1);
650 } else if (!sys::fs::can_execute(Path: ChildExecPath)) {
651 WithColor::error(OS&: errs(), Prefix: argv[0])
652 << "unable to find usable child executable: '" << ChildExecPath
653 << "'\n";
654 return -1;
655 }
656#endif
657 }
658
659 if (!RemoteMCJIT) {
660 // If the program doesn't explicitly call exit, we will need the Exit
661 // function later on to make an explicit call, so get the function now.
662 FunctionCallee Exit = Mod->getOrInsertFunction(
663 Name: "exit", RetTy: Type::getVoidTy(C&: Context), Args: Type::getInt32Ty(C&: Context));
664
665 // Run static constructors.
666 if (!ForceInterpreter) {
667 // Give MCJIT a chance to apply relocations and set page permissions.
668 EE->finalizeObject();
669 }
670 EE->runStaticConstructorsDestructors(isDtors: false);
671
672 // Trigger compilation separately so code regions that need to be
673 // invalidated will be known.
674 (void)EE->getPointerToFunction(F: EntryFn);
675 // Clear instruction cache before code will be executed.
676 if (RTDyldMM)
677 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
678
679 // Run main.
680 Result = EE->runFunctionAsMain(Fn: EntryFn, argv: InputArgv, envp);
681
682 // Run static destructors.
683 EE->runStaticConstructorsDestructors(isDtors: true);
684
685 // If the program didn't call exit explicitly, we should call it now.
686 // This ensures that any atexit handlers get called correctly.
687 if (Function *ExitF =
688 dyn_cast<Function>(Val: Exit.getCallee()->stripPointerCasts())) {
689 if (ExitF->getFunctionType() == Exit.getFunctionType()) {
690 std::vector<GenericValue> Args;
691 GenericValue ResultGV;
692 ResultGV.IntVal = APInt(32, Result);
693 Args.push_back(x: ResultGV);
694 EE->runFunction(F: ExitF, ArgValues: Args);
695 WithColor::error(OS&: errs(), Prefix: argv[0])
696 << "exit(" << Result << ") returned!\n";
697 abort();
698 }
699 }
700 WithColor::error(OS&: errs(), Prefix: argv[0]) << "exit defined with wrong prototype!\n";
701 abort();
702 } else {
703 // else == "if (RemoteMCJIT)"
704 std::unique_ptr<orc::ExecutorProcessControl> EPC = ExitOnErr(launchRemote());
705
706 // Remote target MCJIT doesn't (yet) support static constructors. No reason
707 // it couldn't. This is a limitation of the LLI implementation, not the
708 // MCJIT itself. FIXME.
709
710 // Create a remote memory manager.
711 auto RemoteMM = ExitOnErr(
712 orc::EPCGenericRTDyldMemoryManager::CreateWithDefaultBootstrapSymbols(
713 EPC&: *EPC));
714
715 // Forward MCJIT's memory manager calls to the remote memory manager.
716 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
717 std::move(RemoteMM));
718
719 // Forward MCJIT's symbol resolution calls to the remote.
720 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
721 ExitOnErr(RemoteResolver::Create(EPC&: *EPC)));
722 // Grab the target address of the JIT'd main function on the remote and call
723 // it.
724 // FIXME: argv and envp handling.
725 auto Entry =
726 orc::ExecutorAddr(EE->getFunctionAddress(Name: EntryFn->getName().str()));
727 EE->finalizeObject();
728 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
729 << format("%llx", Entry.getValue()) << "\n");
730 Result = ExitOnErr(EPC->runAsMain(MainFnAddr: Entry, Args: {}));
731
732 // Like static constructors, the remote target MCJIT support doesn't handle
733 // this yet. It could. FIXME.
734
735 // Delete the EE - we need to tear it down *before* we terminate the session
736 // with the remote, otherwise it'll crash when it tries to release resources
737 // on a remote that has already been disconnected.
738 EE.reset();
739
740 // Signal the remote target that we're done JITing.
741 ExitOnErr(EPC->disconnect());
742 }
743
744 return Result;
745}
746
747// JITLink debug support plugins put information about JITed code in this GDB
748// JIT Interface global from OrcTargetProcess.
749extern "C" LLVM_ABI struct jit_descriptor __jit_debug_descriptor;
750
751static struct jit_code_entry *
752findNextDebugDescriptorEntry(struct jit_code_entry *Latest) {
753 if (Latest == nullptr)
754 return __jit_debug_descriptor.first_entry;
755 if (Latest->next_entry)
756 return Latest->next_entry;
757 return nullptr;
758}
759
760static ToolOutputFile &claimToolOutput() {
761 static std::unique_ptr<ToolOutputFile> ToolOutput = nullptr;
762 if (ToolOutput) {
763 WithColor::error(OS&: errs(), Prefix: "lli")
764 << "Can not claim stdout for tool output twice\n";
765 exit(status: 1);
766 }
767 std::error_code EC;
768 ToolOutput = std::make_unique<ToolOutputFile>(args: "-", args&: EC, args: sys::fs::OF_None);
769 if (EC) {
770 WithColor::error(OS&: errs(), Prefix: "lli")
771 << "Failed to create tool output file: " << EC.message() << "\n";
772 exit(status: 1);
773 }
774 return *ToolOutput;
775}
776
777static std::function<void(Module &)> createIRDebugDumper() {
778 switch (OrcDumpKind) {
779 case DumpKind::NoDump:
780 case DumpKind::DumpDebugDescriptor:
781 case DumpKind::DumpDebugObjects:
782 return [](Module &M) {};
783
784 case DumpKind::DumpFuncsToStdOut:
785 return [](Module &M) {
786 printf(format: "[ ");
787
788 for (const auto &F : M) {
789 if (F.isDeclaration())
790 continue;
791
792 if (F.hasName()) {
793 std::string Name(std::string(F.getName()));
794 printf(format: "%s ", Name.c_str());
795 } else
796 printf(format: "<anon> ");
797 }
798
799 printf(format: "]\n");
800 };
801
802 case DumpKind::DumpModsToStdOut:
803 return [](Module &M) {
804 outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";
805 };
806
807 case DumpKind::DumpModsToDisk:
808 return [](Module &M) {
809 std::error_code EC;
810 raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC,
811 sys::fs::OF_TextWithCRLF);
812 if (EC) {
813 errs() << "Couldn't open " << M.getModuleIdentifier()
814 << " for dumping.\nError:" << EC.message() << "\n";
815 exit(status: 1);
816 }
817 Out << M;
818 };
819 }
820 llvm_unreachable("Unknown DumpKind");
821}
822
823static std::function<void(MemoryBuffer &)> createObjDebugDumper() {
824 switch (OrcDumpKind) {
825 case DumpKind::NoDump:
826 case DumpKind::DumpFuncsToStdOut:
827 case DumpKind::DumpModsToStdOut:
828 case DumpKind::DumpModsToDisk:
829 return [](MemoryBuffer &) {};
830
831 case DumpKind::DumpDebugDescriptor: {
832 // Dump the empty descriptor at startup once
833 fprintf(stderr, format: "jit_debug_descriptor 0x%016" PRIx64 "\n",
834 pointerToJITTargetAddress(Ptr: __jit_debug_descriptor.first_entry));
835 return [](MemoryBuffer &) {
836 // Dump new entries as they appear
837 static struct jit_code_entry *Latest = nullptr;
838 while (auto *NewEntry = findNextDebugDescriptorEntry(Latest)) {
839 fprintf(stderr, format: "jit_debug_descriptor 0x%016" PRIx64 "\n",
840 pointerToJITTargetAddress(Ptr: NewEntry));
841 Latest = NewEntry;
842 }
843 };
844 }
845
846 case DumpKind::DumpDebugObjects: {
847 return [](MemoryBuffer &Obj) {
848 static struct jit_code_entry *Latest = nullptr;
849 static ToolOutputFile &ToolOutput = claimToolOutput();
850 while (auto *NewEntry = findNextDebugDescriptorEntry(Latest)) {
851 ToolOutput.os().write(Ptr: NewEntry->symfile_addr, Size: NewEntry->symfile_size);
852 Latest = NewEntry;
853 }
854 };
855 }
856 }
857 llvm_unreachable("Unknown DumpKind");
858}
859
860static Error loadDylibs() {
861 for (const auto &Dylib : Dylibs) {
862 std::string ErrMsg;
863 if (sys::DynamicLibrary::LoadLibraryPermanently(Filename: Dylib.c_str(), ErrMsg: &ErrMsg))
864 return make_error<StringError>(Args&: ErrMsg, Args: inconvertibleErrorCode());
865 }
866
867 return Error::success();
868}
869
870static void exitOnLazyCallThroughFailure() { exit(status: 1); }
871
872static Expected<orc::ThreadSafeModule>
873loadModule(StringRef Path, orc::ThreadSafeContext TSCtx) {
874 SMDiagnostic Err;
875 auto M = TSCtx.withContextDo(
876 F: [&](LLVMContext *Ctx) { return parseIRFile(Filename: Path, Err, Context&: *Ctx); });
877 if (!M) {
878 std::string ErrMsg;
879 {
880 raw_string_ostream ErrMsgStream(ErrMsg);
881 Err.print(ProgName: "lli", S&: ErrMsgStream);
882 }
883 return make_error<StringError>(Args: std::move(ErrMsg), Args: inconvertibleErrorCode());
884 }
885
886 if (EnableCacheManager)
887 M->setModuleIdentifier("file:" + M->getModuleIdentifier());
888
889 return orc::ThreadSafeModule(std::move(M), std::move(TSCtx));
890}
891
892static int mingw_noop_main(void) {
893 // Cygwin and MinGW insert calls from the main function to the runtime
894 // function __main. The __main function is responsible for setting up main's
895 // environment (e.g. running static constructors), however this is not needed
896 // when running under lli: the executor process will have run non-JIT ctors,
897 // and ORC will take care of running JIT'd ctors. To avoid a missing symbol
898 // error we just implement __main as a no-op.
899 //
900 // FIXME: Move this to ORC-RT (and the ORC-RT substitution library once it
901 // exists). That will allow it to work out-of-process, and for all
902 // ORC tools (the problem isn't lli specific).
903 return 0;
904}
905
906// Try to enable debugger support for the given instance.
907// This alway returns success, but prints a warning if it's not able to enable
908// debugger support.
909static Error tryEnableDebugSupport(orc::LLJIT &J) {
910 if (auto Err = enableDebuggerSupport(J)) {
911 [[maybe_unused]] std::string ErrMsg = toString(E: std::move(Err));
912 LLVM_DEBUG(dbgs() << "lli: " << ErrMsg << "\n");
913 }
914 return Error::success();
915}
916
917static int runOrcJIT(const char *ProgName) {
918 // Start setting up the JIT environment.
919
920 // Parse the main module.
921 orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
922 auto MainModule = ExitOnErr(loadModule(Path: InputFile, TSCtx));
923
924 // Get TargetTriple and DataLayout from the main module if they're explicitly
925 // set.
926 std::optional<Triple> TT;
927 std::optional<DataLayout> DL;
928 MainModule.withModuleDo(F: [&](Module &M) {
929 if (!M.getTargetTriple().empty())
930 TT = M.getTargetTriple();
931 if (!M.getDataLayout().isDefault())
932 DL = M.getDataLayout();
933 });
934
935 orc::LLLazyJITBuilder Builder;
936
937 Builder.setJITTargetMachineBuilder(
938 TT ? orc::JITTargetMachineBuilder(*TT)
939 : ExitOnErr(orc::JITTargetMachineBuilder::detectHost()));
940
941 TT = Builder.getJITTargetMachineBuilder()->getTargetTriple();
942 if (DL)
943 Builder.setDataLayout(DL);
944
945 if (!codegen::getMArch().empty())
946 Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(
947 codegen::getMArch());
948
949 Builder.getJITTargetMachineBuilder()
950 ->setCPU(codegen::getCPUStr())
951 .addFeatures(FeatureVec: codegen::getFeatureList())
952 .setRelocationModel(codegen::getExplicitRelocModel())
953 .setCodeModel(codegen::getExplicitCodeModel());
954
955 // Link process symbols unless NoProcessSymbols is set.
956 Builder.setLinkProcessSymbolsByDefault(!NoProcessSymbols);
957
958 // FIXME: Setting a dummy call-through manager in non-lazy mode prevents the
959 // JIT builder to instantiate a default (which would fail with an error for
960 // unsupported architectures).
961 if (UseJITKind != JITKind::OrcLazy) {
962 auto ES = std::make_unique<orc::ExecutionSession>(
963 args: ExitOnErr(orc::SelfExecutorProcessControl::Create()));
964 Builder.setLazyCallthroughManager(
965 std::make_unique<orc::LazyCallThroughManager>(args&: *ES, args: orc::ExecutorAddr(),
966 args: nullptr));
967 Builder.setExecutionSession(std::move(ES));
968 }
969
970 Builder.setLazyCompileFailureAddr(
971 orc::ExecutorAddr::fromPtr(Ptr: exitOnLazyCallThroughFailure));
972 Builder.setNumCompileThreads(LazyJITCompileThreads);
973
974 // If the object cache is enabled then set a custom compile function
975 // creator to use the cache.
976 std::unique_ptr<LLIObjectCache> CacheManager;
977 if (EnableCacheManager) {
978
979 CacheManager = std::make_unique<LLIObjectCache>(args&: ObjectCacheDir);
980
981 Builder.setCompileFunctionCreator(
982 [&](orc::JITTargetMachineBuilder JTMB)
983 -> Expected<std::unique_ptr<orc::IRCompileLayer::IRCompiler>> {
984 if (LazyJITCompileThreads > 0)
985 return std::make_unique<orc::ConcurrentIRCompiler>(args: std::move(JTMB),
986 args: CacheManager.get());
987
988 auto TM = JTMB.createTargetMachine();
989 if (!TM)
990 return TM.takeError();
991
992 return std::make_unique<orc::TMOwningSimpleCompiler>(args: std::move(*TM),
993 args: CacheManager.get());
994 });
995 }
996
997 // Enable debugging of JIT'd code (only works on JITLink for ELF and MachO).
998 Builder.setPrePlatformSetup(tryEnableDebugSupport);
999
1000 // Set up LLJIT platform.
1001 LLJITPlatform P = Platform;
1002 if (P == LLJITPlatform::Auto)
1003 P = OrcRuntime.empty() ? LLJITPlatform::GenericIR
1004 : LLJITPlatform::ExecutorNative;
1005
1006 switch (P) {
1007 case LLJITPlatform::ExecutorNative: {
1008 Builder.setPlatformSetUp(orc::ExecutorNativePlatform(OrcRuntime));
1009 break;
1010 }
1011 case LLJITPlatform::GenericIR:
1012 // Nothing to do: LLJITBuilder will use this by default.
1013 break;
1014 case LLJITPlatform::Inactive:
1015 Builder.setPlatformSetUp(orc::setUpInactivePlatform);
1016 break;
1017 default:
1018 llvm_unreachable("Unrecognized platform value");
1019 }
1020
1021 switch (JITLinker) {
1022 case JITLinkerKind::JITLink:
1023 Builder.getJITTargetMachineBuilder()
1024 ->setRelocationModel(Reloc::PIC_)
1025 .setCodeModel(CodeModel::Small);
1026 Builder.setObjectLinkingLayerCreator([&](orc::ExecutionSession &ES) {
1027 return std::make_unique<orc::ObjectLinkingLayer>(args&: ES);
1028 });
1029 break;
1030 case JITLinkerKind::RuntimeDyld:
1031 Builder.setObjectLinkingLayerCreator([&](orc::ExecutionSession &ES) {
1032 return std::make_unique<orc::RTDyldObjectLinkingLayer>(
1033 args&: ES, args: [](const MemoryBuffer &) {
1034 return std::make_unique<SectionMemoryManager>();
1035 });
1036 });
1037 break;
1038 case JITLinkerKind::Default:
1039 // Let LLJITBuilder decide
1040 break;
1041 }
1042
1043 auto J = ExitOnErr(Builder.create());
1044
1045 auto *ObjLayer = &J->getObjLinkingLayer();
1046 if (auto *RTDyldObjLayer = dyn_cast<orc::RTDyldObjectLinkingLayer>(Val: ObjLayer)) {
1047 RTDyldObjLayer->registerJITEventListener(
1048 L&: *JITEventListener::createGDBRegistrationListener());
1049#if LLVM_USE_OPROFILE
1050 RTDyldObjLayer->registerJITEventListener(
1051 *JITEventListener::createOProfileJITEventListener());
1052#endif
1053#if LLVM_USE_INTEL_JITEVENTS
1054 RTDyldObjLayer->registerJITEventListener(
1055 *JITEventListener::createIntelJITEventListener());
1056#endif
1057#if LLVM_USE_PERF
1058 RTDyldObjLayer->registerJITEventListener(
1059 *JITEventListener::createPerfJITEventListener());
1060#endif
1061 }
1062
1063 if (PerModuleLazy)
1064 J->setPartitionFunction(orc::IRPartitionLayer::compileWholeModule);
1065
1066 auto IRDump = createIRDebugDumper();
1067 J->getIRTransformLayer().setTransform(
1068 [&](orc::ThreadSafeModule TSM,
1069 const orc::MaterializationResponsibility &R) {
1070 TSM.withModuleDo(F: [&](Module &M) {
1071 if (verifyModule(M, OS: &dbgs())) {
1072 dbgs() << "Bad module: " << &M << "\n";
1073 exit(status: 1);
1074 }
1075 IRDump(M);
1076 });
1077 return TSM;
1078 });
1079
1080 auto ObjDump = createObjDebugDumper();
1081 J->getObjTransformLayer().setTransform(
1082 [&](std::unique_ptr<MemoryBuffer> Obj)
1083 -> Expected<std::unique_ptr<MemoryBuffer>> {
1084 ObjDump(*Obj);
1085 return std::move(Obj);
1086 });
1087
1088 // If this is a Mingw or Cygwin executor then we need to alias __main to
1089 // orc_rt_int_void_return_0.
1090 if (J->getTargetTriple().isOSCygMing()) {
1091 auto &WorkaroundJD = J->getProcessSymbolsJITDylib()
1092 ? *J->getProcessSymbolsJITDylib()
1093 : J->getMainJITDylib();
1094 ExitOnErr(WorkaroundJD.define(
1095 MU: orc::absoluteSymbols(Symbols: {{J->mangleAndIntern(UnmangledName: "__main"),
1096 {orc::ExecutorAddr::fromPtr(Ptr: mingw_noop_main),
1097 JITSymbolFlags::Exported}}})));
1098 }
1099
1100 // Regular modules are greedy: They materialize as a whole and trigger
1101 // materialization for all required symbols recursively. Lazy modules go
1102 // through partitioning and they replace outgoing calls with reexport stubs
1103 // that resolve on call-through.
1104 auto AddModule = [&](orc::JITDylib &JD, orc::ThreadSafeModule M) {
1105 return UseJITKind == JITKind::OrcLazy ? J->addLazyIRModule(JD, M: std::move(M))
1106 : J->addIRModule(JD, TSM: std::move(M));
1107 };
1108
1109 // Add the main module.
1110 ExitOnErr(AddModule(J->getMainJITDylib(), std::move(MainModule)));
1111
1112 // Create JITDylibs and add any extra modules.
1113 {
1114 // Create JITDylibs, keep a map from argument index to dylib. We will use
1115 // -extra-module argument indexes to determine what dylib to use for each
1116 // -extra-module.
1117 std::map<unsigned, orc::JITDylib *> IdxToDylib;
1118 IdxToDylib[0] = &J->getMainJITDylib();
1119 for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
1120 JDItr != JDEnd; ++JDItr) {
1121 orc::JITDylib *JD = J->getJITDylibByName(Name: *JDItr);
1122 if (!JD) {
1123 JD = &ExitOnErr(J->createJITDylib(Name: *JDItr));
1124 J->getMainJITDylib().addToLinkOrder(JD&: *JD);
1125 JD->addToLinkOrder(JD&: J->getMainJITDylib());
1126 }
1127 IdxToDylib[JITDylibs.getPosition(optnum: JDItr - JITDylibs.begin())] = JD;
1128 }
1129
1130 for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
1131 EMItr != EMEnd; ++EMItr) {
1132 auto M = ExitOnErr(loadModule(Path: *EMItr, TSCtx));
1133
1134 auto EMIdx = ExtraModules.getPosition(optnum: EMItr - ExtraModules.begin());
1135 assert(EMIdx != 0 && "ExtraModule should have index > 0");
1136 auto JDItr = std::prev(x: IdxToDylib.lower_bound(x: EMIdx));
1137 auto &JD = *JDItr->second;
1138 ExitOnErr(AddModule(JD, std::move(M)));
1139 }
1140
1141 for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();
1142 EAItr != EAEnd; ++EAItr) {
1143 auto EAIdx = ExtraArchives.getPosition(optnum: EAItr - ExtraArchives.begin());
1144 assert(EAIdx != 0 && "ExtraArchive should have index > 0");
1145 auto JDItr = std::prev(x: IdxToDylib.lower_bound(x: EAIdx));
1146 auto &JD = *JDItr->second;
1147 ExitOnErr(J->linkStaticLibraryInto(JD, Path: EAItr->c_str()));
1148 }
1149 }
1150
1151 // Add the objects.
1152 for (auto &ObjPath : ExtraObjects) {
1153 auto Obj = ExitOnErr(errorOrToExpected(EO: MemoryBuffer::getFile(Filename: ObjPath)));
1154 ExitOnErr(J->addObjectFile(Obj: std::move(Obj)));
1155 }
1156
1157 // Run any static constructors.
1158 ExitOnErr(J->initialize(JD&: J->getMainJITDylib()));
1159
1160 // Run any -thread-entry points.
1161 std::vector<std::thread> AltEntryThreads;
1162 for (auto &ThreadEntryPoint : ThreadEntryPoints) {
1163 auto EntryPointSym = ExitOnErr(J->lookup(UnmangledName: ThreadEntryPoint));
1164 typedef void (*EntryPointPtr)();
1165 auto EntryPoint = EntryPointSym.toPtr<EntryPointPtr>();
1166 AltEntryThreads.push_back(x: std::thread([EntryPoint]() { EntryPoint(); }));
1167 }
1168
1169 // Resolve and run the main function.
1170 using MainFnTy = int(int, char *[]);
1171 auto MainAddr = ExitOnErr(J->lookup(UnmangledName: EntryFunc));
1172 auto MainFn = MainAddr.toPtr<MainFnTy *>();
1173 int Result = orc::runAsMain(Main: MainFn, Args: InputArgv, ProgramName: StringRef(InputFile));
1174
1175 // Wait for -entry-point threads.
1176 for (auto &AltEntryThread : AltEntryThreads)
1177 AltEntryThread.join();
1178
1179 // Run destructors.
1180 ExitOnErr(J->deinitialize(JD&: J->getMainJITDylib()));
1181
1182 return Result;
1183}
1184
1185static void disallowOrcOptions() {
1186 // Make sure nobody used an orc-lazy specific option accidentally.
1187
1188 if (LazyJITCompileThreads != 0) {
1189 errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
1190 exit(status: 1);
1191 }
1192
1193 if (!ThreadEntryPoints.empty()) {
1194 errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
1195 exit(status: 1);
1196 }
1197
1198 if (PerModuleLazy) {
1199 errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
1200 exit(status: 1);
1201 }
1202}
1203
1204static Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote() {
1205#ifndef LLVM_ON_UNIX
1206 llvm_unreachable("launchRemote not supported on non-Unix platforms");
1207#else
1208 int PipeFD[2][2];
1209 pid_t ChildPID;
1210
1211 // Create two pipes.
1212 if (pipe(pipedes: PipeFD[0]) != 0 || pipe(pipedes: PipeFD[1]) != 0)
1213 perror(s: "Error creating pipe: ");
1214
1215 ChildPID = fork();
1216
1217 if (ChildPID == 0) {
1218 // In the child...
1219
1220 // Close the parent ends of the pipes
1221 close(fd: PipeFD[0][1]);
1222 close(fd: PipeFD[1][0]);
1223
1224
1225 // Execute the child process.
1226 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
1227 {
1228 ChildPath.reset(p: new char[ChildExecPath.size() + 1]);
1229 llvm::copy(Range&: ChildExecPath, Out: &ChildPath[0]);
1230 ChildPath[ChildExecPath.size()] = '\0';
1231 std::string ChildInStr = utostr(X: PipeFD[0][0]);
1232 ChildIn.reset(p: new char[ChildInStr.size() + 1]);
1233 llvm::copy(Range&: ChildInStr, Out: &ChildIn[0]);
1234 ChildIn[ChildInStr.size()] = '\0';
1235 std::string ChildOutStr = utostr(X: PipeFD[1][1]);
1236 ChildOut.reset(p: new char[ChildOutStr.size() + 1]);
1237 llvm::copy(Range&: ChildOutStr, Out: &ChildOut[0]);
1238 ChildOut[ChildOutStr.size()] = '\0';
1239 }
1240
1241 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
1242 int rc = execv(path: ChildExecPath.c_str(), argv: args);
1243 if (rc != 0)
1244 perror(s: "Error executing child process: ");
1245 llvm_unreachable("Error executing child process");
1246 }
1247 // else we're the parent...
1248
1249 // Close the child ends of the pipes
1250 close(fd: PipeFD[0][0]);
1251 close(fd: PipeFD[1][1]);
1252
1253 // Return a SimpleRemoteEPC instance connected to our end of the pipes.
1254 return orc::SimpleRemoteEPC::Create<orc::FDSimpleRemoteEPCTransport>(
1255 D: std::make_unique<llvm::orc::InPlaceTaskDispatcher>(),
1256 S: llvm::orc::SimpleRemoteEPC::Setup(), TransportTCtorArgs&: PipeFD[1][0], TransportTCtorArgs&: PipeFD[0][1]);
1257#endif
1258}
1259
1260// For MinGW environments, manually export the __chkstk function from the lli
1261// executable.
1262//
1263// Normally, this function is provided by compiler-rt builtins or libgcc.
1264// It is named "_alloca" on i386, "___chkstk_ms" on x86_64, and "__chkstk" on
1265// arm/aarch64. In MSVC configurations, it's named "__chkstk" in all
1266// configurations.
1267//
1268// When Orc tries to resolve symbols at runtime, this succeeds in MSVC
1269// configurations, somewhat by accident/luck; kernelbase.dll does export a
1270// symbol named "__chkstk" which gets found by Orc, even if regular applications
1271// never link against that function from that DLL (it's linked in statically
1272// from a compiler support library).
1273//
1274// The MinGW specific symbol names aren't available in that DLL though.
1275// Therefore, manually export the relevant symbol from lli, to let it be
1276// found at runtime during tests.
1277//
1278// For real JIT uses, the real compiler support libraries should be linked
1279// in, somehow; this is a workaround to let tests pass.
1280//
1281// We need to make sure that this symbol actually is linked in when we
1282// try to export it; if no functions allocate a large enough stack area,
1283// nothing would reference it. Therefore, manually declare it and add a
1284// reference to it. (Note, the declarations of _alloca/___chkstk_ms/__chkstk
1285// are somewhat bogus, these functions use a different custom calling
1286// convention.)
1287//
1288// TODO: Move this into libORC at some point, see
1289// https://github.com/llvm/llvm-project/issues/56603.
1290#ifdef __MINGW32__
1291// This is a MinGW version of #pragma comment(linker, "...") that doesn't
1292// require compiling with -fms-extensions.
1293#if defined(__i386__)
1294#undef _alloca
1295extern "C" void _alloca(void);
1296static __attribute__((used)) void (*const ref_func)(void) = _alloca;
1297static __attribute__((section(".drectve"), used)) const char export_chkstk[] =
1298 "-export:_alloca";
1299#elif defined(__x86_64__)
1300extern "C" void ___chkstk_ms(void);
1301static __attribute__((used)) void (*const ref_func)(void) = ___chkstk_ms;
1302static __attribute__((section(".drectve"), used)) const char export_chkstk[] =
1303 "-export:___chkstk_ms";
1304#else
1305extern "C" void __chkstk(void);
1306static __attribute__((used)) void (*const ref_func)(void) = __chkstk;
1307static __attribute__((section(".drectve"), used)) const char export_chkstk[] =
1308 "-export:__chkstk";
1309#endif
1310#endif
1311