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