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