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