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