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