Add more complex function definition generation and an impl-file benchmark (#7998)

Previously, we only had the dense API declarations benchmark. This adds
a benchmark that aims to emulate what a realistic implementation file in
Carbon would look like, based on what `.cpp` files look like in Carbon,
Clang, and LLVM. It's still a little artificial in order to provide
stability, but it should give us coverage of compile time performance of
statements and function definitions at more realistic scales.

In order to generate more interesting and longer function definitions,
this introduces a plan-based approach to guide how each feature of a
definition is produced. Initially, it identifies these as roughly:

- local variables
- updates to variables
- `if`, `else`, `while` blocks
- "guard" statements -- conditions with a return, break, or continue
- read of a parameter

The plan also manages the nesting depth of these constructs.

Because the plan establishes how many of these constructs exist in a
function definition, and at what nesting depth, the emission can
randomize the order and arrangement without changing the size of the
function. This follows the pattern in all our benchmark source
generation of getting byte-identical stability while avoiding
predictable structures. Technically, I think the current approach goes a
bit too far because function definitions I suspect are somewhat
predictable in their structure in practice. But a conservative benchmark
I think is a good starting point. =]

The target distributions for definition sizes, maximum depths, and
statement mixes come from a very rough Claude-powered analysis of 10,697
function definitions in 533 Carbon toolchain, LLVM, and Clang
implementation files. These were analyzed and classified by Claude using
a one-off Python script and libclang. I haven't reviewed any of the
analysis carefully, the resulting distributions look plausible enough as
a starting point. Comparing real code against generated C++ from the
plans, each number per-definition average:

| statements | definitions | max depth   | ifs         | loops       |
|------------|-------------|-------------|-------------|-------------|
| 7-9        | 10.9 / 11%  | 1.25 / 1.23 | 1.74 / 1.86 | 0.23 / 0.15 |
| 14-19      | 7.3 / 7%    | 1.89 / 1.88 | 3.53 / 3.71 | 0.61 / 0.42 |
| 28-39      | 3.3 / 3%    | 2.76 / 2.75 | 7.75 / 8.46 | 1.26 / 1.27 |
| 60+        | 1.5 / 2%    | 4.03 / 3.80 | 25.0 / 27.1 | 3.72 / 4.04 |

To maintain stability, every definition has an accumulator, a statement
reading its parameters, and a `return`, so real definitions of one to
three statements become three.

Note that updates are currently also used instead of calls to other
functions -- a later PR will switch those to calls so that we form more
plausible call graphs. In general, subsequent PRs will refine and expand
the plan to generate increasingly more realistic function definitions.

There are probably lots of improvements that could be made here, both to
generate higher quality definitions and to improve the generation logic
to be more efficient, etc. But already this has allowed _much_ more
extensive benchmarking of Carbon's compile-time performance so it seems
likely a reasonable increment.

Assisted-by: Claude Code and Antigravity with Gemini

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
This commit is contained in:
Chandler Carruthandjosh11b authored and GitHub committed 2026-10-21 23:02:26 +00:00
1 parent 503f09037d
commit 9319bb0369
5 files changed
+1199 -120

No files matched your search

+5 -4
View File
@@ -24,6 +24,7 @@ cc_library(
"//common:set",
"//toolchain/lex:token_kind",
"@abseil-cpp//absl/random",
"@abseil-cpp//absl/random:seed_sequences",
"@llvm-project//llvm:Support",
],
)
@@ -93,10 +94,10 @@ sh_test(
srcs = [":compile_benchmark"],
args = [
"--benchmark_dry_run",
# Dry-run the smallest (256-line) case of every benchmark. Also run just
# the lex benchmark that executes a subprocess to reduce the overhead
# and reduce timeouts. The `$$` is repeated for Bazel escaping of `$`.
"--benchmark_filter=^(BM_CompileApi.*/256|BM_CompileExec.*Phase::Lex.*/256/real_time)$$",
# Dry-run the smallest case of every benchmark. Also run just the lex
# benchmark that executes a subprocess to reduce the overhead and reduce
# timeouts. The `$$` is repeated for Bazel escaping of `$`.
"--benchmark_filter=^(BM_CompileApiFileDenseDecls.*/256|BM_CompileImplFile.*/1024|BM_CompileExec.*Phase::Lex.*/256/real_time)$$",
],
env = cc_env(),
)
+57 -12
View File
@@ -266,6 +266,27 @@ static auto DenseDeclParams() -> SourceGen::DenseDeclParams {
return params;
}
// Parameters for the implementation file pattern: classes whose functions and
// methods are all defined out-of-line, with the default definition sizes. Two
// thirds of the functions are methods, and they average two parameters (`0..2`
// from `max_params = 2`, plus the extra parameter added to out-of-line
// definitions), as in the Carbon toolchain's, LLVM's, and Clang's
// implementation files.
static auto ImplFileParams() -> SourceGen::DenseDeclParams {
SourceGen::DenseDeclParams params;
params.class_params = {.public_function_decls = 2,
.public_function_decl_params = {.max_params = 2},
.public_method_decls = 6,
.public_method_decl_params = {.max_params = 2},
.private_function_decls = 2,
.private_function_decl_params = {.max_params = 2},
.private_method_decls = 2,
.private_method_decl_params = {.max_params = 2},
.private_field_decls = 4};
params.define_decls_out_of_line = true;
return params;
}
// Benchmark on multiple files of the same size but with different source code
// in order to avoid branch prediction perfectly learning a particular file's
// structure and shape, and to get closer to a cache-cold benchmark number which
@@ -384,6 +405,11 @@ static auto BM_CompileApiFileDenseDecls(benchmark::State& state) -> void {
RunApiFileBenchmark<L, P, M>(state, DenseDeclParams());
}
template <Lang L, Phase P, Mode M = Mode::InProcess>
static auto BM_CompileImplFile(benchmark::State& state) -> void {
RunApiFileBenchmark<L, P, M>(state, ImplFileParams());
}
// A thin wrapper for the subprocess benchmarks: they reuse the shared
// implementation above, but register under their own (terser) name rather than
// spelling out `Mode::Subprocess` at each registration.
@@ -392,44 +418,63 @@ static auto BM_CompileExecApiFileDenseDecls(benchmark::State& state) -> void {
BM_CompileApiFileDenseDecls<L, P, Mode::Subprocess>(state);
}
// Applies the shared range configuration used by every compile benchmark:
// Applies the range configuration of the dense declarations benchmarks:
// 256-line test cases through 256k-line test cases.
static auto ConfigureCompileBenchmark(benchmark::Benchmark* b) -> void {
static auto ConfigureDenseDeclBenchmark(benchmark::Benchmark* b) -> void {
b->RangeMultiplier(4)->Range(256, static_cast<int64_t>(256 * 1024));
}
// The implementation file benchmarks start at 1024 lines instead, because a
// class with all of its functions defined doesn't fit in 256 lines.
static auto ConfigureImplFileBenchmark(benchmark::Benchmark* b) -> void {
b->RangeMultiplier(4)->Range(1024, static_cast<int64_t>(256 * 1024));
}
// In-process benchmarks measure the compiler as a library across each phase of
// compilation. The mode defaults to `Mode::InProcess`.
BENCHMARK(BM_CompileApiFileDenseDecls<Lang::Carbon, Phase::Lex>)
->Apply(ConfigureCompileBenchmark);
->Apply(ConfigureDenseDeclBenchmark);
BENCHMARK(BM_CompileApiFileDenseDecls<Lang::Carbon, Phase::Parse>)
->Apply(ConfigureCompileBenchmark);
->Apply(ConfigureDenseDeclBenchmark);
BENCHMARK(BM_CompileApiFileDenseDecls<Lang::Carbon, Phase::Check>)
->Apply(ConfigureCompileBenchmark);
->Apply(ConfigureDenseDeclBenchmark);
BENCHMARK(BM_CompileApiFileDenseDecls<Lang::Cpp, Phase::Lex>)
->Apply(ConfigureCompileBenchmark);
->Apply(ConfigureDenseDeclBenchmark);
BENCHMARK(BM_CompileApiFileDenseDecls<Lang::Cpp, Phase::Check>)
->Apply(ConfigureCompileBenchmark);
->Apply(ConfigureDenseDeclBenchmark);
// Subprocess benchmarks measure the same work end-to-end by executing the
// installed compiler binary, including process startup cost. They use real
// (wall-clock) time because the compilation happens in a child process whose
// CPU time isn't attributed to the benchmark process.
BENCHMARK(BM_CompileExecApiFileDenseDecls<Lang::Carbon, Phase::Lex>)
->Apply(ConfigureCompileBenchmark)
->Apply(ConfigureDenseDeclBenchmark)
->UseRealTime();
BENCHMARK(BM_CompileExecApiFileDenseDecls<Lang::Carbon, Phase::Parse>)
->Apply(ConfigureCompileBenchmark)
->Apply(ConfigureDenseDeclBenchmark)
->UseRealTime();
BENCHMARK(BM_CompileExecApiFileDenseDecls<Lang::Carbon, Phase::Check>)
->Apply(ConfigureCompileBenchmark)
->Apply(ConfigureDenseDeclBenchmark)
->UseRealTime();
BENCHMARK(BM_CompileExecApiFileDenseDecls<Lang::Cpp, Phase::Lex>)
->Apply(ConfigureCompileBenchmark)
->Apply(ConfigureDenseDeclBenchmark)
->UseRealTime();
BENCHMARK(BM_CompileExecApiFileDenseDecls<Lang::Cpp, Phase::Check>)
->Apply(ConfigureCompileBenchmark)
->Apply(ConfigureDenseDeclBenchmark)
->UseRealTime();
// In-process benchmarks of the implementation file pattern.
BENCHMARK(BM_CompileImplFile<Lang::Carbon, Phase::Lex>)
->Apply(ConfigureImplFileBenchmark);
BENCHMARK(BM_CompileImplFile<Lang::Carbon, Phase::Parse>)
->Apply(ConfigureImplFileBenchmark);
BENCHMARK(BM_CompileImplFile<Lang::Carbon, Phase::Check>)
->Apply(ConfigureImplFileBenchmark);
BENCHMARK(BM_CompileImplFile<Lang::Cpp, Phase::Lex>)
->Apply(ConfigureImplFileBenchmark);
BENCHMARK(BM_CompileImplFile<Lang::Cpp, Phase::Check>)
->Apply(ConfigureImplFileBenchmark);
} // namespace
} // namespace Carbon::Testing
File diff suppressed because it is too large. Load diff
+56 -2
View File
@@ -239,6 +239,15 @@ class SourceGen {
int declared_types_weight = 30;
};
// A definition size in a histogram of definition sizes, with its weight.
// `statements` counts the statements beyond the three that every definition
// has: an accumulator, a statement reading the parameters, and the final
// `return`.
struct DefSizeWeight {
int statements;
int weight;
};
// Parameters used to generate a file with dense declarations.
struct DenseDeclParams {
// TODO: Add more parameters to control generating top-level constructs
@@ -249,6 +258,28 @@ class SourceGen {
// Parameters used to guide the selection of types for use in declarations.
TypeUseParams type_use_params = {};
// Whether to define each declared function and method out-of-line, after
// every class.
bool define_decls_out_of_line = false;
// The histogram of sizes of out-of-line definitions. A file's definitions
// follow it as closely as their number allows.
//
// The default weights are percentages (rounded to sum to 100, with the
// 0.4% tail bucket rounded up to 1%) of the function definitions in a
// sample of the Carbon toolchain's, LLVM's, and Clang's implementation
// files, in buckets of their statement counts. Each size is a bucket's
// median, less the three statements that every generated definition has.
// The 43% of real definitions that have at most three statements get no
// more statements.
llvm::SmallVector<DefSizeWeight> out_of_line_def_sizes = {
{.statements = 0, .weight = 43}, {.statements = 2, .weight = 18},
{.statements = 5, .weight = 11}, {.statements = 8, .weight = 9},
{.statements = 13, .weight = 7}, {.statements = 20, .weight = 5},
{.statements = 29, .weight = 3}, {.statements = 43, .weight = 2},
{.statements = 67, .weight = 1}, {.statements = 125, .weight = 1},
};
};
// Access a global instance of this type to generate Carbon code for
@@ -367,6 +398,24 @@ class SourceGen {
llvm::StringRef type;
};
// A declaration's signature, for emitting its out-of-line definition, and
// the index of the definition's plan.
struct FunctionSig {
llvm::StringRef name;
bool is_method;
llvm::SmallVector<TypedName> params;
llvm::SmallVector<llvm::StringRef> param_consumers;
llvm::StringRef return_type;
int def_plan;
};
// A declaration to define out-of-line, after every class: the name of its
// class, and its signature.
struct OutOfLineDef {
llvm::StringRef class_name;
FunctionSig sig;
};
auto EmitParams(bool is_method, llvm::ArrayRef<TypedName> params,
llvm::StringRef indent, llvm::raw_ostream& os) -> void;
auto EmitFunctionDecl(llvm::StringRef name, bool is_private, bool is_method,
@@ -375,7 +424,10 @@ class SourceGen {
llvm::raw_ostream& os) -> void;
auto GenerateFunctionDecl(ClassGenState& state, llvm::StringRef name,
bool is_private, bool is_method, int param_count,
llvm::StringRef indent, llvm::raw_ostream& os)
llvm::StringRef indent, llvm::raw_ostream& os,
FunctionSig* captured = nullptr) -> void;
auto GenerateOutOfLineDef(ClassGenState& state, llvm::StringRef class_name,
const FunctionSig& sig, llvm::raw_ostream& os)
-> void;
auto GenerateInlineFunctionDef(ClassGenState& state, llvm::StringRef name,
int param_count, int local_count,
@@ -394,7 +446,9 @@ class SourceGen {
llvm::raw_ostream& os) -> void;
auto GenerateChecksumFunction(llvm::raw_ostream& os) -> void;
auto GenerateClassDef(const ClassParams& params, ClassGenState& state,
llvm::raw_ostream& os) -> void;
llvm::raw_ostream& os,
llvm::SmallVectorImpl<OutOfLineDef>& out_of_line_defs)
-> void;
absl::BitGen rng_;
llvm::BumpPtrAllocator storage_;
+65 -17
View File
@@ -569,30 +569,78 @@ TEST(SourceGenTest, GenApiFileDenseDeclsInlineBodiesCppCompiles) {
}
}
// Every declared function and method has an out-of-line definition, using the
// default size distribution (from 0-statement minimal definitions through
// deeply nested definitions).
TEST_P(GenApiFileDenseDeclsParamsTest, OutOfLineDefs) {
SourceGen::DenseDeclParams params = {
.class_params = {.inline_function_defs = 2, .max_body_locals = 3},
.define_decls_out_of_line = true};
EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(3000, params, 16));
EXPECT_TRUE(TestCompile(
GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(3000, params)));
}
// Large out-of-line definitions, which nest deeply. A definition's block
// arrangement and which locals its statements read depend on the seed, so
// compile several seeds.
TEST_P(GenApiFileDenseDeclsParamsTest, LargeOutOfLineDefs) {
SourceGen::DenseDeclParams params = {
.class_params = {.public_function_decls = 1,
.public_method_decls = 2,
.private_function_decls = 0,
.private_method_decls = 1,
.private_field_decls = 2},
.define_decls_out_of_line = true,
.out_of_line_def_sizes = {{.statements = 40, .weight = 1},
{.statements = 150, .weight = 1}}};
EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(3000, params, 24));
for (int _ : llvm::seq(4)) {
EXPECT_TRUE(TestCompile(
GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(3000, params)));
}
}
// The line estimates have to track the emitted lines closely, or files miss
// their target size. The target is large so that rounding to a whole number of
// classes is small next to the tolerance. C++ gets a larger tolerance for its
// access specifier lines, which the estimates don't count.
TEST(SourceGenTest, GenApiFileDenseDeclsLineTargetAccuracy) {
SourceGen::DenseDeclParams params = {
.class_params = {.inline_function_defs = 1,
.max_body_locals = 3,
.inline_getters = 1,
.inline_predicates = 1,
.inline_forwarders = 1}};
llvm::SmallVector<SourceGen::DenseDeclParams, 0> param_set;
param_set.push_back({.class_params = {.inline_function_defs = 1,
.max_body_locals = 3,
.inline_getters = 1,
.inline_predicates = 1,
.inline_forwarders = 1}});
// The implementation file shape.
param_set.push_back(
{.class_params = {.public_function_decls = 2,
.public_function_decl_params = {.max_params = 2},
.public_method_decls = 6,
.public_method_decl_params = {.max_params = 2},
.private_function_decls = 2,
.private_function_decl_params = {.max_params = 2},
.private_method_decls = 2,
.private_method_decl_params = {.max_params = 2},
.private_field_decls = 4},
.define_decls_out_of_line = true});
constexpr int TargetLines = 20000;
for (SourceGen::Language language :
{SourceGen::Language::Carbon, SourceGen::Language::Cpp}) {
SourceGen gen(language);
std::string source = gen.GenApiFileDenseDecls(TargetLines, params);
ssize_t lines = CountLines(source);
if (language == SourceGen::Language::Carbon) {
// Within 2% of the requested line count.
EXPECT_THAT(lines, AllOf(Ge(19600), Le(20400)));
} else {
// Within 10% of the requested line count.
EXPECT_THAT(lines, AllOf(Ge(18000), Le(22000)));
for (const SourceGen::DenseDeclParams& params : param_set) {
for (SourceGen::Language language :
{SourceGen::Language::Carbon, SourceGen::Language::Cpp}) {
SourceGen gen(language);
std::string source = gen.GenApiFileDenseDecls(TargetLines, params);
ssize_t lines = CountLines(source);
if (language == SourceGen::Language::Carbon) {
// Within 2% of the requested line count.
EXPECT_THAT(lines, AllOf(Ge(19600), Le(20400)))
<< "define_decls_out_of_line=" << params.define_decls_out_of_line;
} else {
// Within 10% of the requested line count.
EXPECT_THAT(lines, AllOf(Ge(18000), Le(22000)))
<< "define_decls_out_of_line=" << params.define_decls_out_of_line;
}
}
}
}