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