Path: blob/main/contrib/llvm-project/llvm/tools/lli/lli.cpp
35259 views
//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This utility provides a simple wrapper around the LLVM Execution Engines,9// which allow the direct execution of LLVM programs through a Just-In-Time10// compiler, or through an interpreter if no JIT is available for this platform.11//12//===----------------------------------------------------------------------===//1314#include "ForwardingMemoryManager.h"15#include "llvm/ADT/StringExtras.h"16#include "llvm/Bitcode/BitcodeReader.h"17#include "llvm/CodeGen/CommandFlags.h"18#include "llvm/CodeGen/LinkAllCodegenComponents.h"19#include "llvm/Config/llvm-config.h"20#include "llvm/ExecutionEngine/GenericValue.h"21#include "llvm/ExecutionEngine/Interpreter.h"22#include "llvm/ExecutionEngine/JITEventListener.h"23#include "llvm/ExecutionEngine/JITSymbol.h"24#include "llvm/ExecutionEngine/MCJIT.h"25#include "llvm/ExecutionEngine/ObjectCache.h"26#include "llvm/ExecutionEngine/Orc/DebugUtils.h"27#include "llvm/ExecutionEngine/Orc/Debugging/DebuggerSupport.h"28#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"29#include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"30#include "llvm/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.h"31#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"32#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"33#include "llvm/ExecutionEngine/Orc/LLJIT.h"34#include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.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/ToolOutputFile.h"65#include "llvm/Support/WithColor.h"66#include "llvm/Support/raw_ostream.h"67#include "llvm/TargetParser/Triple.h"68#include "llvm/Transforms/Instrumentation.h"69#include <cerrno>70#include <optional>7172#if !defined(_MSC_VER) && !defined(__MINGW32__)73#include <unistd.h>74#else75#include <io.h>76#endif7778#ifdef __CYGWIN__79#include <cygwin/version.h>80#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<100781#define DO_NOTHING_ATEXIT 182#endif83#endif8485using namespace llvm;8687static codegen::RegisterCodeGenFlags CGF;8889#define DEBUG_TYPE "lli"9091namespace {9293enum class JITKind { MCJIT, Orc, OrcLazy };94enum class JITLinkerKind { Default, RuntimeDyld, JITLink };9596cl::opt<std::string>97InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));9899cl::list<std::string>100InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));101102cl::opt<bool> ForceInterpreter("force-interpreter",103cl::desc("Force interpretation: disable JIT"),104cl::init(false));105106cl::opt<JITKind> UseJITKind(107"jit-kind", cl::desc("Choose underlying JIT kind."),108cl::init(JITKind::Orc),109cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),110clEnumValN(JITKind::Orc, "orc", "Orc JIT"),111clEnumValN(JITKind::OrcLazy, "orc-lazy",112"Orc-based lazy JIT.")));113114cl::opt<JITLinkerKind>115JITLinker("jit-linker", cl::desc("Choose the dynamic linker/loader."),116cl::init(JITLinkerKind::Default),117cl::values(clEnumValN(JITLinkerKind::Default, "default",118"Default for platform and JIT-kind"),119clEnumValN(JITLinkerKind::RuntimeDyld, "rtdyld",120"RuntimeDyld"),121clEnumValN(JITLinkerKind::JITLink, "jitlink",122"Orc-specific linker")));123cl::opt<std::string> OrcRuntime("orc-runtime",124cl::desc("Use ORC runtime from given path"),125cl::init(""));126127cl::opt<unsigned>128LazyJITCompileThreads("compile-threads",129cl::desc("Choose the number of compile threads "130"(jit-kind=orc-lazy only)"),131cl::init(0));132133cl::list<std::string>134ThreadEntryPoints("thread-entry",135cl::desc("calls the given entry-point on a new thread "136"(jit-kind=orc-lazy only)"));137138cl::opt<bool> PerModuleLazy(139"per-module-lazy",140cl::desc("Performs lazy compilation on whole module boundaries "141"rather than individual functions"),142cl::init(false));143144cl::list<std::string>145JITDylibs("jd",146cl::desc("Specifies the JITDylib to be used for any subsequent "147"-extra-module arguments."));148149cl::list<std::string>150Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"));151152// The MCJIT supports building for a target address space separate from153// the JIT compilation process. Use a forked process and a copying154// memory manager with IPC to execute using this functionality.155cl::opt<bool> RemoteMCJIT("remote-mcjit",156cl::desc("Execute MCJIT'ed code in a separate process."),157cl::init(false));158159// Manually specify the child process for remote execution. This overrides160// the simulated remote execution that allocates address space for child161// execution. The child process will be executed and will communicate with162// lli via stdin/stdout pipes.163cl::opt<std::string>164ChildExecPath("mcjit-remote-process",165cl::desc("Specify the filename of the process to launch "166"for remote MCJIT execution. If none is specified,"167"\n\tremote execution will be simulated in-process."),168cl::value_desc("filename"), cl::init(""));169170// Determine optimization level.171cl::opt<char> OptLevel("O",172cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "173"(default = '-O2')"),174cl::Prefix, cl::init('2'));175176cl::opt<std::string>177TargetTriple("mtriple", cl::desc("Override target triple for module"));178179cl::opt<std::string>180EntryFunc("entry-function",181cl::desc("Specify the entry function (default = 'main') "182"of the executable"),183cl::value_desc("function"),184cl::init("main"));185186cl::list<std::string>187ExtraModules("extra-module",188cl::desc("Extra modules to be loaded"),189cl::value_desc("input bitcode"));190191cl::list<std::string>192ExtraObjects("extra-object",193cl::desc("Extra object files to be loaded"),194cl::value_desc("input object"));195196cl::list<std::string>197ExtraArchives("extra-archive",198cl::desc("Extra archive files to be loaded"),199cl::value_desc("input archive"));200201cl::opt<bool>202EnableCacheManager("enable-cache-manager",203cl::desc("Use cache manager to save/load modules"),204cl::init(false));205206cl::opt<std::string>207ObjectCacheDir("object-cache-dir",208cl::desc("Directory to store cached object files "209"(must be user writable)"),210cl::init(""));211212cl::opt<std::string>213FakeArgv0("fake-argv0",214cl::desc("Override the 'argv[0]' value passed into the executing"215" program"), cl::value_desc("executable"));216217cl::opt<bool>218DisableCoreFiles("disable-core-files", cl::Hidden,219cl::desc("Disable emission of core files if possible"));220221cl::opt<bool>222NoLazyCompilation("disable-lazy-compilation",223cl::desc("Disable JIT lazy compilation"),224cl::init(false));225226cl::opt<bool>227GenerateSoftFloatCalls("soft-float",228cl::desc("Generate software floating point library calls"),229cl::init(false));230231cl::opt<bool> NoProcessSymbols(232"no-process-syms",233cl::desc("Do not resolve lli process symbols in JIT'd code"),234cl::init(false));235236enum class LLJITPlatform { Inactive, Auto, ExecutorNative, GenericIR };237238cl::opt<LLJITPlatform> Platform(239"lljit-platform", cl::desc("Platform to use with LLJIT"),240cl::init(LLJITPlatform::Auto),241cl::values(clEnumValN(LLJITPlatform::Auto, "Auto",242"Like 'ExecutorNative' if ORC runtime "243"provided, otherwise like 'GenericIR'"),244clEnumValN(LLJITPlatform::ExecutorNative, "ExecutorNative",245"Use the native platform for the executor."246"Requires -orc-runtime"),247clEnumValN(LLJITPlatform::GenericIR, "GenericIR",248"Use LLJITGenericIRPlatform"),249clEnumValN(LLJITPlatform::Inactive, "Inactive",250"Disable platform support explicitly")),251cl::Hidden);252253enum class DumpKind {254NoDump,255DumpFuncsToStdOut,256DumpModsToStdOut,257DumpModsToDisk,258DumpDebugDescriptor,259DumpDebugObjects,260};261262cl::opt<DumpKind> OrcDumpKind(263"orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),264cl::init(DumpKind::NoDump),265cl::values(266clEnumValN(DumpKind::NoDump, "no-dump", "Don't dump anything."),267clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",268"Dump function names to stdout."),269clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",270"Dump modules to stdout."),271clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",272"Dump modules to the current "273"working directory. (WARNING: "274"will overwrite existing files)."),275clEnumValN(DumpKind::DumpDebugDescriptor, "jit-debug-descriptor",276"Dump __jit_debug_descriptor contents to stdout"),277clEnumValN(DumpKind::DumpDebugObjects, "jit-debug-objects",278"Dump __jit_debug_descriptor in-memory debug "279"objects as tool output")),280cl::Hidden);281282ExitOnError ExitOnErr;283}284285LLVM_ATTRIBUTE_USED void linkComponents() {286errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper287<< (void *)&llvm_orc_deregisterEHFrameSectionWrapper288<< (void *)&llvm_orc_registerJITLoaderGDBWrapper289<< (void *)&llvm_orc_registerJITLoaderGDBAllocAction;290}291292//===----------------------------------------------------------------------===//293// Object cache294//295// This object cache implementation writes cached objects to disk to the296// directory specified by CacheDir, using a filename provided in the module297// descriptor. The cache tries to load a saved object using that path if the298// file exists. CacheDir defaults to "", in which case objects are cached299// alongside their originating bitcodes.300//301class LLIObjectCache : public ObjectCache {302public:303LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {304// Add trailing '/' to cache dir if necessary.305if (!this->CacheDir.empty() &&306this->CacheDir[this->CacheDir.size() - 1] != '/')307this->CacheDir += '/';308}309~LLIObjectCache() override {}310311void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {312const std::string &ModuleID = M->getModuleIdentifier();313std::string CacheName;314if (!getCacheFilename(ModuleID, CacheName))315return;316if (!CacheDir.empty()) { // Create user-defined cache dir.317SmallString<128> dir(sys::path::parent_path(CacheName));318sys::fs::create_directories(Twine(dir));319}320321std::error_code EC;322raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);323outfile.write(Obj.getBufferStart(), Obj.getBufferSize());324outfile.close();325}326327std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {328const std::string &ModuleID = M->getModuleIdentifier();329std::string CacheName;330if (!getCacheFilename(ModuleID, CacheName))331return nullptr;332// Load the object from the cache filename333ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =334MemoryBuffer::getFile(CacheName, /*IsText=*/false,335/*RequiresNullTerminator=*/false);336// If the file isn't there, that's OK.337if (!IRObjectBuffer)338return nullptr;339// MCJIT will want to write into this buffer, and we don't want that340// because the file has probably just been mmapped. Instead we make341// a copy. The filed-based buffer will be released when it goes342// out of scope.343return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());344}345346private:347std::string CacheDir;348349bool getCacheFilename(StringRef ModID, std::string &CacheName) {350if (!ModID.consume_front("file:"))351return false;352353std::string CacheSubdir = std::string(ModID);354// Transform "X:\foo" => "/X\foo" for convenience on Windows.355if (is_style_windows(llvm::sys::path::Style::native) &&356isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {357CacheSubdir[1] = CacheSubdir[0];358CacheSubdir[0] = '/';359}360361CacheName = CacheDir + CacheSubdir;362size_t pos = CacheName.rfind('.');363CacheName.replace(pos, CacheName.length() - pos, ".o");364return true;365}366};367368// On Mingw and Cygwin, an external symbol named '__main' is called from the369// generated 'main' function to allow static initialization. To avoid linking370// problems with remote targets (because lli's remote target support does not371// currently handle external linking) we add a secondary module which defines372// an empty '__main' function.373static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,374StringRef TargetTripleStr) {375IRBuilder<> Builder(Context);376Triple TargetTriple(TargetTripleStr);377378// Create a new module.379std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);380M->setTargetTriple(TargetTripleStr);381382// Create an empty function named "__main".383Type *ReturnTy;384if (TargetTriple.isArch64Bit())385ReturnTy = Type::getInt64Ty(Context);386else387ReturnTy = Type::getInt32Ty(Context);388Function *Result =389Function::Create(FunctionType::get(ReturnTy, {}, false),390GlobalValue::ExternalLinkage, "__main", M.get());391392BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);393Builder.SetInsertPoint(BB);394Value *ReturnVal = ConstantInt::get(ReturnTy, 0);395Builder.CreateRet(ReturnVal);396397// Add this new module to the ExecutionEngine.398EE.addModule(std::move(M));399}400401CodeGenOptLevel getOptLevel() {402if (auto Level = CodeGenOpt::parseLevel(OptLevel))403return *Level;404WithColor::error(errs(), "lli") << "invalid optimization level.\n";405exit(1);406}407408[[noreturn]] static void reportError(SMDiagnostic Err, const char *ProgName) {409Err.print(ProgName, errs());410exit(1);411}412413Error loadDylibs();414int runOrcJIT(const char *ProgName);415void disallowOrcOptions();416Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote();417418//===----------------------------------------------------------------------===//419// main Driver function420//421int main(int argc, char **argv, char * const *envp) {422InitLLVM X(argc, argv);423424if (argc > 1)425ExitOnErr.setBanner(std::string(argv[0]) + ": ");426427// If we have a native target, initialize it to ensure it is linked in and428// usable by the JIT.429InitializeNativeTarget();430InitializeNativeTargetAsmPrinter();431InitializeNativeTargetAsmParser();432433cl::ParseCommandLineOptions(argc, argv,434"llvm interpreter & dynamic compiler\n");435436// If the user doesn't want core files, disable them.437if (DisableCoreFiles)438sys::Process::PreventCoreFiles();439440ExitOnErr(loadDylibs());441442if (EntryFunc.empty()) {443WithColor::error(errs(), argv[0])444<< "--entry-function name cannot be empty\n";445exit(1);446}447448if (UseJITKind == JITKind::MCJIT || ForceInterpreter)449disallowOrcOptions();450else451return runOrcJIT(argv[0]);452453// Old lli implementation based on ExecutionEngine and MCJIT.454LLVMContext Context;455456// Load the bitcode...457SMDiagnostic Err;458std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);459Module *Mod = Owner.get();460if (!Mod)461reportError(Err, argv[0]);462463if (EnableCacheManager) {464std::string CacheName("file:");465CacheName.append(InputFile);466Mod->setModuleIdentifier(CacheName);467}468469// If not jitting lazily, load the whole bitcode file eagerly too.470if (NoLazyCompilation) {471// Use *argv instead of argv[0] to work around a wrong GCC warning.472ExitOnError ExitOnErr(std::string(*argv) +473": bitcode didn't read correctly: ");474ExitOnErr(Mod->materializeAll());475}476477std::string ErrorMsg;478EngineBuilder builder(std::move(Owner));479builder.setMArch(codegen::getMArch());480builder.setMCPU(codegen::getCPUStr());481builder.setMAttrs(codegen::getFeatureList());482if (auto RM = codegen::getExplicitRelocModel())483builder.setRelocationModel(*RM);484if (auto CM = codegen::getExplicitCodeModel())485builder.setCodeModel(*CM);486builder.setErrorStr(&ErrorMsg);487builder.setEngineKind(ForceInterpreter488? EngineKind::Interpreter489: EngineKind::JIT);490491// If we are supposed to override the target triple, do so now.492if (!TargetTriple.empty())493Mod->setTargetTriple(Triple::normalize(TargetTriple));494495// Enable MCJIT if desired.496RTDyldMemoryManager *RTDyldMM = nullptr;497if (!ForceInterpreter) {498if (RemoteMCJIT)499RTDyldMM = new ForwardingMemoryManager();500else501RTDyldMM = new SectionMemoryManager();502503// Deliberately construct a temp std::unique_ptr to pass in. Do not null out504// RTDyldMM: We still use it below, even though we don't own it.505builder.setMCJITMemoryManager(506std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));507} else if (RemoteMCJIT) {508WithColor::error(errs(), argv[0])509<< "remote process execution does not work with the interpreter.\n";510exit(1);511}512513builder.setOptLevel(getOptLevel());514515TargetOptions Options =516codegen::InitTargetOptionsFromCodeGenFlags(Triple(TargetTriple));517if (codegen::getFloatABIForCalls() != FloatABI::Default)518Options.FloatABIType = codegen::getFloatABIForCalls();519520builder.setTargetOptions(Options);521522std::unique_ptr<ExecutionEngine> EE(builder.create());523if (!EE) {524if (!ErrorMsg.empty())525WithColor::error(errs(), argv[0])526<< "error creating EE: " << ErrorMsg << "\n";527else528WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";529exit(1);530}531532std::unique_ptr<LLIObjectCache> CacheManager;533if (EnableCacheManager) {534CacheManager.reset(new LLIObjectCache(ObjectCacheDir));535EE->setObjectCache(CacheManager.get());536}537538// Load any additional modules specified on the command line.539for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {540std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);541if (!XMod)542reportError(Err, argv[0]);543if (EnableCacheManager) {544std::string CacheName("file:");545CacheName.append(ExtraModules[i]);546XMod->setModuleIdentifier(CacheName);547}548EE->addModule(std::move(XMod));549}550551for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {552Expected<object::OwningBinary<object::ObjectFile>> Obj =553object::ObjectFile::createObjectFile(ExtraObjects[i]);554if (!Obj) {555// TODO: Actually report errors helpfully.556consumeError(Obj.takeError());557reportError(Err, argv[0]);558}559object::OwningBinary<object::ObjectFile> &O = Obj.get();560EE->addObjectFile(std::move(O));561}562563for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {564ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =565MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);566if (!ArBufOrErr)567reportError(Err, argv[0]);568std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();569570Expected<std::unique_ptr<object::Archive>> ArOrErr =571object::Archive::create(ArBuf->getMemBufferRef());572if (!ArOrErr) {573std::string Buf;574raw_string_ostream OS(Buf);575logAllUnhandledErrors(ArOrErr.takeError(), OS);576OS.flush();577errs() << Buf;578exit(1);579}580std::unique_ptr<object::Archive> &Ar = ArOrErr.get();581582object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));583584EE->addArchive(std::move(OB));585}586587// If the target is Cygwin/MingW and we are generating remote code, we588// need an extra module to help out with linking.589if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {590addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());591}592593// The following functions have no effect if their respective profiling594// support wasn't enabled in the build configuration.595EE->RegisterJITEventListener(596JITEventListener::createOProfileJITEventListener());597EE->RegisterJITEventListener(598JITEventListener::createIntelJITEventListener());599if (!RemoteMCJIT)600EE->RegisterJITEventListener(601JITEventListener::createPerfJITEventListener());602603if (!NoLazyCompilation && RemoteMCJIT) {604WithColor::warning(errs(), argv[0])605<< "remote mcjit does not support lazy compilation\n";606NoLazyCompilation = true;607}608EE->DisableLazyCompilation(NoLazyCompilation);609610// If the user specifically requested an argv[0] to pass into the program,611// do it now.612if (!FakeArgv0.empty()) {613InputFile = static_cast<std::string>(FakeArgv0);614} else {615// Otherwise, if there is a .bc suffix on the executable strip it off, it616// might confuse the program.617if (StringRef(InputFile).ends_with(".bc"))618InputFile.erase(InputFile.length() - 3);619}620621// Add the module's name to the start of the vector of arguments to main().622InputArgv.insert(InputArgv.begin(), InputFile);623624// Call the main function from M as if its signature were:625// int main (int argc, char **argv, const char **envp)626// using the contents of Args to determine argc & argv, and the contents of627// EnvVars to determine envp.628//629Function *EntryFn = Mod->getFunction(EntryFunc);630if (!EntryFn) {631WithColor::error(errs(), argv[0])632<< '\'' << EntryFunc << "\' function not found in module.\n";633return -1;634}635636// Reset errno to zero on entry to main.637errno = 0;638639int Result = -1;640641// Sanity check use of remote-jit: LLI currently only supports use of the642// remote JIT on Unix platforms.643if (RemoteMCJIT) {644#ifndef LLVM_ON_UNIX645WithColor::warning(errs(), argv[0])646<< "host does not support external remote targets.\n";647WithColor::note() << "defaulting to local execution\n";648return -1;649#else650if (ChildExecPath.empty()) {651WithColor::error(errs(), argv[0])652<< "-remote-mcjit requires -mcjit-remote-process.\n";653exit(1);654} else if (!sys::fs::can_execute(ChildExecPath)) {655WithColor::error(errs(), argv[0])656<< "unable to find usable child executable: '" << ChildExecPath657<< "'\n";658return -1;659}660#endif661}662663if (!RemoteMCJIT) {664// If the program doesn't explicitly call exit, we will need the Exit665// function later on to make an explicit call, so get the function now.666FunctionCallee Exit = Mod->getOrInsertFunction(667"exit", Type::getVoidTy(Context), Type::getInt32Ty(Context));668669// Run static constructors.670if (!ForceInterpreter) {671// Give MCJIT a chance to apply relocations and set page permissions.672EE->finalizeObject();673}674EE->runStaticConstructorsDestructors(false);675676// Trigger compilation separately so code regions that need to be677// invalidated will be known.678(void)EE->getPointerToFunction(EntryFn);679// Clear instruction cache before code will be executed.680if (RTDyldMM)681static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();682683// Run main.684Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);685686// Run static destructors.687EE->runStaticConstructorsDestructors(true);688689// If the program didn't call exit explicitly, we should call it now.690// This ensures that any atexit handlers get called correctly.691if (Function *ExitF =692dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) {693if (ExitF->getFunctionType() == Exit.getFunctionType()) {694std::vector<GenericValue> Args;695GenericValue ResultGV;696ResultGV.IntVal = APInt(32, Result);697Args.push_back(ResultGV);698EE->runFunction(ExitF, Args);699WithColor::error(errs(), argv[0])700<< "exit(" << Result << ") returned!\n";701abort();702}703}704WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n";705abort();706} else {707// else == "if (RemoteMCJIT)"708std::unique_ptr<orc::ExecutorProcessControl> EPC = ExitOnErr(launchRemote());709710// Remote target MCJIT doesn't (yet) support static constructors. No reason711// it couldn't. This is a limitation of the LLI implementation, not the712// MCJIT itself. FIXME.713714// Create a remote memory manager.715auto RemoteMM = ExitOnErr(716orc::EPCGenericRTDyldMemoryManager::CreateWithDefaultBootstrapSymbols(717*EPC));718719// Forward MCJIT's memory manager calls to the remote memory manager.720static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(721std::move(RemoteMM));722723// Forward MCJIT's symbol resolution calls to the remote.724static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(725ExitOnErr(RemoteResolver::Create(*EPC)));726// Grab the target address of the JIT'd main function on the remote and call727// it.728// FIXME: argv and envp handling.729auto Entry =730orc::ExecutorAddr(EE->getFunctionAddress(EntryFn->getName().str()));731EE->finalizeObject();732LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"733<< format("%llx", Entry.getValue()) << "\n");734Result = ExitOnErr(EPC->runAsMain(Entry, {}));735736// Like static constructors, the remote target MCJIT support doesn't handle737// this yet. It could. FIXME.738739// Delete the EE - we need to tear it down *before* we terminate the session740// with the remote, otherwise it'll crash when it tries to release resources741// on a remote that has already been disconnected.742EE.reset();743744// Signal the remote target that we're done JITing.745ExitOnErr(EPC->disconnect());746}747748return Result;749}750751// JITLink debug support plugins put information about JITed code in this GDB752// JIT Interface global from OrcTargetProcess.753extern "C" struct jit_descriptor __jit_debug_descriptor;754755static struct jit_code_entry *756findNextDebugDescriptorEntry(struct jit_code_entry *Latest) {757if (Latest == nullptr)758return __jit_debug_descriptor.first_entry;759if (Latest->next_entry)760return Latest->next_entry;761return nullptr;762}763764static ToolOutputFile &claimToolOutput() {765static std::unique_ptr<ToolOutputFile> ToolOutput = nullptr;766if (ToolOutput) {767WithColor::error(errs(), "lli")768<< "Can not claim stdout for tool output twice\n";769exit(1);770}771std::error_code EC;772ToolOutput = std::make_unique<ToolOutputFile>("-", EC, sys::fs::OF_None);773if (EC) {774WithColor::error(errs(), "lli")775<< "Failed to create tool output file: " << EC.message() << "\n";776exit(1);777}778return *ToolOutput;779}780781static std::function<void(Module &)> createIRDebugDumper() {782switch (OrcDumpKind) {783case DumpKind::NoDump:784case DumpKind::DumpDebugDescriptor:785case DumpKind::DumpDebugObjects:786return [](Module &M) {};787788case DumpKind::DumpFuncsToStdOut:789return [](Module &M) {790printf("[ ");791792for (const auto &F : M) {793if (F.isDeclaration())794continue;795796if (F.hasName()) {797std::string Name(std::string(F.getName()));798printf("%s ", Name.c_str());799} else800printf("<anon> ");801}802803printf("]\n");804};805806case DumpKind::DumpModsToStdOut:807return [](Module &M) {808outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";809};810811case DumpKind::DumpModsToDisk:812return [](Module &M) {813std::error_code EC;814raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC,815sys::fs::OF_TextWithCRLF);816if (EC) {817errs() << "Couldn't open " << M.getModuleIdentifier()818<< " for dumping.\nError:" << EC.message() << "\n";819exit(1);820}821Out << M;822};823}824llvm_unreachable("Unknown DumpKind");825}826827static std::function<void(MemoryBuffer &)> createObjDebugDumper() {828switch (OrcDumpKind) {829case DumpKind::NoDump:830case DumpKind::DumpFuncsToStdOut:831case DumpKind::DumpModsToStdOut:832case DumpKind::DumpModsToDisk:833return [](MemoryBuffer &) {};834835case DumpKind::DumpDebugDescriptor: {836// Dump the empty descriptor at startup once837fprintf(stderr, "jit_debug_descriptor 0x%016" PRIx64 "\n",838pointerToJITTargetAddress(__jit_debug_descriptor.first_entry));839return [](MemoryBuffer &) {840// Dump new entries as they appear841static struct jit_code_entry *Latest = nullptr;842while (auto *NewEntry = findNextDebugDescriptorEntry(Latest)) {843fprintf(stderr, "jit_debug_descriptor 0x%016" PRIx64 "\n",844pointerToJITTargetAddress(NewEntry));845Latest = NewEntry;846}847};848}849850case DumpKind::DumpDebugObjects: {851return [](MemoryBuffer &Obj) {852static struct jit_code_entry *Latest = nullptr;853static ToolOutputFile &ToolOutput = claimToolOutput();854while (auto *NewEntry = findNextDebugDescriptorEntry(Latest)) {855ToolOutput.os().write(NewEntry->symfile_addr, NewEntry->symfile_size);856Latest = NewEntry;857}858};859}860}861llvm_unreachable("Unknown DumpKind");862}863864Error loadDylibs() {865for (const auto &Dylib : Dylibs) {866std::string ErrMsg;867if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))868return make_error<StringError>(ErrMsg, inconvertibleErrorCode());869}870871return Error::success();872}873874static void exitOnLazyCallThroughFailure() { exit(1); }875876Expected<orc::ThreadSafeModule>877loadModule(StringRef Path, orc::ThreadSafeContext TSCtx) {878SMDiagnostic Err;879auto M = parseIRFile(Path, Err, *TSCtx.getContext());880if (!M) {881std::string ErrMsg;882{883raw_string_ostream ErrMsgStream(ErrMsg);884Err.print("lli", ErrMsgStream);885}886return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());887}888889if (EnableCacheManager)890M->setModuleIdentifier("file:" + M->getModuleIdentifier());891892return orc::ThreadSafeModule(std::move(M), std::move(TSCtx));893}894895int mingw_noop_main(void) {896// Cygwin and MinGW insert calls from the main function to the runtime897// function __main. The __main function is responsible for setting up main's898// environment (e.g. running static constructors), however this is not needed899// when running under lli: the executor process will have run non-JIT ctors,900// and ORC will take care of running JIT'd ctors. To avoid a missing symbol901// error we just implement __main as a no-op.902//903// FIXME: Move this to ORC-RT (and the ORC-RT substitution library once it904// exists). That will allow it to work out-of-process, and for all905// ORC tools (the problem isn't lli specific).906return 0;907}908909// Try to enable debugger support for the given instance.910// This alway returns success, but prints a warning if it's not able to enable911// debugger support.912Error tryEnableDebugSupport(orc::LLJIT &J) {913if (auto Err = enableDebuggerSupport(J)) {914[[maybe_unused]] std::string ErrMsg = toString(std::move(Err));915LLVM_DEBUG(dbgs() << "lli: " << ErrMsg << "\n");916}917return Error::success();918}919920int runOrcJIT(const char *ProgName) {921// Start setting up the JIT environment.922923// Parse the main module.924orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());925auto MainModule = ExitOnErr(loadModule(InputFile, TSCtx));926927// Get TargetTriple and DataLayout from the main module if they're explicitly928// set.929std::optional<Triple> TT;930std::optional<DataLayout> DL;931MainModule.withModuleDo([&](Module &M) {932if (!M.getTargetTriple().empty())933TT = Triple(M.getTargetTriple());934if (!M.getDataLayout().isDefault())935DL = M.getDataLayout();936});937938orc::LLLazyJITBuilder Builder;939940Builder.setJITTargetMachineBuilder(941TT ? orc::JITTargetMachineBuilder(*TT)942: ExitOnErr(orc::JITTargetMachineBuilder::detectHost()));943944TT = Builder.getJITTargetMachineBuilder()->getTargetTriple();945if (DL)946Builder.setDataLayout(DL);947948if (!codegen::getMArch().empty())949Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(950codegen::getMArch());951952Builder.getJITTargetMachineBuilder()953->setCPU(codegen::getCPUStr())954.addFeatures(codegen::getFeatureList())955.setRelocationModel(codegen::getExplicitRelocModel())956.setCodeModel(codegen::getExplicitCodeModel());957958// Link process symbols unless NoProcessSymbols is set.959Builder.setLinkProcessSymbolsByDefault(!NoProcessSymbols);960961// FIXME: Setting a dummy call-through manager in non-lazy mode prevents the962// JIT builder to instantiate a default (which would fail with an error for963// unsupported architectures).964if (UseJITKind != JITKind::OrcLazy) {965auto ES = std::make_unique<orc::ExecutionSession>(966ExitOnErr(orc::SelfExecutorProcessControl::Create()));967Builder.setLazyCallthroughManager(968std::make_unique<orc::LazyCallThroughManager>(*ES, orc::ExecutorAddr(),969nullptr));970Builder.setExecutionSession(std::move(ES));971}972973Builder.setLazyCompileFailureAddr(974orc::ExecutorAddr::fromPtr(exitOnLazyCallThroughFailure));975Builder.setNumCompileThreads(LazyJITCompileThreads);976977// If the object cache is enabled then set a custom compile function978// creator to use the cache.979std::unique_ptr<LLIObjectCache> CacheManager;980if (EnableCacheManager) {981982CacheManager = std::make_unique<LLIObjectCache>(ObjectCacheDir);983984Builder.setCompileFunctionCreator(985[&](orc::JITTargetMachineBuilder JTMB)986-> Expected<std::unique_ptr<orc::IRCompileLayer::IRCompiler>> {987if (LazyJITCompileThreads > 0)988return std::make_unique<orc::ConcurrentIRCompiler>(std::move(JTMB),989CacheManager.get());990991auto TM = JTMB.createTargetMachine();992if (!TM)993return TM.takeError();994995return std::make_unique<orc::TMOwningSimpleCompiler>(std::move(*TM),996CacheManager.get());997});998}9991000// Enable debugging of JIT'd code (only works on JITLink for ELF and MachO).1001Builder.setPrePlatformSetup(tryEnableDebugSupport);10021003// Set up LLJIT platform.1004LLJITPlatform P = Platform;1005if (P == LLJITPlatform::Auto)1006P = OrcRuntime.empty() ? LLJITPlatform::GenericIR1007: LLJITPlatform::ExecutorNative;10081009switch (P) {1010case LLJITPlatform::ExecutorNative: {1011Builder.setPlatformSetUp(orc::ExecutorNativePlatform(OrcRuntime));1012break;1013}1014case LLJITPlatform::GenericIR:1015// Nothing to do: LLJITBuilder will use this by default.1016break;1017case LLJITPlatform::Inactive:1018Builder.setPlatformSetUp(orc::setUpInactivePlatform);1019break;1020default:1021llvm_unreachable("Unrecognized platform value");1022}10231024std::unique_ptr<orc::ExecutorProcessControl> EPC = nullptr;1025if (JITLinker == JITLinkerKind::JITLink) {1026EPC = ExitOnErr(orc::SelfExecutorProcessControl::Create(1027std::make_shared<orc::SymbolStringPool>()));10281029Builder.getJITTargetMachineBuilder()1030->setRelocationModel(Reloc::PIC_)1031.setCodeModel(CodeModel::Small);1032Builder.setObjectLinkingLayerCreator([&P](orc::ExecutionSession &ES,1033const Triple &TT) {1034auto L = std::make_unique<orc::ObjectLinkingLayer>(ES);1035if (P != LLJITPlatform::ExecutorNative)1036L->addPlugin(std::make_unique<orc::EHFrameRegistrationPlugin>(1037ES, ExitOnErr(orc::EPCEHFrameRegistrar::Create(ES))));1038return L;1039});1040}10411042auto J = ExitOnErr(Builder.create());10431044auto *ObjLayer = &J->getObjLinkingLayer();1045if (auto *RTDyldObjLayer = dyn_cast<orc::RTDyldObjectLinkingLayer>(ObjLayer)) {1046RTDyldObjLayer->registerJITEventListener(1047*JITEventListener::createGDBRegistrationListener());1048#if LLVM_USE_OPROFILE1049RTDyldObjLayer->registerJITEventListener(1050*JITEventListener::createOProfileJITEventListener());1051#endif1052#if LLVM_USE_INTEL_JITEVENTS1053RTDyldObjLayer->registerJITEventListener(1054*JITEventListener::createIntelJITEventListener());1055#endif1056#if LLVM_USE_PERF1057RTDyldObjLayer->registerJITEventListener(1058*JITEventListener::createPerfJITEventListener());1059#endif1060}10611062if (PerModuleLazy)1063J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);10641065auto IRDump = createIRDebugDumper();1066J->getIRTransformLayer().setTransform(1067[&](orc::ThreadSafeModule TSM,1068const orc::MaterializationResponsibility &R) {1069TSM.withModuleDo([&](Module &M) {1070if (verifyModule(M, &dbgs())) {1071dbgs() << "Bad module: " << &M << "\n";1072exit(1);1073}1074IRDump(M);1075});1076return TSM;1077});10781079auto ObjDump = createObjDebugDumper();1080J->getObjTransformLayer().setTransform(1081[&](std::unique_ptr<MemoryBuffer> Obj)1082-> Expected<std::unique_ptr<MemoryBuffer>> {1083ObjDump(*Obj);1084return std::move(Obj);1085});10861087// If this is a Mingw or Cygwin executor then we need to alias __main to1088// orc_rt_int_void_return_0.1089if (J->getTargetTriple().isOSCygMing())1090ExitOnErr(J->getProcessSymbolsJITDylib()->define(1091orc::absoluteSymbols({{J->mangleAndIntern("__main"),1092{orc::ExecutorAddr::fromPtr(mingw_noop_main),1093JITSymbolFlags::Exported}}})));10941095// Regular modules are greedy: They materialize as a whole and trigger1096// materialization for all required symbols recursively. Lazy modules go1097// through partitioning and they replace outgoing calls with reexport stubs1098// that resolve on call-through.1099auto AddModule = [&](orc::JITDylib &JD, orc::ThreadSafeModule M) {1100return UseJITKind == JITKind::OrcLazy ? J->addLazyIRModule(JD, std::move(M))1101: J->addIRModule(JD, std::move(M));1102};11031104// Add the main module.1105ExitOnErr(AddModule(J->getMainJITDylib(), std::move(MainModule)));11061107// Create JITDylibs and add any extra modules.1108{1109// Create JITDylibs, keep a map from argument index to dylib. We will use1110// -extra-module argument indexes to determine what dylib to use for each1111// -extra-module.1112std::map<unsigned, orc::JITDylib *> IdxToDylib;1113IdxToDylib[0] = &J->getMainJITDylib();1114for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();1115JDItr != JDEnd; ++JDItr) {1116orc::JITDylib *JD = J->getJITDylibByName(*JDItr);1117if (!JD) {1118JD = &ExitOnErr(J->createJITDylib(*JDItr));1119J->getMainJITDylib().addToLinkOrder(*JD);1120JD->addToLinkOrder(J->getMainJITDylib());1121}1122IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD;1123}11241125for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();1126EMItr != EMEnd; ++EMItr) {1127auto M = ExitOnErr(loadModule(*EMItr, TSCtx));11281129auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());1130assert(EMIdx != 0 && "ExtraModule should have index > 0");1131auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));1132auto &JD = *JDItr->second;1133ExitOnErr(AddModule(JD, std::move(M)));1134}11351136for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();1137EAItr != EAEnd; ++EAItr) {1138auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin());1139assert(EAIdx != 0 && "ExtraArchive should have index > 0");1140auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx));1141auto &JD = *JDItr->second;1142ExitOnErr(J->linkStaticLibraryInto(JD, EAItr->c_str()));1143}1144}11451146// Add the objects.1147for (auto &ObjPath : ExtraObjects) {1148auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));1149ExitOnErr(J->addObjectFile(std::move(Obj)));1150}11511152// Run any static constructors.1153ExitOnErr(J->initialize(J->getMainJITDylib()));11541155// Run any -thread-entry points.1156std::vector<std::thread> AltEntryThreads;1157for (auto &ThreadEntryPoint : ThreadEntryPoints) {1158auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));1159typedef void (*EntryPointPtr)();1160auto EntryPoint = EntryPointSym.toPtr<EntryPointPtr>();1161AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));1162}11631164// Resolve and run the main function.1165auto MainAddr = ExitOnErr(J->lookup(EntryFunc));1166int Result;11671168if (EPC) {1169// ExecutorProcessControl-based execution with JITLink.1170Result = ExitOnErr(EPC->runAsMain(MainAddr, InputArgv));1171} else {1172// Manual in-process execution with RuntimeDyld.1173using MainFnTy = int(int, char *[]);1174auto MainFn = MainAddr.toPtr<MainFnTy *>();1175Result = orc::runAsMain(MainFn, InputArgv, StringRef(InputFile));1176}11771178// Wait for -entry-point threads.1179for (auto &AltEntryThread : AltEntryThreads)1180AltEntryThread.join();11811182// Run destructors.1183ExitOnErr(J->deinitialize(J->getMainJITDylib()));11841185return Result;1186}11871188void disallowOrcOptions() {1189// Make sure nobody used an orc-lazy specific option accidentally.11901191if (LazyJITCompileThreads != 0) {1192errs() << "-compile-threads requires -jit-kind=orc-lazy\n";1193exit(1);1194}11951196if (!ThreadEntryPoints.empty()) {1197errs() << "-thread-entry requires -jit-kind=orc-lazy\n";1198exit(1);1199}12001201if (PerModuleLazy) {1202errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";1203exit(1);1204}1205}12061207Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote() {1208#ifndef LLVM_ON_UNIX1209llvm_unreachable("launchRemote not supported on non-Unix platforms");1210#else1211int PipeFD[2][2];1212pid_t ChildPID;12131214// Create two pipes.1215if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)1216perror("Error creating pipe: ");12171218ChildPID = fork();12191220if (ChildPID == 0) {1221// In the child...12221223// Close the parent ends of the pipes1224close(PipeFD[0][1]);1225close(PipeFD[1][0]);122612271228// Execute the child process.1229std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;1230{1231ChildPath.reset(new char[ChildExecPath.size() + 1]);1232std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);1233ChildPath[ChildExecPath.size()] = '\0';1234std::string ChildInStr = utostr(PipeFD[0][0]);1235ChildIn.reset(new char[ChildInStr.size() + 1]);1236std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);1237ChildIn[ChildInStr.size()] = '\0';1238std::string ChildOutStr = utostr(PipeFD[1][1]);1239ChildOut.reset(new char[ChildOutStr.size() + 1]);1240std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);1241ChildOut[ChildOutStr.size()] = '\0';1242}12431244char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };1245int rc = execv(ChildExecPath.c_str(), args);1246if (rc != 0)1247perror("Error executing child process: ");1248llvm_unreachable("Error executing child process");1249}1250// else we're the parent...12511252// Close the child ends of the pipes1253close(PipeFD[0][0]);1254close(PipeFD[1][1]);12551256// Return a SimpleRemoteEPC instance connected to our end of the pipes.1257return orc::SimpleRemoteEPC::Create<orc::FDSimpleRemoteEPCTransport>(1258std::make_unique<llvm::orc::InPlaceTaskDispatcher>(),1259llvm::orc::SimpleRemoteEPC::Setup(), PipeFD[1][0], PipeFD[0][1]);1260#endif1261}12621263// For MinGW environments, manually export the __chkstk function from the lli1264// executable.1265//1266// Normally, this function is provided by compiler-rt builtins or libgcc.1267// It is named "_alloca" on i386, "___chkstk_ms" on x86_64, and "__chkstk" on1268// arm/aarch64. In MSVC configurations, it's named "__chkstk" in all1269// configurations.1270//1271// When Orc tries to resolve symbols at runtime, this succeeds in MSVC1272// configurations, somewhat by accident/luck; kernelbase.dll does export a1273// symbol named "__chkstk" which gets found by Orc, even if regular applications1274// never link against that function from that DLL (it's linked in statically1275// from a compiler support library).1276//1277// The MinGW specific symbol names aren't available in that DLL though.1278// Therefore, manually export the relevant symbol from lli, to let it be1279// found at runtime during tests.1280//1281// For real JIT uses, the real compiler support libraries should be linked1282// in, somehow; this is a workaround to let tests pass.1283//1284// We need to make sure that this symbol actually is linked in when we1285// try to export it; if no functions allocate a large enough stack area,1286// nothing would reference it. Therefore, manually declare it and add a1287// reference to it. (Note, the declarations of _alloca/___chkstk_ms/__chkstk1288// are somewhat bogus, these functions use a different custom calling1289// convention.)1290//1291// TODO: Move this into libORC at some point, see1292// https://github.com/llvm/llvm-project/issues/56603.1293#ifdef __MINGW32__1294// This is a MinGW version of #pragma comment(linker, "...") that doesn't1295// require compiling with -fms-extensions.1296#if defined(__i386__)1297#undef _alloca1298extern "C" void _alloca(void);1299static __attribute__((used)) void (*const ref_func)(void) = _alloca;1300static __attribute__((section(".drectve"), used)) const char export_chkstk[] =1301"-export:_alloca";1302#elif defined(__x86_64__)1303extern "C" void ___chkstk_ms(void);1304static __attribute__((used)) void (*const ref_func)(void) = ___chkstk_ms;1305static __attribute__((section(".drectve"), used)) const char export_chkstk[] =1306"-export:___chkstk_ms";1307#else1308extern "C" void __chkstk(void);1309static __attribute__((used)) void (*const ref_func)(void) = __chkstk;1310static __attribute__((section(".drectve"), used)) const char export_chkstk[] =1311"-export:__chkstk";1312#endif1313#endif131413151316