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