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