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