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