xref: /llvm-project-15.0.7/llvm/tools/lli/lli.cpp (revision f489e2bf)
1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility provides a simple wrapper around the LLVM Execution Engines,
11 // which allow the direct execution of LLVM programs through a Just-In-Time
12 // compiler, or through an interpreter if no JIT is available for this platform.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "OrcLazyJIT.h"
17 #include "RemoteJITUtils.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Bitcode/BitcodeReader.h"
21 #include "llvm/CodeGen/CommandFlags.inc"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/Config/llvm-config.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/ExecutionEngine/Interpreter.h"
26 #include "llvm/ExecutionEngine/JITEventListener.h"
27 #include "llvm/ExecutionEngine/MCJIT.h"
28 #include "llvm/ExecutionEngine/ObjectCache.h"
29 #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
30 #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
31 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/TypeBuilder.h"
37 #include "llvm/IRReader/IRReader.h"
38 #include "llvm/Object/Archive.h"
39 #include "llvm/Object/ObjectFile.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/DynamicLibrary.h"
43 #include "llvm/Support/Format.h"
44 #include "llvm/Support/InitLLVM.h"
45 #include "llvm/Support/ManagedStatic.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/Memory.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/PluginLoader.h"
51 #include "llvm/Support/Process.h"
52 #include "llvm/Support/Program.h"
53 #include "llvm/Support/SourceMgr.h"
54 #include "llvm/Support/TargetSelect.h"
55 #include "llvm/Support/WithColor.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Transforms/Instrumentation.h"
58 #include <cerrno>
59 
60 #ifdef __CYGWIN__
61 #include <cygwin/version.h>
62 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
63 #define DO_NOTHING_ATEXIT 1
64 #endif
65 #endif
66 
67 using namespace llvm;
68 
69 #define DEBUG_TYPE "lli"
70 
71 namespace {
72 
73   enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
74 
75   cl::opt<std::string>
76   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
77 
78   cl::list<std::string>
79   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
80 
81   cl::opt<bool> ForceInterpreter("force-interpreter",
82                                  cl::desc("Force interpretation: disable JIT"),
83                                  cl::init(false));
84 
85   cl::opt<JITKind> UseJITKind("jit-kind",
86                               cl::desc("Choose underlying JIT kind."),
87                               cl::init(JITKind::MCJIT),
88                               cl::values(
89                                 clEnumValN(JITKind::MCJIT, "mcjit",
90                                            "MCJIT"),
91                                 clEnumValN(JITKind::OrcMCJITReplacement,
92                                            "orc-mcjit",
93                                            "Orc-based MCJIT replacement"),
94                                 clEnumValN(JITKind::OrcLazy,
95                                            "orc-lazy",
96                                            "Orc-based lazy JIT.")));
97 
98   // The MCJIT supports building for a target address space separate from
99   // the JIT compilation process. Use a forked process and a copying
100   // memory manager with IPC to execute using this functionality.
101   cl::opt<bool> RemoteMCJIT("remote-mcjit",
102     cl::desc("Execute MCJIT'ed code in a separate process."),
103     cl::init(false));
104 
105   // Manually specify the child process for remote execution. This overrides
106   // the simulated remote execution that allocates address space for child
107   // execution. The child process will be executed and will communicate with
108   // lli via stdin/stdout pipes.
109   cl::opt<std::string>
110   ChildExecPath("mcjit-remote-process",
111                 cl::desc("Specify the filename of the process to launch "
112                          "for remote MCJIT execution.  If none is specified,"
113                          "\n\tremote execution will be simulated in-process."),
114                 cl::value_desc("filename"), cl::init(""));
115 
116   // Determine optimization level.
117   cl::opt<char>
118   OptLevel("O",
119            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
120                     "(default = '-O2')"),
121            cl::Prefix,
122            cl::ZeroOrMore,
123            cl::init(' '));
124 
125   cl::opt<std::string>
126   TargetTriple("mtriple", cl::desc("Override target triple for module"));
127 
128   cl::opt<std::string>
129   EntryFunc("entry-function",
130             cl::desc("Specify the entry function (default = 'main') "
131                      "of the executable"),
132             cl::value_desc("function"),
133             cl::init("main"));
134 
135   cl::list<std::string>
136   ExtraModules("extra-module",
137          cl::desc("Extra modules to be loaded"),
138          cl::value_desc("input bitcode"));
139 
140   cl::list<std::string>
141   ExtraObjects("extra-object",
142          cl::desc("Extra object files to be loaded"),
143          cl::value_desc("input object"));
144 
145   cl::list<std::string>
146   ExtraArchives("extra-archive",
147          cl::desc("Extra archive files to be loaded"),
148          cl::value_desc("input archive"));
149 
150   cl::opt<bool>
151   EnableCacheManager("enable-cache-manager",
152         cl::desc("Use cache manager to save/load mdoules"),
153         cl::init(false));
154 
155   cl::opt<std::string>
156   ObjectCacheDir("object-cache-dir",
157                   cl::desc("Directory to store cached object files "
158                            "(must be user writable)"),
159                   cl::init(""));
160 
161   cl::opt<std::string>
162   FakeArgv0("fake-argv0",
163             cl::desc("Override the 'argv[0]' value passed into the executing"
164                      " program"), cl::value_desc("executable"));
165 
166   cl::opt<bool>
167   DisableCoreFiles("disable-core-files", cl::Hidden,
168                    cl::desc("Disable emission of core files if possible"));
169 
170   cl::opt<bool>
171   NoLazyCompilation("disable-lazy-compilation",
172                   cl::desc("Disable JIT lazy compilation"),
173                   cl::init(false));
174 
175   cl::opt<bool>
176   GenerateSoftFloatCalls("soft-float",
177     cl::desc("Generate software floating point library calls"),
178     cl::init(false));
179 
180   ExitOnError ExitOnErr;
181 }
182 
183 //===----------------------------------------------------------------------===//
184 // Object cache
185 //
186 // This object cache implementation writes cached objects to disk to the
187 // directory specified by CacheDir, using a filename provided in the module
188 // descriptor. The cache tries to load a saved object using that path if the
189 // file exists. CacheDir defaults to "", in which case objects are cached
190 // alongside their originating bitcodes.
191 //
192 class LLIObjectCache : public ObjectCache {
193 public:
194   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
195     // Add trailing '/' to cache dir if necessary.
196     if (!this->CacheDir.empty() &&
197         this->CacheDir[this->CacheDir.size() - 1] != '/')
198       this->CacheDir += '/';
199   }
200   ~LLIObjectCache() override {}
201 
202   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
203     const std::string &ModuleID = M->getModuleIdentifier();
204     std::string CacheName;
205     if (!getCacheFilename(ModuleID, CacheName))
206       return;
207     if (!CacheDir.empty()) { // Create user-defined cache dir.
208       SmallString<128> dir(sys::path::parent_path(CacheName));
209       sys::fs::create_directories(Twine(dir));
210     }
211     std::error_code EC;
212     raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
213     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
214     outfile.close();
215   }
216 
217   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
218     const std::string &ModuleID = M->getModuleIdentifier();
219     std::string CacheName;
220     if (!getCacheFilename(ModuleID, CacheName))
221       return nullptr;
222     // Load the object from the cache filename
223     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
224         MemoryBuffer::getFile(CacheName, -1, false);
225     // If the file isn't there, that's OK.
226     if (!IRObjectBuffer)
227       return nullptr;
228     // MCJIT will want to write into this buffer, and we don't want that
229     // because the file has probably just been mmapped.  Instead we make
230     // a copy.  The filed-based buffer will be released when it goes
231     // out of scope.
232     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
233   }
234 
235 private:
236   std::string CacheDir;
237 
238   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
239     std::string Prefix("file:");
240     size_t PrefixLength = Prefix.length();
241     if (ModID.substr(0, PrefixLength) != Prefix)
242       return false;
243         std::string CacheSubdir = ModID.substr(PrefixLength);
244 #if defined(_WIN32)
245         // Transform "X:\foo" => "/X\foo" for convenience.
246         if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
247           CacheSubdir[1] = CacheSubdir[0];
248           CacheSubdir[0] = '/';
249         }
250 #endif
251     CacheName = CacheDir + CacheSubdir;
252     size_t pos = CacheName.rfind('.');
253     CacheName.replace(pos, CacheName.length() - pos, ".o");
254     return true;
255   }
256 };
257 
258 // On Mingw and Cygwin, an external symbol named '__main' is called from the
259 // generated 'main' function to allow static initialization.  To avoid linking
260 // problems with remote targets (because lli's remote target support does not
261 // currently handle external linking) we add a secondary module which defines
262 // an empty '__main' function.
263 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
264                                   StringRef TargetTripleStr) {
265   IRBuilder<> Builder(Context);
266   Triple TargetTriple(TargetTripleStr);
267 
268   // Create a new module.
269   std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
270   M->setTargetTriple(TargetTripleStr);
271 
272   // Create an empty function named "__main".
273   Function *Result;
274   if (TargetTriple.isArch64Bit()) {
275     Result = Function::Create(
276       TypeBuilder<int64_t(void), false>::get(Context),
277       GlobalValue::ExternalLinkage, "__main", M.get());
278   } else {
279     Result = Function::Create(
280       TypeBuilder<int32_t(void), false>::get(Context),
281       GlobalValue::ExternalLinkage, "__main", M.get());
282   }
283   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
284   Builder.SetInsertPoint(BB);
285   Value *ReturnVal;
286   if (TargetTriple.isArch64Bit())
287     ReturnVal = ConstantInt::get(Context, APInt(64, 0));
288   else
289     ReturnVal = ConstantInt::get(Context, APInt(32, 0));
290   Builder.CreateRet(ReturnVal);
291 
292   // Add this new module to the ExecutionEngine.
293   EE.addModule(std::move(M));
294 }
295 
296 CodeGenOpt::Level getOptLevel() {
297   switch (OptLevel) {
298   default:
299     WithColor::error(errs(), "lli") << "invalid optimization level.\n";
300     exit(1);
301   case '0': return CodeGenOpt::None;
302   case '1': return CodeGenOpt::Less;
303   case ' ':
304   case '2': return CodeGenOpt::Default;
305   case '3': return CodeGenOpt::Aggressive;
306   }
307   llvm_unreachable("Unrecognized opt level.");
308 }
309 
310 LLVM_ATTRIBUTE_NORETURN
311 static void reportError(SMDiagnostic Err, const char *ProgName) {
312   Err.print(ProgName, errs());
313   exit(1);
314 }
315 
316 //===----------------------------------------------------------------------===//
317 // main Driver function
318 //
319 int main(int argc, char **argv, char * const *envp) {
320   InitLLVM X(argc, argv);
321 
322   if (argc > 1)
323     ExitOnErr.setBanner(std::string(argv[0]) + ": ");
324 
325   // If we have a native target, initialize it to ensure it is linked in and
326   // usable by the JIT.
327   InitializeNativeTarget();
328   InitializeNativeTargetAsmPrinter();
329   InitializeNativeTargetAsmParser();
330 
331   cl::ParseCommandLineOptions(argc, argv,
332                               "llvm interpreter & dynamic compiler\n");
333 
334   // If the user doesn't want core files, disable them.
335   if (DisableCoreFiles)
336     sys::Process::PreventCoreFiles();
337 
338   LLVMContext Context;
339 
340   // Load the bitcode...
341   SMDiagnostic Err;
342   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
343   Module *Mod = Owner.get();
344   if (!Mod)
345     reportError(Err, argv[0]);
346 
347   if (UseJITKind == JITKind::OrcLazy) {
348     std::vector<std::unique_ptr<Module>> Ms;
349     Ms.push_back(std::move(Owner));
350     for (auto &ExtraMod : ExtraModules) {
351       Ms.push_back(parseIRFile(ExtraMod, Err, Context));
352       if (!Ms.back())
353         reportError(Err, argv[0]);
354     }
355     std::vector<std::string> Args;
356     Args.push_back(InputFile);
357     for (auto &Arg : InputArgv)
358       Args.push_back(Arg);
359     return runOrcLazyJIT(std::move(Ms), Args);
360   }
361 
362   if (EnableCacheManager) {
363     std::string CacheName("file:");
364     CacheName.append(InputFile);
365     Mod->setModuleIdentifier(CacheName);
366   }
367 
368   // If not jitting lazily, load the whole bitcode file eagerly too.
369   if (NoLazyCompilation) {
370     // Use *argv instead of argv[0] to work around a wrong GCC warning.
371     ExitOnError ExitOnErr(std::string(*argv) +
372                           ": bitcode didn't read correctly: ");
373     ExitOnErr(Mod->materializeAll());
374   }
375 
376   std::string ErrorMsg;
377   EngineBuilder builder(std::move(Owner));
378   builder.setMArch(MArch);
379   builder.setMCPU(getCPUStr());
380   builder.setMAttrs(getFeatureList());
381   if (RelocModel.getNumOccurrences())
382     builder.setRelocationModel(RelocModel);
383   if (CMModel.getNumOccurrences())
384     builder.setCodeModel(CMModel);
385   builder.setErrorStr(&ErrorMsg);
386   builder.setEngineKind(ForceInterpreter
387                         ? EngineKind::Interpreter
388                         : EngineKind::JIT);
389   builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
390 
391   // If we are supposed to override the target triple, do so now.
392   if (!TargetTriple.empty())
393     Mod->setTargetTriple(Triple::normalize(TargetTriple));
394 
395   // Enable MCJIT if desired.
396   RTDyldMemoryManager *RTDyldMM = nullptr;
397   if (!ForceInterpreter) {
398     if (RemoteMCJIT)
399       RTDyldMM = new ForwardingMemoryManager();
400     else
401       RTDyldMM = new SectionMemoryManager();
402 
403     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
404     // RTDyldMM: We still use it below, even though we don't own it.
405     builder.setMCJITMemoryManager(
406       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
407   } else if (RemoteMCJIT) {
408     WithColor::error(errs(), argv[0])
409         << "remote process execution does not work with the interpreter.\n";
410     exit(1);
411   }
412 
413   builder.setOptLevel(getOptLevel());
414 
415   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
416   if (FloatABIForCalls != FloatABI::Default)
417     Options.FloatABIType = FloatABIForCalls;
418 
419   builder.setTargetOptions(Options);
420 
421   std::unique_ptr<ExecutionEngine> EE(builder.create());
422   if (!EE) {
423     if (!ErrorMsg.empty())
424       WithColor::error(errs(), argv[0])
425           << "error creating EE: " << ErrorMsg << "\n";
426     else
427       WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
428     exit(1);
429   }
430 
431   std::unique_ptr<LLIObjectCache> CacheManager;
432   if (EnableCacheManager) {
433     CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
434     EE->setObjectCache(CacheManager.get());
435   }
436 
437   // Load any additional modules specified on the command line.
438   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
439     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
440     if (!XMod)
441       reportError(Err, argv[0]);
442     if (EnableCacheManager) {
443       std::string CacheName("file:");
444       CacheName.append(ExtraModules[i]);
445       XMod->setModuleIdentifier(CacheName);
446     }
447     EE->addModule(std::move(XMod));
448   }
449 
450   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
451     Expected<object::OwningBinary<object::ObjectFile>> Obj =
452         object::ObjectFile::createObjectFile(ExtraObjects[i]);
453     if (!Obj) {
454       // TODO: Actually report errors helpfully.
455       consumeError(Obj.takeError());
456       reportError(Err, argv[0]);
457     }
458     object::OwningBinary<object::ObjectFile> &O = Obj.get();
459     EE->addObjectFile(std::move(O));
460   }
461 
462   for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
463     ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
464         MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
465     if (!ArBufOrErr)
466       reportError(Err, argv[0]);
467     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
468 
469     Expected<std::unique_ptr<object::Archive>> ArOrErr =
470         object::Archive::create(ArBuf->getMemBufferRef());
471     if (!ArOrErr) {
472       std::string Buf;
473       raw_string_ostream OS(Buf);
474       logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
475       OS.flush();
476       errs() << Buf;
477       exit(1);
478     }
479     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
480 
481     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
482 
483     EE->addArchive(std::move(OB));
484   }
485 
486   // If the target is Cygwin/MingW and we are generating remote code, we
487   // need an extra module to help out with linking.
488   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
489     addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
490   }
491 
492   // The following functions have no effect if their respective profiling
493   // support wasn't enabled in the build configuration.
494   EE->RegisterJITEventListener(
495                 JITEventListener::createOProfileJITEventListener());
496   EE->RegisterJITEventListener(
497                 JITEventListener::createIntelJITEventListener());
498 
499   if (!NoLazyCompilation && RemoteMCJIT) {
500     WithColor::warning(errs(), argv[0])
501         << "remote mcjit does not support lazy compilation\n";
502     NoLazyCompilation = true;
503   }
504   EE->DisableLazyCompilation(NoLazyCompilation);
505 
506   // If the user specifically requested an argv[0] to pass into the program,
507   // do it now.
508   if (!FakeArgv0.empty()) {
509     InputFile = static_cast<std::string>(FakeArgv0);
510   } else {
511     // Otherwise, if there is a .bc suffix on the executable strip it off, it
512     // might confuse the program.
513     if (StringRef(InputFile).endswith(".bc"))
514       InputFile.erase(InputFile.length() - 3);
515   }
516 
517   // Add the module's name to the start of the vector of arguments to main().
518   InputArgv.insert(InputArgv.begin(), InputFile);
519 
520   // Call the main function from M as if its signature were:
521   //   int main (int argc, char **argv, const char **envp)
522   // using the contents of Args to determine argc & argv, and the contents of
523   // EnvVars to determine envp.
524   //
525   Function *EntryFn = Mod->getFunction(EntryFunc);
526   if (!EntryFn) {
527     WithColor::error(errs(), argv[0])
528         << '\'' << EntryFunc << "\' function not found in module.\n";
529     return -1;
530   }
531 
532   // Reset errno to zero on entry to main.
533   errno = 0;
534 
535   int Result = -1;
536 
537   // Sanity check use of remote-jit: LLI currently only supports use of the
538   // remote JIT on Unix platforms.
539   if (RemoteMCJIT) {
540 #ifndef LLVM_ON_UNIX
541     WithColor::warning(errs(), argv[0])
542         << "host does not support external remote targets.\n";
543     WithColor::note() << "defaulting to local execution\n";
544     return -1;
545 #else
546     if (ChildExecPath.empty()) {
547       WithColor::error(errs(), argv[0])
548           << "-remote-mcjit requires -mcjit-remote-process.\n";
549       exit(1);
550     } else if (!sys::fs::can_execute(ChildExecPath)) {
551       WithColor::error(errs(), argv[0])
552           << "unable to find usable child executable: '" << ChildExecPath
553           << "'\n";
554       return -1;
555     }
556 #endif
557   }
558 
559   if (!RemoteMCJIT) {
560     // If the program doesn't explicitly call exit, we will need the Exit
561     // function later on to make an explicit call, so get the function now.
562     Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
563                                                       Type::getInt32Ty(Context));
564 
565     // Run static constructors.
566     if (!ForceInterpreter) {
567       // Give MCJIT a chance to apply relocations and set page permissions.
568       EE->finalizeObject();
569     }
570     EE->runStaticConstructorsDestructors(false);
571 
572     // Trigger compilation separately so code regions that need to be
573     // invalidated will be known.
574     (void)EE->getPointerToFunction(EntryFn);
575     // Clear instruction cache before code will be executed.
576     if (RTDyldMM)
577       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
578 
579     // Run main.
580     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
581 
582     // Run static destructors.
583     EE->runStaticConstructorsDestructors(true);
584 
585     // If the program didn't call exit explicitly, we should call it now.
586     // This ensures that any atexit handlers get called correctly.
587     if (Function *ExitF = dyn_cast<Function>(Exit)) {
588       std::vector<GenericValue> Args;
589       GenericValue ResultGV;
590       ResultGV.IntVal = APInt(32, Result);
591       Args.push_back(ResultGV);
592       EE->runFunction(ExitF, Args);
593       WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
594       abort();
595     } else {
596       WithColor::error(errs(), argv[0])
597           << "exit defined with wrong prototype!\n";
598       abort();
599     }
600   } else {
601     // else == "if (RemoteMCJIT)"
602 
603     // Remote target MCJIT doesn't (yet) support static constructors. No reason
604     // it couldn't. This is a limitation of the LLI implementation, not the
605     // MCJIT itself. FIXME.
606 
607     // Lanch the remote process and get a channel to it.
608     std::unique_ptr<FDRawChannel> C = launchRemote();
609     if (!C) {
610       WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
611       exit(1);
612     }
613 
614     // Create a remote target client running over the channel.
615     typedef orc::remote::OrcRemoteTargetClient MyRemote;
616     auto R = ExitOnErr(MyRemote::Create(*C, ExitOnErr));
617 
618     // Create a remote memory manager.
619     auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
620 
621     // Forward MCJIT's memory manager calls to the remote memory manager.
622     static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
623       std::move(RemoteMM));
624 
625     // Forward MCJIT's symbol resolution calls to the remote.
626     static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
627         orc::createLambdaResolver(
628             [](const std::string &Name) { return nullptr; },
629             [&](const std::string &Name) {
630               if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
631                 return JITSymbol(Addr, JITSymbolFlags::Exported);
632               return JITSymbol(nullptr);
633             }));
634 
635     // Grab the target address of the JIT'd main function on the remote and call
636     // it.
637     // FIXME: argv and envp handling.
638     JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
639     EE->finalizeObject();
640     DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
641                  << format("%llx", Entry) << "\n");
642     Result = ExitOnErr(R->callIntVoid(Entry));
643 
644     // Like static constructors, the remote target MCJIT support doesn't handle
645     // this yet. It could. FIXME.
646 
647     // Delete the EE - we need to tear it down *before* we terminate the session
648     // with the remote, otherwise it'll crash when it tries to release resources
649     // on a remote that has already been disconnected.
650     EE.reset();
651 
652     // Signal the remote target that we're done JITing.
653     ExitOnErr(R->terminateSession());
654   }
655 
656   return Result;
657 }
658 
659 std::unique_ptr<FDRawChannel> launchRemote() {
660 #ifndef LLVM_ON_UNIX
661   llvm_unreachable("launchRemote not supported on non-Unix platforms");
662 #else
663   int PipeFD[2][2];
664   pid_t ChildPID;
665 
666   // Create two pipes.
667   if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
668     perror("Error creating pipe: ");
669 
670   ChildPID = fork();
671 
672   if (ChildPID == 0) {
673     // In the child...
674 
675     // Close the parent ends of the pipes
676     close(PipeFD[0][1]);
677     close(PipeFD[1][0]);
678 
679 
680     // Execute the child process.
681     std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
682     {
683       ChildPath.reset(new char[ChildExecPath.size() + 1]);
684       std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
685       ChildPath[ChildExecPath.size()] = '\0';
686       std::string ChildInStr = utostr(PipeFD[0][0]);
687       ChildIn.reset(new char[ChildInStr.size() + 1]);
688       std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
689       ChildIn[ChildInStr.size()] = '\0';
690       std::string ChildOutStr = utostr(PipeFD[1][1]);
691       ChildOut.reset(new char[ChildOutStr.size() + 1]);
692       std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
693       ChildOut[ChildOutStr.size()] = '\0';
694     }
695 
696     char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
697     int rc = execv(ChildExecPath.c_str(), args);
698     if (rc != 0)
699       perror("Error executing child process: ");
700     llvm_unreachable("Error executing child process");
701   }
702   // else we're the parent...
703 
704   // Close the child ends of the pipes
705   close(PipeFD[0][0]);
706   close(PipeFD[1][1]);
707 
708   // Return an RPC channel connected to our end of the pipes.
709   return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
710 #endif
711 }
712