xref: /llvm-project-15.0.7/llvm/tools/lli/lli.cpp (revision 2da3facd)
1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This utility provides a simple wrapper around the LLVM Execution Engines,
10 // which allow the direct execution of LLVM programs through a Just-In-Time
11 // compiler, or through an interpreter if no JIT is available for this platform.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ExecutionUtils.h"
16 #include "ForwardingMemoryManager.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Bitcode/BitcodeReader.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/Config/llvm-config.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/ExecutionEngine/Interpreter.h"
25 #include "llvm/ExecutionEngine/JITEventListener.h"
26 #include "llvm/ExecutionEngine/JITSymbol.h"
27 #include "llvm/ExecutionEngine/MCJIT.h"
28 #include "llvm/ExecutionEngine/ObjectCache.h"
29 #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
30 #include "llvm/ExecutionEngine/Orc/DebugUtils.h"
31 #include "llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h"
32 #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"
33 #include "llvm/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.h"
34 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
35 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
36 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
37 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
38 #include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h"
39 #include "llvm/ExecutionEngine/Orc/SymbolStringPool.h"
40 #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
41 #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
42 #include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
43 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
44 #include "llvm/IR/IRBuilder.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/IR/Verifier.h"
49 #include "llvm/IRReader/IRReader.h"
50 #include "llvm/Object/Archive.h"
51 #include "llvm/Object/ObjectFile.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/DynamicLibrary.h"
55 #include "llvm/Support/Format.h"
56 #include "llvm/Support/InitLLVM.h"
57 #include "llvm/Support/ManagedStatic.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/Memory.h"
60 #include "llvm/Support/MemoryBuffer.h"
61 #include "llvm/Support/Path.h"
62 #include "llvm/Support/PluginLoader.h"
63 #include "llvm/Support/Process.h"
64 #include "llvm/Support/Program.h"
65 #include "llvm/Support/SourceMgr.h"
66 #include "llvm/Support/TargetSelect.h"
67 #include "llvm/Support/WithColor.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Transforms/Instrumentation.h"
70 #include <cerrno>
71 
72 #if !defined(_MSC_VER) && !defined(__MINGW32__)
73 #include <unistd.h>
74 #else
75 #include <io.h>
76 #endif
77 
78 #ifdef __CYGWIN__
79 #include <cygwin/version.h>
80 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
81 #define DO_NOTHING_ATEXIT 1
82 #endif
83 #endif
84 
85 using namespace llvm;
86 
87 static codegen::RegisterCodeGenFlags CGF;
88 
89 #define DEBUG_TYPE "lli"
90 
91 namespace {
92 
93   enum class JITKind { MCJIT, Orc, OrcLazy };
94   enum class JITLinkerKind { Default, RuntimeDyld, JITLink };
95 
96   cl::opt<std::string>
97   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
98 
99   cl::list<std::string>
100   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
101 
102   cl::opt<bool> ForceInterpreter("force-interpreter",
103                                  cl::desc("Force interpretation: disable JIT"),
104                                  cl::init(false));
105 
106   cl::opt<JITKind> UseJITKind(
107       "jit-kind", cl::desc("Choose underlying JIT kind."),
108       cl::init(JITKind::Orc),
109       cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
110                  clEnumValN(JITKind::Orc, "orc", "Orc JIT"),
111                  clEnumValN(JITKind::OrcLazy, "orc-lazy",
112                             "Orc-based lazy JIT.")));
113 
114   cl::opt<JITLinkerKind>
115       JITLinker("jit-linker", cl::desc("Choose the dynamic linker/loader."),
116                 cl::init(JITLinkerKind::Default),
117                 cl::values(clEnumValN(JITLinkerKind::Default, "default",
118                                       "Default for platform and JIT-kind"),
119                            clEnumValN(JITLinkerKind::RuntimeDyld, "rtdyld",
120                                       "RuntimeDyld"),
121                            clEnumValN(JITLinkerKind::JITLink, "jitlink",
122                                       "Orc-specific linker")));
123 
124   cl::opt<unsigned>
125   LazyJITCompileThreads("compile-threads",
126                         cl::desc("Choose the number of compile threads "
127                                  "(jit-kind=orc-lazy only)"),
128                         cl::init(0));
129 
130   cl::list<std::string>
131   ThreadEntryPoints("thread-entry",
132                     cl::desc("calls the given entry-point on a new thread "
133                              "(jit-kind=orc-lazy only)"));
134 
135   cl::opt<bool> PerModuleLazy(
136       "per-module-lazy",
137       cl::desc("Performs lazy compilation on whole module boundaries "
138                "rather than individual functions"),
139       cl::init(false));
140 
141   cl::list<std::string>
142       JITDylibs("jd",
143                 cl::desc("Specifies the JITDylib to be used for any subsequent "
144                          "-extra-module arguments."));
145 
146   cl::list<std::string>
147     Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"),
148            cl::ZeroOrMore);
149 
150   // The MCJIT supports building for a target address space separate from
151   // the JIT compilation process. Use a forked process and a copying
152   // memory manager with IPC to execute using this functionality.
153   cl::opt<bool> RemoteMCJIT("remote-mcjit",
154     cl::desc("Execute MCJIT'ed code in a separate process."),
155     cl::init(false));
156 
157   // Manually specify the child process for remote execution. This overrides
158   // the simulated remote execution that allocates address space for child
159   // execution. The child process will be executed and will communicate with
160   // lli via stdin/stdout pipes.
161   cl::opt<std::string>
162   ChildExecPath("mcjit-remote-process",
163                 cl::desc("Specify the filename of the process to launch "
164                          "for remote MCJIT execution.  If none is specified,"
165                          "\n\tremote execution will be simulated in-process."),
166                 cl::value_desc("filename"), cl::init(""));
167 
168   // Determine optimization level.
169   cl::opt<char>
170   OptLevel("O",
171            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
172                     "(default = '-O2')"),
173            cl::Prefix,
174            cl::ZeroOrMore,
175            cl::init(' '));
176 
177   cl::opt<std::string>
178   TargetTriple("mtriple", cl::desc("Override target triple for module"));
179 
180   cl::opt<std::string>
181   EntryFunc("entry-function",
182             cl::desc("Specify the entry function (default = 'main') "
183                      "of the executable"),
184             cl::value_desc("function"),
185             cl::init("main"));
186 
187   cl::list<std::string>
188   ExtraModules("extra-module",
189          cl::desc("Extra modules to be loaded"),
190          cl::value_desc("input bitcode"));
191 
192   cl::list<std::string>
193   ExtraObjects("extra-object",
194          cl::desc("Extra object files to be loaded"),
195          cl::value_desc("input object"));
196 
197   cl::list<std::string>
198   ExtraArchives("extra-archive",
199          cl::desc("Extra archive files to be loaded"),
200          cl::value_desc("input archive"));
201 
202   cl::opt<bool>
203   EnableCacheManager("enable-cache-manager",
204         cl::desc("Use cache manager to save/load modules"),
205         cl::init(false));
206 
207   cl::opt<std::string>
208   ObjectCacheDir("object-cache-dir",
209                   cl::desc("Directory to store cached object files "
210                            "(must be user writable)"),
211                   cl::init(""));
212 
213   cl::opt<std::string>
214   FakeArgv0("fake-argv0",
215             cl::desc("Override the 'argv[0]' value passed into the executing"
216                      " program"), cl::value_desc("executable"));
217 
218   cl::opt<bool>
219   DisableCoreFiles("disable-core-files", cl::Hidden,
220                    cl::desc("Disable emission of core files if possible"));
221 
222   cl::opt<bool>
223   NoLazyCompilation("disable-lazy-compilation",
224                   cl::desc("Disable JIT lazy compilation"),
225                   cl::init(false));
226 
227   cl::opt<bool>
228   GenerateSoftFloatCalls("soft-float",
229     cl::desc("Generate software floating point library calls"),
230     cl::init(false));
231 
232   cl::opt<bool> NoProcessSymbols(
233       "no-process-syms",
234       cl::desc("Do not resolve lli process symbols in JIT'd code"),
235       cl::init(false));
236 
237   enum class LLJITPlatform { Inactive, DetectHost, GenericIR };
238 
239   cl::opt<LLJITPlatform>
240       Platform("lljit-platform", cl::desc("Platform to use with LLJIT"),
241                cl::init(LLJITPlatform::DetectHost),
242                cl::values(clEnumValN(LLJITPlatform::DetectHost, "DetectHost",
243                                      "Select based on JIT target triple"),
244                           clEnumValN(LLJITPlatform::GenericIR, "GenericIR",
245                                      "Use LLJITGenericIRPlatform"),
246                           clEnumValN(LLJITPlatform::Inactive, "Inactive",
247                                      "Disable platform support explicitly")),
248                cl::Hidden);
249 
250   enum class DumpKind {
251     NoDump,
252     DumpFuncsToStdOut,
253     DumpModsToStdOut,
254     DumpModsToDisk
255   };
256 
257   cl::opt<DumpKind> OrcDumpKind(
258       "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
259       cl::init(DumpKind::NoDump),
260       cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
261                             "Don't dump anything."),
262                  clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
263                             "Dump function names to stdout."),
264                  clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
265                             "Dump modules to stdout."),
266                  clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
267                             "Dump modules to the current "
268                             "working directory. (WARNING: "
269                             "will overwrite existing files).")),
270       cl::Hidden);
271 
272   cl::list<BuiltinFunctionKind> GenerateBuiltinFunctions(
273       "generate",
274       cl::desc("Provide built-in functions for access by JITed code "
275                "(jit-kind=orc-lazy only)"),
276       cl::values(clEnumValN(BuiltinFunctionKind::DumpDebugDescriptor,
277                             "__dump_jit_debug_descriptor",
278                             "Dump __jit_debug_descriptor contents to stdout"),
279                  clEnumValN(BuiltinFunctionKind::DumpDebugObjects,
280                             "__dump_jit_debug_objects",
281                             "Dump __jit_debug_descriptor in-memory debug "
282                             "objects as tool output")),
283       cl::Hidden);
284 
285   ExitOnError ExitOnErr;
286 }
287 
288 LLVM_ATTRIBUTE_USED void linkComponents() {
289   errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper
290          << (void *)&llvm_orc_deregisterEHFrameSectionWrapper
291          << (void *)&llvm_orc_registerJITLoaderGDBWrapper;
292 }
293 
294 //===----------------------------------------------------------------------===//
295 // Object cache
296 //
297 // This object cache implementation writes cached objects to disk to the
298 // directory specified by CacheDir, using a filename provided in the module
299 // descriptor. The cache tries to load a saved object using that path if the
300 // file exists. CacheDir defaults to "", in which case objects are cached
301 // alongside their originating bitcodes.
302 //
303 class LLIObjectCache : public ObjectCache {
304 public:
305   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
306     // Add trailing '/' to cache dir if necessary.
307     if (!this->CacheDir.empty() &&
308         this->CacheDir[this->CacheDir.size() - 1] != '/')
309       this->CacheDir += '/';
310   }
311   ~LLIObjectCache() override {}
312 
313   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
314     const std::string &ModuleID = M->getModuleIdentifier();
315     std::string CacheName;
316     if (!getCacheFilename(ModuleID, CacheName))
317       return;
318     if (!CacheDir.empty()) { // Create user-defined cache dir.
319       SmallString<128> dir(sys::path::parent_path(CacheName));
320       sys::fs::create_directories(Twine(dir));
321     }
322 
323     std::error_code EC;
324     raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
325     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
326     outfile.close();
327   }
328 
329   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
330     const std::string &ModuleID = M->getModuleIdentifier();
331     std::string CacheName;
332     if (!getCacheFilename(ModuleID, CacheName))
333       return nullptr;
334     // Load the object from the cache filename
335     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
336         MemoryBuffer::getFile(CacheName, /*IsText=*/false,
337                               /*RequiresNullTerminator=*/false);
338     // If the file isn't there, that's OK.
339     if (!IRObjectBuffer)
340       return nullptr;
341     // MCJIT will want to write into this buffer, and we don't want that
342     // because the file has probably just been mmapped.  Instead we make
343     // a copy.  The filed-based buffer will be released when it goes
344     // out of scope.
345     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
346   }
347 
348 private:
349   std::string CacheDir;
350 
351   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
352     std::string Prefix("file:");
353     size_t PrefixLength = Prefix.length();
354     if (ModID.substr(0, PrefixLength) != Prefix)
355       return false;
356 
357     std::string CacheSubdir = ModID.substr(PrefixLength);
358 #if defined(_WIN32)
359     // Transform "X:\foo" => "/X\foo" for convenience.
360     if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
361       CacheSubdir[1] = CacheSubdir[0];
362       CacheSubdir[0] = '/';
363     }
364 #endif
365 
366     CacheName = CacheDir + CacheSubdir;
367     size_t pos = CacheName.rfind('.');
368     CacheName.replace(pos, CacheName.length() - pos, ".o");
369     return true;
370   }
371 };
372 
373 // On Mingw and Cygwin, an external symbol named '__main' is called from the
374 // generated 'main' function to allow static initialization.  To avoid linking
375 // problems with remote targets (because lli's remote target support does not
376 // currently handle external linking) we add a secondary module which defines
377 // an empty '__main' function.
378 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
379                                   StringRef TargetTripleStr) {
380   IRBuilder<> Builder(Context);
381   Triple TargetTriple(TargetTripleStr);
382 
383   // Create a new module.
384   std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
385   M->setTargetTriple(TargetTripleStr);
386 
387   // Create an empty function named "__main".
388   Type *ReturnTy;
389   if (TargetTriple.isArch64Bit())
390     ReturnTy = Type::getInt64Ty(Context);
391   else
392     ReturnTy = Type::getInt32Ty(Context);
393   Function *Result =
394       Function::Create(FunctionType::get(ReturnTy, {}, false),
395                        GlobalValue::ExternalLinkage, "__main", M.get());
396 
397   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
398   Builder.SetInsertPoint(BB);
399   Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
400   Builder.CreateRet(ReturnVal);
401 
402   // Add this new module to the ExecutionEngine.
403   EE.addModule(std::move(M));
404 }
405 
406 CodeGenOpt::Level getOptLevel() {
407   switch (OptLevel) {
408   default:
409     WithColor::error(errs(), "lli") << "invalid optimization level.\n";
410     exit(1);
411   case '0': return CodeGenOpt::None;
412   case '1': return CodeGenOpt::Less;
413   case ' ':
414   case '2': return CodeGenOpt::Default;
415   case '3': return CodeGenOpt::Aggressive;
416   }
417   llvm_unreachable("Unrecognized opt level.");
418 }
419 
420 [[noreturn]] static void reportError(SMDiagnostic Err, const char *ProgName) {
421   Err.print(ProgName, errs());
422   exit(1);
423 }
424 
425 Error loadDylibs();
426 int runOrcJIT(const char *ProgName);
427 void disallowOrcOptions();
428 Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote();
429 
430 //===----------------------------------------------------------------------===//
431 // main Driver function
432 //
433 int main(int argc, char **argv, char * const *envp) {
434   InitLLVM X(argc, argv);
435 
436   if (argc > 1)
437     ExitOnErr.setBanner(std::string(argv[0]) + ": ");
438 
439   // If we have a native target, initialize it to ensure it is linked in and
440   // usable by the JIT.
441   InitializeNativeTarget();
442   InitializeNativeTargetAsmPrinter();
443   InitializeNativeTargetAsmParser();
444 
445   cl::ParseCommandLineOptions(argc, argv,
446                               "llvm interpreter & dynamic compiler\n");
447 
448   // If the user doesn't want core files, disable them.
449   if (DisableCoreFiles)
450     sys::Process::PreventCoreFiles();
451 
452   ExitOnErr(loadDylibs());
453 
454   if (UseJITKind == JITKind::MCJIT)
455     disallowOrcOptions();
456   else
457     return runOrcJIT(argv[0]);
458 
459   // Old lli implementation based on ExecutionEngine and MCJIT.
460   LLVMContext Context;
461 
462   // Load the bitcode...
463   SMDiagnostic Err;
464   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
465   Module *Mod = Owner.get();
466   if (!Mod)
467     reportError(Err, argv[0]);
468 
469   if (EnableCacheManager) {
470     std::string CacheName("file:");
471     CacheName.append(InputFile);
472     Mod->setModuleIdentifier(CacheName);
473   }
474 
475   // If not jitting lazily, load the whole bitcode file eagerly too.
476   if (NoLazyCompilation) {
477     // Use *argv instead of argv[0] to work around a wrong GCC warning.
478     ExitOnError ExitOnErr(std::string(*argv) +
479                           ": bitcode didn't read correctly: ");
480     ExitOnErr(Mod->materializeAll());
481   }
482 
483   std::string ErrorMsg;
484   EngineBuilder builder(std::move(Owner));
485   builder.setMArch(codegen::getMArch());
486   builder.setMCPU(codegen::getCPUStr());
487   builder.setMAttrs(codegen::getFeatureList());
488   if (auto RM = codegen::getExplicitRelocModel())
489     builder.setRelocationModel(RM.getValue());
490   if (auto CM = codegen::getExplicitCodeModel())
491     builder.setCodeModel(CM.getValue());
492   builder.setErrorStr(&ErrorMsg);
493   builder.setEngineKind(ForceInterpreter
494                         ? EngineKind::Interpreter
495                         : EngineKind::JIT);
496 
497   // If we are supposed to override the target triple, do so now.
498   if (!TargetTriple.empty())
499     Mod->setTargetTriple(Triple::normalize(TargetTriple));
500 
501   // Enable MCJIT if desired.
502   RTDyldMemoryManager *RTDyldMM = nullptr;
503   if (!ForceInterpreter) {
504     if (RemoteMCJIT)
505       RTDyldMM = new ForwardingMemoryManager();
506     else
507       RTDyldMM = new SectionMemoryManager();
508 
509     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
510     // RTDyldMM: We still use it below, even though we don't own it.
511     builder.setMCJITMemoryManager(
512       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
513   } else if (RemoteMCJIT) {
514     WithColor::error(errs(), argv[0])
515         << "remote process execution does not work with the interpreter.\n";
516     exit(1);
517   }
518 
519   builder.setOptLevel(getOptLevel());
520 
521   TargetOptions Options =
522       codegen::InitTargetOptionsFromCodeGenFlags(Triple(TargetTriple));
523   if (codegen::getFloatABIForCalls() != FloatABI::Default)
524     Options.FloatABIType = codegen::getFloatABIForCalls();
525 
526   builder.setTargetOptions(Options);
527 
528   std::unique_ptr<ExecutionEngine> EE(builder.create());
529   if (!EE) {
530     if (!ErrorMsg.empty())
531       WithColor::error(errs(), argv[0])
532           << "error creating EE: " << ErrorMsg << "\n";
533     else
534       WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
535     exit(1);
536   }
537 
538   std::unique_ptr<LLIObjectCache> CacheManager;
539   if (EnableCacheManager) {
540     CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
541     EE->setObjectCache(CacheManager.get());
542   }
543 
544   // Load any additional modules specified on the command line.
545   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
546     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
547     if (!XMod)
548       reportError(Err, argv[0]);
549     if (EnableCacheManager) {
550       std::string CacheName("file:");
551       CacheName.append(ExtraModules[i]);
552       XMod->setModuleIdentifier(CacheName);
553     }
554     EE->addModule(std::move(XMod));
555   }
556 
557   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
558     Expected<object::OwningBinary<object::ObjectFile>> Obj =
559         object::ObjectFile::createObjectFile(ExtraObjects[i]);
560     if (!Obj) {
561       // TODO: Actually report errors helpfully.
562       consumeError(Obj.takeError());
563       reportError(Err, argv[0]);
564     }
565     object::OwningBinary<object::ObjectFile> &O = Obj.get();
566     EE->addObjectFile(std::move(O));
567   }
568 
569   for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
570     ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
571         MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
572     if (!ArBufOrErr)
573       reportError(Err, argv[0]);
574     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
575 
576     Expected<std::unique_ptr<object::Archive>> ArOrErr =
577         object::Archive::create(ArBuf->getMemBufferRef());
578     if (!ArOrErr) {
579       std::string Buf;
580       raw_string_ostream OS(Buf);
581       logAllUnhandledErrors(ArOrErr.takeError(), OS);
582       OS.flush();
583       errs() << Buf;
584       exit(1);
585     }
586     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
587 
588     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
589 
590     EE->addArchive(std::move(OB));
591   }
592 
593   // If the target is Cygwin/MingW and we are generating remote code, we
594   // need an extra module to help out with linking.
595   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
596     addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
597   }
598 
599   // The following functions have no effect if their respective profiling
600   // support wasn't enabled in the build configuration.
601   EE->RegisterJITEventListener(
602                 JITEventListener::createOProfileJITEventListener());
603   EE->RegisterJITEventListener(
604                 JITEventListener::createIntelJITEventListener());
605   if (!RemoteMCJIT)
606     EE->RegisterJITEventListener(
607                 JITEventListener::createPerfJITEventListener());
608 
609   if (!NoLazyCompilation && RemoteMCJIT) {
610     WithColor::warning(errs(), argv[0])
611         << "remote mcjit does not support lazy compilation\n";
612     NoLazyCompilation = true;
613   }
614   EE->DisableLazyCompilation(NoLazyCompilation);
615 
616   // If the user specifically requested an argv[0] to pass into the program,
617   // do it now.
618   if (!FakeArgv0.empty()) {
619     InputFile = static_cast<std::string>(FakeArgv0);
620   } else {
621     // Otherwise, if there is a .bc suffix on the executable strip it off, it
622     // might confuse the program.
623     if (StringRef(InputFile).endswith(".bc"))
624       InputFile.erase(InputFile.length() - 3);
625   }
626 
627   // Add the module's name to the start of the vector of arguments to main().
628   InputArgv.insert(InputArgv.begin(), InputFile);
629 
630   // Call the main function from M as if its signature were:
631   //   int main (int argc, char **argv, const char **envp)
632   // using the contents of Args to determine argc & argv, and the contents of
633   // EnvVars to determine envp.
634   //
635   Function *EntryFn = Mod->getFunction(EntryFunc);
636   if (!EntryFn) {
637     WithColor::error(errs(), argv[0])
638         << '\'' << EntryFunc << "\' function not found in module.\n";
639     return -1;
640   }
641 
642   // Reset errno to zero on entry to main.
643   errno = 0;
644 
645   int Result = -1;
646 
647   // Sanity check use of remote-jit: LLI currently only supports use of the
648   // remote JIT on Unix platforms.
649   if (RemoteMCJIT) {
650 #ifndef LLVM_ON_UNIX
651     WithColor::warning(errs(), argv[0])
652         << "host does not support external remote targets.\n";
653     WithColor::note() << "defaulting to local execution\n";
654     return -1;
655 #else
656     if (ChildExecPath.empty()) {
657       WithColor::error(errs(), argv[0])
658           << "-remote-mcjit requires -mcjit-remote-process.\n";
659       exit(1);
660     } else if (!sys::fs::can_execute(ChildExecPath)) {
661       WithColor::error(errs(), argv[0])
662           << "unable to find usable child executable: '" << ChildExecPath
663           << "'\n";
664       return -1;
665     }
666 #endif
667   }
668 
669   std::unique_ptr<orc::ExecutorProcessControl> EPC =
670       RemoteMCJIT ? ExitOnErr(launchRemote())
671                   : ExitOnErr(orc::SelfExecutorProcessControl::Create());
672 
673   if (!RemoteMCJIT) {
674     // If the program doesn't explicitly call exit, we will need the Exit
675     // function later on to make an explicit call, so get the function now.
676     FunctionCallee Exit = Mod->getOrInsertFunction(
677         "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context));
678 
679     // Run static constructors.
680     if (!ForceInterpreter) {
681       // Give MCJIT a chance to apply relocations and set page permissions.
682       EE->finalizeObject();
683     }
684     EE->runStaticConstructorsDestructors(false);
685 
686     // Trigger compilation separately so code regions that need to be
687     // invalidated will be known.
688     (void)EE->getPointerToFunction(EntryFn);
689     // Clear instruction cache before code will be executed.
690     if (RTDyldMM)
691       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
692 
693     // Run main.
694     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
695 
696     // Run static destructors.
697     EE->runStaticConstructorsDestructors(true);
698 
699     // If the program didn't call exit explicitly, we should call it now.
700     // This ensures that any atexit handlers get called correctly.
701     if (Function *ExitF =
702             dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) {
703       if (ExitF->getFunctionType() == Exit.getFunctionType()) {
704         std::vector<GenericValue> Args;
705         GenericValue ResultGV;
706         ResultGV.IntVal = APInt(32, Result);
707         Args.push_back(ResultGV);
708         EE->runFunction(ExitF, Args);
709         WithColor::error(errs(), argv[0])
710             << "exit(" << Result << ") returned!\n";
711         abort();
712       }
713     }
714     WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n";
715     abort();
716   } else {
717     // else == "if (RemoteMCJIT)"
718 
719     // Remote target MCJIT doesn't (yet) support static constructors. No reason
720     // it couldn't. This is a limitation of the LLI implementation, not the
721     // MCJIT itself. FIXME.
722 
723     // Create a remote memory manager.
724     auto RemoteMM = ExitOnErr(
725         orc::EPCGenericRTDyldMemoryManager::CreateWithDefaultBootstrapSymbols(
726             *EPC));
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         ExitOnErr(RemoteResolver::Create(*EPC)));
735     // Grab the target address of the JIT'd main function on the remote and call
736     // it.
737     // FIXME: argv and envp handling.
738     auto Entry =
739         orc::ExecutorAddr(EE->getFunctionAddress(EntryFn->getName().str()));
740     EE->finalizeObject();
741     LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
742                       << format("%llx", Entry.getValue()) << "\n");
743     Result = ExitOnErr(EPC->runAsMain(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(EPC->disconnect());
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(
1065         EPC->runAsMain(orc::ExecutorAddr(MainSym.getAddress()), InputArgv));
1066   } else {
1067     // Manual in-process execution with RuntimeDyld.
1068     using MainFnTy = int(int, char *[]);
1069     auto MainFn = jitTargetAddressToFunction<MainFnTy *>(MainSym.getAddress());
1070     Result = orc::runAsMain(MainFn, InputArgv, StringRef(InputFile));
1071   }
1072 
1073   // Wait for -entry-point threads.
1074   for (auto &AltEntryThread : AltEntryThreads)
1075     AltEntryThread.join();
1076 
1077   // Run destructors.
1078   ExitOnErr(J->deinitialize(J->getMainJITDylib()));
1079 
1080   return Result;
1081 }
1082 
1083 void disallowOrcOptions() {
1084   // Make sure nobody used an orc-lazy specific option accidentally.
1085 
1086   if (LazyJITCompileThreads != 0) {
1087     errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
1088     exit(1);
1089   }
1090 
1091   if (!ThreadEntryPoints.empty()) {
1092     errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
1093     exit(1);
1094   }
1095 
1096   if (PerModuleLazy) {
1097     errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
1098     exit(1);
1099   }
1100 }
1101 
1102 Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote() {
1103 #ifndef LLVM_ON_UNIX
1104   llvm_unreachable("launchRemote not supported on non-Unix platforms");
1105 #else
1106   int PipeFD[2][2];
1107   pid_t ChildPID;
1108 
1109   // Create two pipes.
1110   if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
1111     perror("Error creating pipe: ");
1112 
1113   ChildPID = fork();
1114 
1115   if (ChildPID == 0) {
1116     // In the child...
1117 
1118     // Close the parent ends of the pipes
1119     close(PipeFD[0][1]);
1120     close(PipeFD[1][0]);
1121 
1122 
1123     // Execute the child process.
1124     std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
1125     {
1126       ChildPath.reset(new char[ChildExecPath.size() + 1]);
1127       std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
1128       ChildPath[ChildExecPath.size()] = '\0';
1129       std::string ChildInStr = utostr(PipeFD[0][0]);
1130       ChildIn.reset(new char[ChildInStr.size() + 1]);
1131       std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
1132       ChildIn[ChildInStr.size()] = '\0';
1133       std::string ChildOutStr = utostr(PipeFD[1][1]);
1134       ChildOut.reset(new char[ChildOutStr.size() + 1]);
1135       std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
1136       ChildOut[ChildOutStr.size()] = '\0';
1137     }
1138 
1139     char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
1140     int rc = execv(ChildExecPath.c_str(), args);
1141     if (rc != 0)
1142       perror("Error executing child process: ");
1143     llvm_unreachable("Error executing child process");
1144   }
1145   // else we're the parent...
1146 
1147   // Close the child ends of the pipes
1148   close(PipeFD[0][0]);
1149   close(PipeFD[1][1]);
1150 
1151   // Return a SimpleRemoteEPC instance connected to our end of the pipes.
1152   return orc::SimpleRemoteEPC::Create<orc::FDSimpleRemoteEPCTransport>(
1153       PipeFD[1][0], PipeFD[0][1]);
1154 #endif
1155 }
1156