Files
carbon-lang/toolchain/driver/clang_runner.cpp
T
4845f40dff Switch CARBON_CHECK to a format string API (#4285)
This switches `DCHECK` and `FATAL` as well.

The goal is to reduce the code size impact of these assertions so that
we can keep more of them enabled. Currently, the largest cost I see from
`CHECK` is not the actual check or the cold code itself, but actually
the failure to inline trivial functions due to the presence of the cold
code. This means that our goal isn't to reduce apparent code size in the
final binary but the LLVM IR cost assessed for these routines in the
inliner, which closely correlates with code size but is a bit different.

As discussed in #4283, experimentation shows that a single function call
with a minimal number of arguments is the lowest cost model for these.
This is easily achieved with a format-string API that internally uses
`llvm::formatv`. This PR is essentially the `CHECK` version of #4283.

However, the check macros are substantially harder to make work with
both format strings and streaming because they also take a condition.
Also, unexpectedly, I was very successful at devising a regular
expression based automated rewrite from the streaming to the format
string form with only low 10s of manual fixes. This includes compacting
strings broken up across lines, etc. Given how well that went, I've
prepared this PR which just directly switches to the format string API
and migrate everything to use it.

One nice side-effect is that the format string approach ends up greatly
simplifying the implementation here as well.

This is ... *shockingly* effective. Parsing speeds up by more than 3%
with just this change. And checking speeds up by **8%** with this change
alone:
```
BM_CompileAPIFileDenseDecls<Phase::Parse>/256      86.3µs ± 1%  82.9µs ± 1%  -3.94%  (p=0.000 n=17+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024      431µs ± 1%   415µs ± 1%  -3.76%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096     1.77ms ± 1%  1.71ms ± 1%  -3.18%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384    7.44ms ± 1%  7.17ms ± 2%  -3.56%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    30.7ms ± 1%  29.7ms ± 1%  -3.15%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144    131ms ± 1%   127ms ± 1%  -2.81%  (p=0.000 n=18+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/256       878µs ± 2%   800µs ± 1%  -8.91%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/1024     1.88ms ± 2%  1.72ms ± 1%  -8.56%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/4096     5.78ms ± 2%  5.28ms ± 1%  -8.70%  (p=0.000 n=20+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/16384    21.9ms ± 1%  20.1ms ± 1%  -8.02%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/65536    90.4ms ± 2%  83.1ms ± 1%  -8.04%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/262144    381ms ± 2%   352ms ± 1%  -7.79%  (p=0.000 n=19+19)
```

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2024-09-12 16:42:08 +00:00

151 lines
5.7 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "toolchain/driver/clang_runner.h"
#include <algorithm>
#include <memory>
#include <numeric>
#include <optional>
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "common/command_line.h"
#include "common/vlog.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/TargetParser/Host.h"
namespace Carbon {
ClangRunner::ClangRunner(const InstallPaths* install_paths,
llvm::StringRef target, llvm::raw_ostream* vlog_stream)
: installation_(install_paths),
target_(target),
vlog_stream_(vlog_stream),
diagnostic_ids_(new clang::DiagnosticIDs()) {}
auto ClangRunner::Run(llvm::ArrayRef<llvm::StringRef> args) -> bool {
// TODO: Maybe handle response file expansion similar to the Clang CLI?
// If we have a verbose logging stream, and that stream is the same as
// `llvm::errs`, then add the `-v` flag so that the driver also prints verbose
// information.
bool inject_v_arg = vlog_stream_ == &llvm::errs();
std::array<llvm::StringRef, 1> v_arg_storage;
llvm::ArrayRef<llvm::StringRef> maybe_v_arg;
if (inject_v_arg) {
v_arg_storage[0] = "-v";
maybe_v_arg = v_arg_storage;
}
CARBON_CHECK(!args.empty());
CARBON_VLOG("Running Clang driver with arguments: \n");
// Render the arguments into null-terminated C-strings for use by the Clang
// driver. Command lines can get quite long in build systems so this tries to
// minimize the memory allocation overhead.
// Start with a dummy executable name. We'll manually set the install
// directory below.
std::array<llvm::StringRef, 1> exe_arg = {"clang-runner"};
auto args_range =
llvm::concat<const llvm::StringRef>(exe_arg, maybe_v_arg, args);
int total_size = 0;
for (llvm::StringRef arg : args_range) {
// Accumulate both the string size and a null terminator byte.
total_size += arg.size() + 1;
}
// Allocate one chunk of storage for the actual C-strings and a vector of
// pointers into the storage.
llvm::OwningArrayRef<char> cstr_arg_storage(total_size);
llvm::SmallVector<const char*, 64> cstr_args;
cstr_args.reserve(args.size() + inject_v_arg + 1);
for (ssize_t i = 0; llvm::StringRef arg : args_range) {
cstr_args.push_back(&cstr_arg_storage[i]);
memcpy(&cstr_arg_storage[i], arg.data(), arg.size());
i += arg.size();
cstr_arg_storage[i] = '\0';
++i;
}
for (const char* cstr_arg : llvm::ArrayRef(cstr_args)) {
CARBON_VLOG(" '{0}'\n", cstr_arg);
}
CARBON_VLOG("Preparing Clang driver...\n");
// Create the diagnostic options and parse arguments controlling them out of
// our arguments.
llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnostic_options =
clang::CreateAndPopulateDiagOpts(cstr_args);
// TODO: We don't yet support serializing diagnostics the way the actual
// `clang` command line does. Unclear if we need to or not, but it would need
// a bit more logic here to set up chained consumers.
clang::TextDiagnosticPrinter diagnostic_client(llvm::errs(),
diagnostic_options.get());
clang::DiagnosticsEngine diagnostics(
diagnostic_ids_, diagnostic_options.get(), &diagnostic_client,
/*ShouldOwnClient=*/false);
clang::ProcessWarningOptions(diagnostics, *diagnostic_options);
clang::driver::Driver driver("clang-runner", target_, diagnostics);
// Configure the install directory to find other tools and data files.
//
// We directly override the detected directory as we use a synthetic path
// above. This makes it appear that our binary was in the installed binaries
// directory, and allows finding tools relative to it.
driver.Dir = installation_->llvm_install_bin();
CARBON_VLOG("Setting bin directory to: {0}\n", driver.Dir);
// TODO: Directly run in-process rather than using a subprocess. This is both
// more efficient and makes debugging (much) easier. Needs code like:
// driver.CC1Main = [](llvm::SmallVectorImpl<const char*>& argv) {};
std::unique_ptr<clang::driver::Compilation> compilation(
driver.BuildCompilation(cstr_args));
CARBON_CHECK(compilation, "Should always successfully allocate!");
if (compilation->containsError()) {
// These should have been diagnosed by the driver.
return false;
}
CARBON_VLOG("Running Clang driver...\n");
llvm::SmallVector<std::pair<int, const clang::driver::Command*>>
failing_commands;
int result = driver.ExecuteCompilation(*compilation, failing_commands);
// Finish diagnosing any failures before we verbosely log the source of those
// failures.
diagnostic_client.finish();
CARBON_VLOG("Execution result code: {0}\n", result);
for (const auto& [command_result, failing_command] : failing_commands) {
CARBON_VLOG("Failing command '{0}' with code '{1}' was:\n",
failing_command->getExecutable(), command_result);
if (vlog_stream_) {
failing_command->Print(*vlog_stream_, "\n\n", /*Quote=*/true);
}
}
// Return whether the command was executed successfully.
return result == 0 && failing_commands.empty();
}
} // namespace Carbon