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