Reenable Clang bindings

This commit is contained in:
David Gonzalez Martin 2024-06-09 07:09:17 -06:00
parent b4145308a3
commit 6d43d39597
4 changed files with 67 additions and 29 deletions

View File

@ -93,9 +93,9 @@ pub fn build(b: *std.Build) !void {
const cpp_files = .{ const cpp_files = .{
"src/llvm/llvm.cpp", "src/llvm/llvm.cpp",
"src/llvm/lld.cpp", "src/llvm/lld.cpp",
// "src/llvm/clang_main.cpp", "src/llvm/clang_main.cpp",
// "src/llvm/clang_cc1.cpp", "src/llvm/clang_cc1.cpp",
// "src/llvm/clang_cc1as.cpp", "src/llvm/clang_cc1as.cpp",
// "src/llvm/ar.cpp", // "src/llvm/ar.cpp",
}; };
@ -108,10 +108,11 @@ pub fn build(b: *std.Build) !void {
"-D__STDC_FORMAT_MACROS", "-D__STDC_FORMAT_MACROS",
"-D__STDC_LIMIT_MACROS", "-D__STDC_LIMIT_MACROS",
"-D_GNU_SOURCE", "-D_GNU_SOURCE",
"-fvisibility-inlines-hidden",
"-fno-exceptions", "-fno-exceptions",
"-fno-rtti", "-fno-rtti",
"-Werror=type-limits", "-fno-stack-protector",
"-fvisibility-inlines-hidden",
"-Wno-type-limits",
"-Wno-missing-braces", "-Wno-missing-braces",
"-Wno-comment", "-Wno-comment",
}, },
@ -429,7 +430,7 @@ pub fn build(b: *std.Build) !void {
} }
} else { } else {
compiler.linkSystemLibrary("LLVM"); compiler.linkSystemLibrary("LLVM");
// compiler.linkSystemLibrary("clang-cpp"); compiler.linkSystemLibrary("clang-cpp");
compiler.linkSystemLibrary("lldCommon"); compiler.linkSystemLibrary("lldCommon");
compiler.linkSystemLibrary("lldCOFF"); compiler.linkSystemLibrary("lldCOFF");
compiler.linkSystemLibrary("lldELF"); compiler.linkSystemLibrary("lldELF");

View File

@ -28,6 +28,7 @@
#include "llvm/ADT/Statistic.h" #include "llvm/ADT/Statistic.h"
#include "llvm/Config/llvm-config.h" #include "llvm/Config/llvm-config.h"
#include "llvm/LinkAllPasses.h" #include "llvm/LinkAllPasses.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/TargetRegistry.h" #include "llvm/MC/TargetRegistry.h"
#include "llvm/Option/Arg.h" #include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h" #include "llvm/Option/ArgList.h"
@ -38,12 +39,15 @@
#include "llvm/Support/ManagedStatic.h" #include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h" #include "llvm/Support/Path.h"
#include "llvm/Support/Process.h" #include "llvm/Support/Process.h"
#include "llvm/Support/RISCVISAInfo.h"
#include "llvm/Support/Signals.h" #include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h" #include "llvm/Support/TargetSelect.h"
#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/Timer.h" #include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetMachine.h"
#include "llvm/TargetParser/AArch64TargetParser.h"
#include "llvm/TargetParser/ARMTargetParser.h"
#include <cstdio> #include <cstdio>
#ifdef CLANG_HAVE_RLIMITS #ifdef CLANG_HAVE_RLIMITS
@ -182,6 +186,43 @@ static int PrintSupportedCPUs(std::string TargetStr) {
return 0; return 0;
} }
static int PrintSupportedExtensions(std::string TargetStr) {
std::string Error;
const llvm::Target *TheTarget =
llvm::TargetRegistry::lookupTarget(TargetStr, Error);
if (!TheTarget) {
llvm::errs() << Error;
return 1;
}
llvm::TargetOptions Options;
std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
TheTarget->createTargetMachine(TargetStr, "", "", Options, std::nullopt));
const llvm::Triple &MachineTriple = TheTargetMachine->getTargetTriple();
const llvm::MCSubtargetInfo *MCInfo = TheTargetMachine->getMCSubtargetInfo();
const llvm::ArrayRef<llvm::SubtargetFeatureKV> Features =
MCInfo->getAllProcessorFeatures();
llvm::StringMap<llvm::StringRef> DescMap;
for (const llvm::SubtargetFeatureKV &feature : Features)
DescMap.insert({feature.Key, feature.Desc});
if (MachineTriple.isRISCV())
llvm::riscvExtensionsHelp(DescMap);
else if (MachineTriple.isAArch64())
llvm::AArch64::PrintSupportedExtensions(DescMap);
else if (MachineTriple.isARM())
llvm::ARM::PrintSupportedExtensions(DescMap);
else {
// The option was already checked in Driver::HandleImmediateArgs,
// so we do not expect to get here if we are not a supported architecture.
assert(0 && "Unhandled triple for --print-supported-extensions option.");
return 1;
}
return 0;
}
int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
ensureSufficientStack(); ensureSufficientStack();
@ -221,6 +262,10 @@ int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
if (Clang->getFrontendOpts().PrintSupportedCPUs) if (Clang->getFrontendOpts().PrintSupportedCPUs)
return PrintSupportedCPUs(Clang->getTargetOpts().Triple); return PrintSupportedCPUs(Clang->getTargetOpts().Triple);
// --print-supported-extensions takes priority over the actual compilation.
if (Clang->getFrontendOpts().PrintSupportedExtensions)
return PrintSupportedExtensions(Clang->getTargetOpts().Triple);
// Infer the builtin include path if unspecified. // Infer the builtin include path if unspecified.
if (Clang->getHeaderSearchOpts().UseBuiltinIncludes && if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
Clang->getHeaderSearchOpts().ResourceDir.empty()) Clang->getHeaderSearchOpts().ResourceDir.empty())

View File

@ -204,10 +204,10 @@ bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
// Parse the arguments. // Parse the arguments.
const OptTable &OptTbl = getDriverOptTable(); const OptTable &OptTbl = getDriverOptTable();
const unsigned IncludedFlagsBitmask = options::CC1AsOption; llvm::opt::Visibility VisibilityMask(options::CC1AsOption);
unsigned MissingArgIndex, MissingArgCount; unsigned MissingArgIndex, MissingArgCount;
InputArgList Args = OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount, InputArgList Args =
IncludedFlagsBitmask); OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount, VisibilityMask);
// Check for missing argument error. // Check for missing argument error.
if (MissingArgCount) { if (MissingArgCount) {
@ -220,7 +220,7 @@ bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
for (const Arg *A : Args.filtered(OPT_UNKNOWN)) { for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
auto ArgString = A->getAsString(Args); auto ArgString = A->getAsString(Args);
std::string Nearest; std::string Nearest;
if (OptTbl.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1) if (OptTbl.findNearest(ArgString, Nearest, VisibilityMask) > 1)
Diags.Report(diag::err_drv_unknown_argument) << ArgString; Diags.Report(diag::err_drv_unknown_argument) << ArgString;
else else
Diags.Report(diag::err_drv_unknown_argument_with_suggestion) Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
@ -643,9 +643,10 @@ int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
if (Asm.ShowHelp) { if (Asm.ShowHelp) {
getDriverOptTable().printHelp( getDriverOptTable().printHelp(
llvm::outs(), "clang -cc1as [options] file...", llvm::outs(), "clang -cc1as [options] file...",
"Clang Integrated Assembler", "Clang Integrated Assembler", /*ShowHidden=*/false,
/*Include=*/driver::options::CC1AsOption, /*Exclude=*/0, /*ShowAllAliases=*/false,
/*ShowAllAliases=*/false); llvm::opt::Visibility(driver::options::CC1AsOption));
return 0; return 0;
} }

View File

@ -36,7 +36,6 @@
#include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h" #include "llvm/Support/FileSystem.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/LLVMDriver.h" #include "llvm/Support/LLVMDriver.h"
#include "llvm/Support/Path.h" #include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/PrettyStackTrace.h"
@ -65,7 +64,7 @@ std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
if (llvm::ErrorOr<std::string> P = if (llvm::ErrorOr<std::string> P =
llvm::sys::findProgramByName(ExecutablePath)) llvm::sys::findProgramByName(ExecutablePath))
ExecutablePath = *P; ExecutablePath = *P;
return std::string(ExecutablePath.str()); return std::string(ExecutablePath);
} }
// This just needs to be some symbol in the binary; C++ doesn't // This just needs to be some symbol in the binary; C++ doesn't
@ -79,9 +78,9 @@ static const char *GetStableCStr(std::set<std::string> &SavedStrings,
return SavedStrings.insert(std::string(S)).first->c_str(); return SavedStrings.insert(std::string(S)).first->c_str();
} }
/// ApplyQAOverride - Apply a list of edits to the input argument lists. /// ApplyOneQAOverride - Apply a list of edits to the input argument lists.
/// ///
/// The input string is a space separate list of edits to perform, /// The input string is a space separated list of edits to perform,
/// they are applied in order to the input argument lists. Edits /// they are applied in order to the input argument lists. Edits
/// should be one of the following forms: /// should be one of the following forms:
/// ///
@ -122,7 +121,7 @@ static void ApplyOneQAOverride(raw_ostream &OS,
GetStableCStr(SavedStrings, Edit.substr(1)); GetStableCStr(SavedStrings, Edit.substr(1));
OS << "### Adding argument " << Str << " at end\n"; OS << "### Adding argument " << Str << " at end\n";
Args.push_back(Str); Args.push_back(Str);
} else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") && } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.ends_with("/") &&
Edit.slice(2, Edit.size() - 1).contains('/')) { Edit.slice(2, Edit.size() - 1).contains('/')) {
StringRef MatchPattern = Edit.substr(2).split('/').first; StringRef MatchPattern = Edit.substr(2).split('/').first;
StringRef ReplPattern = Edit.substr(2).split('/').second; StringRef ReplPattern = Edit.substr(2).split('/').second;
@ -177,7 +176,7 @@ static void ApplyOneQAOverride(raw_ostream &OS,
} }
} }
/// ApplyQAOverride - Apply a comma separate list of edits to the /// ApplyQAOverride - Apply a space separated list of edits to the
/// input argument lists. See ApplyOneQAOverride. /// input argument lists. See ApplyOneQAOverride.
static void ApplyQAOverride(SmallVectorImpl<const char*> &Args, static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
const char *OverrideStr, const char *OverrideStr,
@ -371,14 +370,6 @@ static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV,
static int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) { static int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
noteBottomOfStack(); noteBottomOfStack();
// ZIG PATCH: On Windows, InitLLVM calls GetCommandLineW(),
// and overwrites the args. We don't want it to do that,
// and we also don't need the signal handlers it installs
// (we have our own already), so we just use llvm_shutdown_obj
// instead.
// llvm::InitLLVM X(Argc, Argv);
llvm::llvm_shutdown_obj X;
llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
" and include the crash backtrace, preprocessed " " and include the crash backtrace, preprocessed "
"source, and associated run script.\n"); "source, and associated run script.\n");
@ -405,7 +396,7 @@ static int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContex
} }
// Handle -cc1 integrated tools. // Handle -cc1 integrated tools.
if (Args.size() >= 2 && StringRef(Args[1]).startswith("-cc1")) if (Args.size() >= 2 && StringRef(Args[1]).starts_with("-cc1"))
return ExecuteCC1Tool(Args, ToolContext); return ExecuteCC1Tool(Args, ToolContext);
// Handle options that need handling before the real command line parsing in // Handle options that need handling before the real command line parsing in
@ -606,6 +597,6 @@ static int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContex
return Res; return Res;
} }
extern "C" int NativityClangMain(int argc, char **argv) { extern "C" int nat_clang_main(int argc, char ** argv) {
return clang_main(argc, argv, {argv[0], nullptr, false}); return clang_main(argc, argv, {argv[0], nullptr, false});
} }