diff --git a/toolchain/benchmarking/BUILD b/toolchain/benchmarking/BUILD index 9b2a92da1a5d..3fde6b2772c6 100644 --- a/toolchain/benchmarking/BUILD +++ b/toolchain/benchmarking/BUILD @@ -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(), ) diff --git a/toolchain/benchmarking/compile_benchmark.cpp b/toolchain/benchmarking/compile_benchmark.cpp index a2674589a668..6a9ec9ee83e6 100644 --- a/toolchain/benchmarking/compile_benchmark.cpp +++ b/toolchain/benchmarking/compile_benchmark.cpp @@ -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(state, DenseDeclParams()); } +template +static auto BM_CompileImplFile(benchmark::State& state) -> void { + RunApiFileBenchmark(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(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(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(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) - ->Apply(ConfigureCompileBenchmark); + ->Apply(ConfigureDenseDeclBenchmark); BENCHMARK(BM_CompileApiFileDenseDecls) - ->Apply(ConfigureCompileBenchmark); + ->Apply(ConfigureDenseDeclBenchmark); BENCHMARK(BM_CompileApiFileDenseDecls) - ->Apply(ConfigureCompileBenchmark); + ->Apply(ConfigureDenseDeclBenchmark); BENCHMARK(BM_CompileApiFileDenseDecls) - ->Apply(ConfigureCompileBenchmark); + ->Apply(ConfigureDenseDeclBenchmark); BENCHMARK(BM_CompileApiFileDenseDecls) - ->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) - ->Apply(ConfigureCompileBenchmark) + ->Apply(ConfigureDenseDeclBenchmark) ->UseRealTime(); BENCHMARK(BM_CompileExecApiFileDenseDecls) - ->Apply(ConfigureCompileBenchmark) + ->Apply(ConfigureDenseDeclBenchmark) ->UseRealTime(); BENCHMARK(BM_CompileExecApiFileDenseDecls) - ->Apply(ConfigureCompileBenchmark) + ->Apply(ConfigureDenseDeclBenchmark) ->UseRealTime(); BENCHMARK(BM_CompileExecApiFileDenseDecls) - ->Apply(ConfigureCompileBenchmark) + ->Apply(ConfigureDenseDeclBenchmark) ->UseRealTime(); BENCHMARK(BM_CompileExecApiFileDenseDecls) - ->Apply(ConfigureCompileBenchmark) + ->Apply(ConfigureDenseDeclBenchmark) ->UseRealTime(); +// In-process benchmarks of the implementation file pattern. +BENCHMARK(BM_CompileImplFile) + ->Apply(ConfigureImplFileBenchmark); +BENCHMARK(BM_CompileImplFile) + ->Apply(ConfigureImplFileBenchmark); +BENCHMARK(BM_CompileImplFile) + ->Apply(ConfigureImplFileBenchmark); + +BENCHMARK(BM_CompileImplFile) + ->Apply(ConfigureImplFileBenchmark); +BENCHMARK(BM_CompileImplFile) + ->Apply(ConfigureImplFileBenchmark); + } // namespace } // namespace Carbon::Testing diff --git a/toolchain/benchmarking/source_gen.cpp b/toolchain/benchmarking/source_gen.cpp index f5870880e778..ef633f09a50a 100644 --- a/toolchain/benchmarking/source_gen.cpp +++ b/toolchain/benchmarking/source_gen.cpp @@ -7,10 +7,12 @@ #include #include #include +#include #include #include #include +#include "absl/random/seed_sequences.h" #include "common/raw_string_ostream.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" @@ -33,10 +35,14 @@ SourceGen::SourceGen(Language language) : language_(language) {} static constexpr int MinClassNameLength = 5; static constexpr int MinMemberNameLength = 4; -// The length of every local variable name. How many times a body spells each -// local depends on the local's position, so a single length keeps the byte +// The length of every local variable name. How many times a definition spells +// each local depends on the local's position, so a single length keeps the byte // count from depending on which name lands where. Locals are shorter than class -// names, so they can't shadow a class that the body names. +// names, so they can't shadow a class that the definition names. This is +// hard-coded rather than in `ClassParams` because seed-independent output sizes +// require a single length `< MinClassNameLength`; it would only need to be +// parameterized to benchmark identifier-length sensitivity specifically for +// local variables. static constexpr int LocalNameLength = 3; // The number of function and method declarations in each class. @@ -73,6 +79,465 @@ static auto WeightedFixedTypes( } } +// The kinds of statement in a definition plan. A plan fixes how many statements +// of each kind a definition has at each depth of nesting, and the definition +// arranges them randomly. A statement has the same size wherever it lands at +// its depth, so the arrangement doesn't change the definition's size. +// +// TODO: Plans only declare and update `i32` locals, read each parameter once, +// and make no calls. Real definitions have locals of many types, read +// parameters and fields throughout, and make calls in most statements. Add +// those statements and expressions, fixing each one's spelling before the +// shuffle as the type use pools do, so that sizes stay the same for every seed. +enum class PlanKind : uint8_t { + // `var : i32 = ;` + Local, + // ` = ;` + Update, + // `if () {`, a block, and `}`. + If, + // `if () {`, a block, `} else {`, a block, and `}`. + IfElse, + // `if () {`, a block, `} else if () {`, a block, and `}`. + ElseIf, + // `while () {`, a block, and `}`. + While, + // `if () {`, `return ;`, and `}`. + GuardReturn, + // `if () {`, `break;` or `continue;`, and `}`, in a loop's block. + GuardExit, + // ` = + ;`, where the reads apply a consumer template + // to each parameter, and read `self` in a method. Definitions add one of + // these to their plan's statements at depth 0. + ReadParams, +}; + +static constexpr int NumPlanKinds = static_cast(PlanKind::ReadParams) + 1; + +// The number of blocks that a statement of `kind` opens. +static auto NumPlanBlocks(PlanKind kind) -> int { + switch (kind) { + case PlanKind::If: + case PlanKind::While: + return 1; + case PlanKind::IfElse: + case PlanKind::ElseIf: + return 2; + default: + return 0; + } +} + +// A statement in a definition plan. `spelling_index` selects among the +// available spellings for `kind`, in `[0, NumPlanSpellings(kind))`. +struct PlanStmt { + PlanKind kind; + int spelling_index; +}; + +// The expressions and conditions in plan statements. `{0}` and `{1}` are +// locals, which all have the same length. Conditions compare a single local, so +// that they can't compare a local with itself. +static constexpr llvm::StringLiteral PlanExprs[] = { + "{0} + 1", "{0} * 2", "{0} - {1}", "({0} % 7) + {1}"}; +static constexpr llvm::StringLiteral PlanConds[] = {"{0} > 3", "{0} < 9", + "{0} == 2", "{0} != 5"}; + +// The number of distinct spellings for a statement of `kind`. +static auto NumPlanSpellings(PlanKind kind) -> int { + switch (kind) { + case PlanKind::Local: + case PlanKind::Update: + return std::size(PlanExprs); + case PlanKind::If: + case PlanKind::IfElse: + case PlanKind::ElseIf: + case PlanKind::While: + case PlanKind::GuardReturn: + return std::size(PlanConds); + case PlanKind::GuardExit: + // Pairs one of `PlanConds` with `break;` or `continue;`. + return std::lcm(std::size(PlanConds), 2); + case PlanKind::ReadParams: + return 1; + } +} + +// The statements of a definition plan at each depth. The statement that a guard +// returns or exits with is one depth below the guard, and isn't listed. +struct DefPlan { + llvm::SmallVector> levels; + // The number of lines and locals in the plan's statements. + int lines = 0; + int locals = 0; +}; + +// The internal shape calibration of definition plans, which approximates the +// function definitions in a sample of the Carbon toolchain's, LLVM's, and +// Clang's implementation files, as classified with libclang (excluding +// definitions with a `switch`). +// +// These constants are hardcoded rather than in `DenseDeclParams` or +// `ClassParams` unless a benchmark or test needs to vary a specific structural +// dimension inside definitions (such as nesting depth, branching factor, or +// local variable density) independently of statement count. +// +// All rates and bucket distributions below are integer percentages (with +// multi-bucket rows summing to 100). +// +// A row of `PlanShapeTable` giving the shape parameters for plans with at +// least `min_statements` statements: the percentage of plans with each maximum +// depth, and the number of guard returns at a depth as a percentage of the +// statements at the next depth. +struct PlanShapeRow { + int min_statements; + std::array max_depth_percents; + int guard_return_percent; +}; +// Rows are sorted in strictly increasing order of `min_statements`, starting +// with `min_statements = 0` so that every statement count has an applicable +// row. A plan deterministically uses the last row with +// `min_statements <= statements`. +static constexpr PlanShapeRow PlanShapeTable[] = { + {.min_statements = 0, + .max_depth_percents = {100, 0, 0, 0, 0, 0}, + .guard_return_percent = 0}, + {.min_statements = 2, + .max_depth_percents = {25, 62, 13, 0, 0, 0}, + .guard_return_percent = 65}, + {.min_statements = 5, + .max_depth_percents = {8, 64, 25, 3, 0, 0}, + .guard_return_percent = 47}, + {.min_statements = 8, + .max_depth_percents = {7, 46, 34, 11, 2, 0}, + .guard_return_percent = 32}, + {.min_statements = 13, + .max_depth_percents = {2, 36, 39, 18, 4, 1}, + .guard_return_percent = 21}, + {.min_statements = 20, + .max_depth_percents = {2, 21, 42, 25, 7, 3}, + .guard_return_percent = 16}, + {.min_statements = 29, + .max_depth_percents = {0, 11, 32, 35, 17, 5}, + .guard_return_percent = 12}, + {.min_statements = 43, + .max_depth_percents = {0, 2, 23, 42, 21, 12}, + .guard_return_percent = 10}, + {.min_statements = 67, + .max_depth_percents = {0, 5, 4, 29, 30, 32}, + .guard_return_percent = 12}, +}; +// Indexed by a plan's maximum depth, each row gives the percentage of the +// plan's statements at each depth (summing to 100). Every definition also has +// three statements at depth 0, so plans have a lower share there than real +// definitions. +static constexpr std::array PlanDepthPercents[] = { + {100, 0, 0, 0, 0, 0}, {60, 40, 0, 0, 0, 0}, {38, 45, 17, 0, 0, 0}, + {25, 38, 27, 10, 0, 0}, {17, 29, 28, 18, 8, 0}, {13, 25, 24, 19, 13, 6}, +}; +// The percentage of loop blocks that have a guard exit (`break` or `continue`). +static constexpr int LoopExitPercent = 35; +// The percentage of non-guard statements at the next depth that open a new +// `if`, `else`, or `while` block (~2.1 statements per block). +static constexpr int NewBlockPercent = 48; +// The percentages of those blocks that are a loop's, and that are one of the +// two blocks of an `if` with an `else` or `else if`. +static constexpr int LoopBlockPercent = 15; +static constexpr int ElseBlockPercent = 30; +// The percentage of those two-block `if` statements that use `else if` rather +// than `else`. +static constexpr int ElseIfPercent = 42; +// How many times more likely a loop block is than another block of the same +// size to get each further statement when arranging a definition. +static constexpr int LoopBlockWeight = 3; +// The percentages of the statements at depth 0, and deeper, that declare a new +// local variable. +static constexpr int TopLocalPercent = 35; +static constexpr int NestedLocalPercent = 25; + +// Scales `count` by `percent`%, rounding up with probability equal to the +// remainder (`(count * percent % 100) / 100.0`). +using ScaleByPercentFn = llvm::function_refint>; + +// Returns the maximum depth of the `variant`th plan with `statements` +// statements. The variants of a size follow the distribution in its row of +// `PlanShapeTable`: multiples of the golden ratio (`std::numbers::phi`) mod 1.0 +// in `double` spread their choices evenly across `[0, 100)` without needing a +// fixed-point rational approximation. +static auto ChoosePlanMaxDepth(const PlanShapeRow& shape, int statements, + int variant) -> int { + int choice = static_cast( + std::fmod((variant + 0.5) * std::numbers::phi, 1.0) * 100); + int max_depth = 0; + for (int percent : shape.max_depth_percents) { + choice -= percent; + if (choice < 0) { + break; + } + ++max_depth; + } + return std::min(max_depth, statements - 1); +} + +// Splits `statements` statements between depths 0 through `max_depth`, +// following `PlanDepthPercents` and giving each depth at least one. +static auto SplitPlanDepths(int statements, int max_depth, + ScaleByPercentFn scale_by_percent) + -> llvm::SmallVector { + llvm::SmallVector depth_counts; + int cumulative_percent = 0; + int assigned = 0; + for (int percent : + llvm::ArrayRef(PlanDepthPercents[max_depth]).take_front(max_depth)) { + cumulative_percent += percent; + int upto = scale_by_percent(statements, cumulative_percent); + depth_counts.push_back(upto - assigned); + assigned = upto; + } + depth_counts.push_back(statements - assigned); + for (int& count : depth_counts) { + if (count == 0) { + ++count; + --*llvm::max_element(depth_counts); + } + } + return depth_counts; +} + +// Composes the plan of a definition with `statements` statements, for the +// `variant`th definition of that size. Percentage-scaled counts round with a +// generator seeded with the size and variant, so that definitions of one size +// vary while their average follows the calibration, and nothing depends on the +// `SourceGen` seed. +static auto ComposeDefPlan(int statements, int variant) -> DefPlan { + DefPlan plan; + if (statements == 0) { + return plan; + } + absl::SeedSeq seed_seq = {statements, variant}; + absl::BitGen rng(seed_seq); + auto scale_by_percent = [&](int count, int percent) { + return (count * percent + absl::Uniform(rng, 0, 100)) / 100; + }; + + // Find the last row satisfying `statements >= row.min_statements`. This + // invariant is satisfied for `*shape` throughout the loop because the first + // row has `min_statements == 0`. + static_assert(PlanShapeTable[0].min_statements == 0); + const PlanShapeRow* shape = PlanShapeTable; + for (const PlanShapeRow& row : PlanShapeTable) { + if (&row != PlanShapeTable) { + CARBON_CHECK(row.min_statements > (&row - 1)->min_statements); + } + if (statements >= row.min_statements) { + shape = &row; + } + } + llvm::SmallVector depth_counts = SplitPlanDepths( + statements, ChoosePlanMaxDepth(*shape, statements, variant), + scale_by_percent); + + plan.levels.resize(depth_counts.size()); + // Select each statement's spelling starting from `variant` and advancing with + // each statement of the same kind, so that spellings rotate both across + // variants of the same size and across same-kind statements within a plan. + std::array next_spelling = {}; + next_spelling.fill(variant); + auto add = [&](int depth, PlanKind kind, int count) { + int num_spellings = NumPlanSpellings(kind); + int& next = next_spelling[static_cast(kind)]; + for (auto _ : llvm::seq(count)) { + plan.levels[depth].push_back( + {.kind = kind, .spelling_index = next % num_spellings}); + ++next; + } + }; + + // How many of `depth_counts[depth]` are the `return`, `break`, or `continue` + // body statements of guards at `depth - 1` (which are emitted as part of + // those guards rather than as separate `PlanStmt`s at `depth`). + int guard_children = 0; + // The blocks at a depth, and how many of them are loop blocks. + int blocks = 1; + int loop_blocks = 0; + int num_depths = depth_counts.size(); + for (int depth : llvm::seq(num_depths)) { + int count = depth_counts[depth]; + int heads = count - guard_children; + int next = depth + 1 < num_depths ? depth_counts[depth + 1] : 0; + int guards = 0; + int exits = 0; + int ifs = 0; + int pairs = 0; + int loops = 0; + int next_blocks = 0; + if (next > 0) { + // Guards' statements can't hold deeper ones, so leave a free statement at + // the next depth when there are any. + int min_free = depth + 2 < num_depths ? 1 : 0; + exits = std::min({scale_by_percent(loop_blocks, LoopExitPercent), heads, + next - min_free}); + guards = std::min({scale_by_percent(next, shape->guard_return_percent), + heads - exits, next - exits - min_free}); + // The number of statements at the next depth that aren't the body of a + // guard at this depth, and so must be placed in blocks opened by + // non-guard statements at this depth. + int free = next - guards - exits; + // When there are such `free` statements at the next depth (rather than + // every statement at the next depth being a guard's body), keep at least + // one non-guard statement at this depth to open a block for them. + if (free > 0 && heads == guards + exits) { + if (guards > 0) { + --guards; + } else { + --exits; + } + ++free; + } + if (free > 0) { + next_blocks = std::max(1, scale_by_percent(free, NewBlockPercent)); + loops = scale_by_percent(next_blocks, LoopBlockPercent); + pairs = std::min(scale_by_percent(next_blocks, ElseBlockPercent / 2), + (next_blocks - loops) / 2); + ifs = next_blocks - loops - 2 * pairs; + // Fit the statements that open blocks into this depth, merging blocks + // when they don't fit. + int room = heads - guards - exits; + while (ifs + pairs + loops > room) { + if (ifs >= 2) { + ifs -= 2; + ++pairs; + } else if (ifs > 0) { + --ifs; + --next_blocks; + } else if (loops > 0) { + --loops; + --next_blocks; + } else { + --pairs; + next_blocks -= 2; + } + } + } + } + + int fixed = guards + exits + ifs + pairs + loops; + // Each block at this depth ends with a statement that isn't a local. + int max_locals = heads - fixed - std::max(0, blocks - fixed); + int local_percent = depth == 0 ? TopLocalPercent : NestedLocalPercent; + int locals = std::min(scale_by_percent(heads, local_percent), max_locals); + int else_ifs = scale_by_percent(pairs, ElseIfPercent); + add(depth, PlanKind::Local, locals); + add(depth, PlanKind::Update, heads - fixed - locals); + add(depth, PlanKind::If, ifs); + add(depth, PlanKind::IfElse, pairs - else_ifs); + add(depth, PlanKind::ElseIf, else_ifs); + add(depth, PlanKind::While, loops); + add(depth, PlanKind::GuardReturn, guards); + add(depth, PlanKind::GuardExit, exits); + + // Each statement takes a line, and so does the `}` that ends each block and + // guard, and the line between the blocks of a pair. + plan.lines += count + ifs + loops + 2 * pairs + guards + exits; + plan.locals += locals; + guard_children = guards + exits; + blocks = next_blocks; + loop_blocks = loops; + } + return plan; +} + +// Returns how many of `num_defs` definitions have each size in `sizes`, in +// proportion to its weight. The definitions left over from rounding down go to +// the sizes with the largest remainders, the earliest first on ties. +static auto ApportionDefSizes(int num_defs, + llvm::ArrayRef sizes) + -> llvm::SmallVector { + int64_t total_weight = 0; + for (const SourceGen::DefSizeWeight& size : sizes) { + CARBON_CHECK(size.statements >= 0 && size.weight >= 0, + "Definition sizes and weights can't be negative."); + total_weight += size.weight; + } + CARBON_CHECK(total_weight > 0, + "Definition sizes need a positive total weight."); + llvm::SmallVector counts; + llvm::SmallVector remainders; + int left_over = num_defs; + for (const SourceGen::DefSizeWeight& size : sizes) { + int64_t share = static_cast(num_defs) * size.weight; + counts.push_back(share / total_weight); + remainders.push_back(share % total_weight); + left_over -= counts.back(); + } + llvm::SmallVector order(sizes.size()); + std::iota(order.begin(), order.end(), 0); + llvm::stable_sort(order, [&](int lhs, int rhs) { + return remainders[lhs] > remainders[rhs]; + }); + for (int index : llvm::ArrayRef(order).take_front(left_over)) { + ++counts[index]; + } + return counts; +} + +// Builds the plans for `num_defs` definitions, with sizes following `sizes`. +// Each size's plans spread evenly through the order, so that any stretch of the +// order has a mix of sizes. +static auto BuildDefPlans(int num_defs, + llvm::ArrayRef sizes) + -> llvm::SmallVector { + // Entries are sorted by `position`, which is `(variant + 0.5) / count`, to + // interleave buckets with different counts. + struct Entry { + double position; + int statements; + int variant; + }; + llvm::SmallVector entries; + entries.reserve(num_defs); + llvm::SmallVector counts = ApportionDefSizes(num_defs, sizes); + for (auto [size, count] : llvm::zip_equal(sizes, counts)) { + for (int variant : llvm::seq(count)) { + entries.push_back({.position = (variant + 0.5) / count, + .statements = size.statements, + .variant = variant}); + } + } + llvm::stable_sort(entries, [](const Entry& lhs, const Entry& rhs) { + return lhs.position < rhs.position; + }); + llvm::SmallVector plans; + plans.reserve(num_defs); + for (const Entry& entry : entries) { + plans.push_back(ComposeDefPlan(entry.statements, entry.variant)); + } + return plans; +} + +// Estimates the average number of lines in the plans of definitions with sizes +// following `sizes`. Uses `double` (like the other `EstimateAvg*Lines` helpers +// below) to accumulate fractional average line counts across variants and +// constructs before a single final rounding to a whole number of classes. +static auto EstimateAvgDefPlanLines( + llvm::ArrayRef sizes) -> double { + // Average over enough variants that their rounding evens out. + constexpr int NumVariants = 16; + double lines = 0.0; + int64_t total_weight = 0; + for (const SourceGen::DefSizeWeight& size : sizes) { + int size_lines = 0; + for (int variant : llvm::seq(NumVariants)) { + size_lines += ComposeDefPlan(size.statements, variant).lines; + } + lines += static_cast(size_lines) / NumVariants * size.weight; + total_weight += size.weight; + } + CARBON_CHECK(total_weight > 0, + "Definition sizes need a positive total weight."); + return lines / total_weight; +} + // The shuffled state used to generate some number of classes. // // This state encodes everything used to generate class definitions. The state @@ -81,9 +546,7 @@ static auto WeightedFixedTypes( // Detailed comments for out-of-line methods are on their definitions. class SourceGen::ClassGenState { public: - ClassGenState(SourceGen& gen, int num_classes, - const ClassParams& class_params, - const TypeUseParams& type_use_params); + ClassGenState(SourceGen& gen, int num_classes, const DenseDeclParams& params); auto public_function_param_counts() -> llvm::SmallVectorImpl& { return public_function_param_counts_; @@ -105,6 +568,9 @@ class SourceGen::ClassGenState { auto forwarder_param_counts() -> llvm::SmallVectorImpl& { return forwarder_param_counts_; } + // The plans of the out-of-line definitions. A definition uses the plan with + // the index of its return type's use; see `BuildTypePool`. + auto def_plans() -> llvm::ArrayRef { return def_plans_; } auto getter_field_types() -> llvm::SmallVectorImpl& { return getter_field_types_; @@ -171,11 +637,13 @@ class SourceGen::ClassGenState { } } - // A use of a type drawn from a pool. A consumed use also has the consumer - // template that reads it. + // A use of a type drawn from a pool, and its index in the pool before the + // pool was shuffled. A consumed use also has the consumer template that reads + // it. struct TypeUse { llvm::StringRef name; llvm::StringRef consumer; + int index = -1; }; // Each kind of type use draws from its own pool, so that every use in a pool @@ -184,23 +652,33 @@ class SourceGen::ClassGenState { // constructs a value of its type, and "consumed" when a body reads it with a // consumer template. - // Return and parameter types of declarations, and field types when the file - // has no bodies. + // Return and parameter types of declarations without out-of-line + // definitions, and field types when the file has no definitions. auto GetDeclType() -> TypeUse { return GetValidTypeUse(decl_type_pool_); } // Parameter types of inline definitions, which are consumed. auto GetInlineParamType() -> TypeUse { return GetValidTypeUse(inline_param_pool_); } // Return types of inline definitions, and field types when the file has - // bodies, which are produced. + // definitions, which are produced. auto GetProducedType() -> TypeUse { return GetValidTypeUse(produced_type_pool_); } - // `Make` produces every field when the file has bodies. Without bodies, - // fields share the declaration pool, which can include types that have no - // value expression. + // Return types of declarations with out-of-line definitions, which are + // spelled twice and produced. + auto GetOutOfLineReturnType() -> TypeUse { + return GetValidTypeUse(out_of_line_return_pool_); + } + // Parameter types of declarations with out-of-line definitions, which are + // spelled twice and consumed. + auto GetOutOfLineParamType() -> TypeUse { + return GetValidTypeUse(out_of_line_param_pool_); + } + // `Make` produces every field when the file has definitions. Without + // definitions, fields share the declaration pool, which can include types + // that have no value expression. auto GetFieldType() -> TypeUse { - return GetValidTypeUse(has_bodies_ ? produced_type_pool_ : decl_type_pool_); + return GetValidTypeUse(has_defs_ ? produced_type_pool_ : decl_type_pool_); } // Return and parameter types of forwarders, which the declarations that they // call spell again. @@ -208,10 +686,14 @@ class SourceGen::ClassGenState { return GetValidTypeUse(forward_type_pool_); } - auto has_bodies() -> bool { return has_bodies_; } + auto has_defs() -> bool { return has_defs_; } + auto define_decls_out_of_line() -> bool { return define_decls_out_of_line_; } auto type_pools_empty() -> bool { return decl_type_pool_.uses.empty() && inline_param_pool_.uses.empty() && - produced_type_pool_.uses.empty() && forward_type_pool_.uses.empty(); + produced_type_pool_.uses.empty() && + forward_type_pool_.uses.empty() && + out_of_line_return_pool_.uses.empty() && + out_of_line_param_pool_.uses.empty(); } private: @@ -239,6 +721,7 @@ class SourceGen::ClassGenState { llvm::SmallVector inline_function_param_counts_; llvm::SmallVector local_counts_; llvm::SmallVector forwarder_param_counts_; + llvm::SmallVector def_plans_; // Getters return a copy of their field, and `Make` initializes it, so getter // and predicate fields have fixed types with a value expression. These types @@ -248,8 +731,9 @@ class SourceGen::ClassGenState { llvm::SmallVector predicate_fields_; llvm::SmallVector class_names_; - // Field names have their own pool because `Make` spells each field name a - // second time. + // Out-of-line definitions spell declared function and method names a second + // time, and `Make` does the same for field names, so these have separate + // pools. llvm::SmallVector decl_names_; llvm::SmallVector field_names_; llvm::SmallVector param_names_; @@ -267,14 +751,17 @@ class SourceGen::ClassGenState { llvm::SmallVector forwarder_param_names_; bool is_cpp_; - // Whether the file has any bodies. Then each class also gets a `Make` - // function (a default constructor in C++), a `Checksum` method, and a `tag` - // field. - bool has_bodies_; + // Whether the file has any function or method definitions. Then each class + // also gets a `Make` function (a default constructor in C++), a `Checksum` + // method, and a `tag` field. + bool has_defs_; + bool define_decls_out_of_line_; TypePool decl_type_pool_; TypePool inline_param_pool_; TypePool produced_type_pool_; TypePool forward_type_pool_; + TypePool out_of_line_return_pool_; + TypePool out_of_line_param_pool_; Set valid_type_names_; Set class_name_set_; @@ -299,10 +786,12 @@ static auto Sum(const T& range) -> int { // generated so that we can distribute random components across all the // definitions. SourceGen::ClassGenState::ClassGenState(SourceGen& gen, int num_classes, - const ClassParams& class_params, - const TypeUseParams& type_use_params) + const DenseDeclParams& params) : is_cpp_(gen.IsCpp()), - has_bodies_(NumInlineDefsPerClass(class_params) > 0) { + has_defs_(NumInlineDefsPerClass(params.class_params) > 0 || + params.define_decls_out_of_line), + define_decls_out_of_line_(params.define_decls_out_of_line) { + const ClassParams& class_params = params.class_params; public_function_param_counts_ = gen.GetShuffledInts(num_classes * class_params.public_function_decls, 0, class_params.public_function_decl_params.max_params); @@ -323,9 +812,15 @@ SourceGen::ClassGenState::ClassGenState(SourceGen& gen, int num_classes, field_names_ = gen.GetShuffledIdentifiers(num_classes * class_params.private_field_decls, /*min_length=*/MinMemberNameLength); - int num_params = - Sum(public_function_param_counts_) + Sum(public_method_param_counts_) + - Sum(private_function_param_counts_) + Sum(private_method_param_counts_); + int num_out_of_line_defs = define_decls_out_of_line_ + ? num_classes * NumDeclsPerClass(class_params) + : 0; + // Each out-of-line definition has one parameter beyond its random count; see + // `BuildClassAndTypeNames`. + int num_params = Sum(public_function_param_counts_) + + Sum(public_method_param_counts_) + + Sum(private_function_param_counts_) + + Sum(private_method_param_counts_) + num_out_of_line_defs; param_names_ = gen.GetShuffledIdentifiers(num_params); inline_function_param_counts_ = @@ -337,7 +832,12 @@ SourceGen::ClassGenState::ClassGenState(SourceGen& gen, int num_classes, // `BuildClassAndTypeNames`. int num_inline_params = Sum(inline_function_param_counts_) + num_inline_functions; + def_plans_ = + BuildDefPlans(num_out_of_line_defs, params.out_of_line_def_sizes); int num_locals = Sum(local_counts_); + for (const DefPlan& plan : def_plans_) { + num_locals += plan.locals; + } int num_getters = num_classes * class_params.inline_getters; int num_predicates = num_classes * class_params.inline_predicates; int num_forwarders = num_classes * class_params.inline_forwarders; @@ -359,7 +859,8 @@ SourceGen::ClassGenState::ClassGenState(SourceGen& gen, int num_classes, forwarder_param_names_ = gen.GetShuffledIdentifiers(Sum(forwarder_param_counts_)); - BuildClassAndTypeNames(gen, num_classes, class_params, type_use_params); + BuildClassAndTypeNames(gen, num_classes, class_params, + params.type_use_params); } auto SourceGen::ClassGenState::GetValidTypeUse(TypePool& pool) -> TypeUse { @@ -397,7 +898,10 @@ auto SourceGen::ClassGenState::GetValidTypeUse(TypePool& pool) -> TypeUse { // With `producible_only`, the pool only uses fixed types that have a value // expression. With `consumed`, each use gets one of its type's consumer // templates, round-robin per type before the shuffle, so that the mix of -// templates doesn't depend on the seed. +// templates doesn't depend on the seed. Each use also records its pre-shuffle +// `index` in the pool so callers can pair it with other unshuffled +// per-function state (such as `def_plans_`), keeping the pairing and the +// resulting generated code size independent of the shuffle seed. // // `valid_type_names_` must already contain the fixed type spellings. auto SourceGen::ClassGenState::BuildTypePool( @@ -504,6 +1008,9 @@ auto SourceGen::ClassGenState::BuildTypePool( CARBON_CHECK(static_cast(pool.uses.size()) == num_types); pool.last_index = num_types; + for (auto [index, use] : llvm::enumerate(pool.uses)) { + use.index = static_cast(index); + } std::shuffle(pool.uses.begin(), pool.uses.end(), gen.rng_); return pool; } @@ -554,7 +1061,7 @@ auto SourceGen::ClassGenState::BuildClassAndTypeNames( int num_inline_returns = num_classes * class_params.inline_function_defs; int num_inline_params = Sum(inline_function_param_counts_); int num_fields = num_classes * class_params.private_field_decls; - int num_produced_fields = has_bodies_ ? num_fields : 0; + int num_produced_fields = has_defs_ ? num_fields : 0; // Each class draws `inline_function_defs` return types from this pool after // its fields. @@ -572,13 +1079,30 @@ auto SourceGen::ClassGenState::BuildClassAndTypeNames( class_params.inline_function_defs, /*producible_only=*/false, /*consumed=*/true, type_use_params); - // Each class draws `decls_per_class` return types from this pool after its - // fields. - decl_type_pool_ = BuildTypePool( - gen, - num_decl_returns + num_decl_params + (num_fields - num_produced_fields), - decls_per_class, - /*producible_only=*/false, /*consumed=*/false, type_use_params); + if (!define_decls_out_of_line_) { + // Each class draws `decls_per_class` return types from this pool after its + // fields. + decl_type_pool_ = BuildTypePool( + gen, + num_decl_returns + num_decl_params + (num_fields - num_produced_fields), + decls_per_class, + /*producible_only=*/false, /*consumed=*/false, type_use_params); + } else { + // Each class draws `decls_per_class` return types from this pool after its + // fields. A definition's guards also produce a value of its return type, so + // each use's index pairs it with the definition plan that has the same + // index. + out_of_line_return_pool_ = BuildTypePool( + gen, num_decl_returns, decls_per_class, + /*producible_only=*/true, /*consumed=*/false, type_use_params); + // As for inline definitions, each declaration has one parameter beyond its + // random count, so that each class draws at least `decls_per_class` + // parameter types from this pool. + int num_decl_extra_params = num_decl_returns; + out_of_line_param_pool_ = BuildTypePool( + gen, num_decl_params + num_decl_extra_params, decls_per_class, + /*producible_only=*/false, /*consumed=*/true, type_use_params); + } // Each class draws `inline_forwarders` return types from this pool after its // fields. @@ -688,20 +1212,28 @@ static auto EstimateAvgInlineFunctionDefLines(SourceGen::ClassParams params) // Note that this should match the heuristics used when formatting. // TODO: See top-level TODO about line estimates and formatting. -static auto EstimateAvgClassDefLines(SourceGen::ClassParams params) -> double { +static auto EstimateAvgClassDefLines( + const SourceGen::DenseDeclParams& dense_params) -> double { + const SourceGen::ClassParams& params = dense_params.class_params; + bool define_decls_out_of_line = dense_params.define_decls_out_of_line; // Comment line, and class open line. double avg = 2.0; + // Declarations with out-of-line definitions have an extra parameter. + int decl_extra_params = define_decls_out_of_line ? 1 : 0; + // One comment line and blank line per function, plus the function lines. - avg += - (2.0 + EstimateAvgFunctionDeclLines(params.public_function_decl_params)) * - params.public_function_decls; - avg += (2.0 + EstimateAvgMethodDeclLines(params.public_method_decl_params)) * + avg += (2.0 + EstimateAvgFunctionDeclLines(params.public_function_decl_params, + decl_extra_params)) * + params.public_function_decls; + avg += (2.0 + EstimateAvgMethodDeclLines(params.public_method_decl_params, + decl_extra_params)) * params.public_method_decls; - avg += (2.0 + - EstimateAvgFunctionDeclLines(params.private_function_decl_params)) * + avg += (2.0 + EstimateAvgFunctionDeclLines( + params.private_function_decl_params, decl_extra_params)) * params.private_function_decls; - avg += (2.0 + EstimateAvgMethodDeclLines(params.private_method_decl_params)) * + avg += (2.0 + EstimateAvgMethodDeclLines(params.private_method_decl_params, + decl_extra_params)) * params.private_method_decls; avg += (2.0 + EstimateAvgInlineFunctionDefLines(params)) * params.inline_function_defs; @@ -715,24 +1247,32 @@ static auto EstimateAvgClassDefLines(SourceGen::ClassParams params) -> double { forwarder_signature_lines) * params.inline_forwarders; - bool has_bodies = NumInlineDefsPerClass(params) > 0; + bool has_defs = NumInlineDefsPerClass(params) > 0 || define_decls_out_of_line; // A blank line and all the fields (if any), including `tag` when the file has - // bodies. + // definitions. double num_fields = params.private_field_decls + params.inline_getters + - params.inline_predicates + (has_bodies ? 1.0 : 0.0); + params.inline_predicates + (has_defs ? 1.0 : 0.0); if (num_fields > 0) { avg += 1.0 + num_fields; } // `Make` and `Checksum` each have a blank line, a comment line, a signature // line, a return line, and a closing brace line. A C++ constructor puts its - // initializers and empty body on one line, so this overestimates C++ by a - // line. - if (has_bodies) { + // initializers and empty definition on one line, so this overestimates C++ by + // a line. + if (has_defs) { avg += 10.0; } + // Each out-of-line definition has a blank line, a comment line, a signature + // line, an accumulator line, a line reading the parameters, its plan's lines, + // a return line, and a closing brace line. + if (define_decls_out_of_line) { + avg += (7.0 + EstimateAvgDefPlanLines(dense_params.out_of_line_def_sizes)) * + NumDeclsPerClass(params); + } + // No need to account for the class close line, we have an extra blank line // count for the last of the above. return avg; @@ -748,12 +1288,12 @@ auto SourceGen::GenApiFileDenseDecls(int target_lines, // Note that we want a blank line after our file comment block, so every class // needs a blank line. constexpr int NumFileCommentLines = 4; - double avg_class_lines = EstimateAvgClassDefLines(params.class_params); + double avg_class_lines = EstimateAvgClassDefLines(params); CARBON_CHECK(target_lines > NumFileCommentLines + avg_class_lines, "Not enough target lines to generate a single class!"); // Round to the nearest whole class. Truncating can leave the file nearly a - // whole class short of the target, which matters when classes with bodies - // run to hundreds of lines. + // whole class short of the target, which matters when classes with + // definitions run to hundreds of lines. int num_classes = std::lround((target_lines - NumFileCommentLines) / (avg_class_lines + 1)); int expected_lines = @@ -765,7 +1305,11 @@ auto SourceGen::GenApiFileDenseDecls(int target_lines, "// {0} target lines: {1} classes, {2} expected lines", target_lines, num_classes, expected_lines) << "\n"; - source << "//\n// Generating as an API file with dense declarations.\n"; + source << "//\n// Generating as " + << (params.define_decls_out_of_line + ? "an implementation file with out-of-line definitions" + : "an API file with dense declarations") + << ".\n"; // Carbon uses an implicitly imported prelude to get builtin types, but C++ // requires header files so include those. @@ -777,11 +1321,18 @@ auto SourceGen::GenApiFileDenseDecls(int target_lines, source << "#include \n"; } - auto class_gen_state = ClassGenState(*this, num_classes, params.class_params, - params.type_use_params); + auto class_gen_state = ClassGenState(*this, num_classes, params); + llvm::SmallVector out_of_line_defs; for (auto _ : llvm::seq(num_classes)) { source << "\n"; - GenerateClassDef(params.class_params, class_gen_state, source); + GenerateClassDef(params.class_params, class_gen_state, source, + out_of_line_defs); + } + // Out-of-line definitions follow every class, as in an implementation file, + // where all of the API's declarations are visible. + for (const OutOfLineDef& def : out_of_line_defs) { + source << "\n"; + GenerateOutOfLineDef(class_gen_state, def.class_name, def.sig, source); } // Make sure we consumed all the state. @@ -1314,20 +1865,42 @@ auto SourceGen::EmitFunctionDecl(llvm::StringRef name, bool is_private, // // The declaration can be configured with a function name, private modifier, // whether it is a method, the parameter count, and how indented it is. Its -// parameter names and types come from `state`. +// parameter names and types come from `state`. When `captured` is not null, the +// declaration has an out-of-line definition, and records its signature in +// `captured`. auto SourceGen::GenerateFunctionDecl(ClassGenState& state, llvm::StringRef name, bool is_private, bool is_method, int param_count, llvm::StringRef indent, - llvm::raw_ostream& os) -> void { - UniqueIdentifierPopper unique_param_names(*this, state.param_names()); - llvm::SmallVector params; - params.reserve(param_count); + llvm::raw_ostream& os, + FunctionSig* captured) -> void { + bool out_of_line = captured != nullptr; + // Add the extra parameter; see `BuildClassAndTypeNames`. + if (out_of_line) { + param_count += 1; + } + // Exclude class names so that a parameter can't shadow a class that an + // out-of-line definition names. + UniqueIdentifierPopper unique_param_names(*this, state.param_names(), + &state.class_name_set()); + FunctionSig sig = {.name = name, .is_method = is_method}; + sig.params.reserve(param_count); + sig.param_consumers.reserve(param_count); for (auto _ : llvm::seq(param_count)) { - params.push_back( - {.name = unique_param_names.Pop(), .type = state.GetDeclType().name}); + llvm::StringRef param = unique_param_names.Pop(); + ClassGenState::TypeUse type = + out_of_line ? state.GetOutOfLineParamType() : state.GetDeclType(); + sig.params.push_back({.name = param, .type = type.name}); + sig.param_consumers.push_back(type.consumer); + } + ClassGenState::TypeUse return_type = + out_of_line ? state.GetOutOfLineReturnType() : state.GetDeclType(); + sig.return_type = return_type.name; + sig.def_plan = return_type.index; + EmitFunctionDecl(name, is_private, is_method, sig.params, sig.return_type, + indent, os); + if (captured) { + *captured = std::move(sig); } - EmitFunctionDecl(name, is_private, is_method, params, - state.GetDeclType().name, indent, os); } // Emits `format` with `name` substituted for its `{0}`. @@ -1338,12 +1911,359 @@ static auto EmitTemplate(llvm::StringRef format, llvm::StringRef name, os << prefix << name << suffix; } +// A statement of an arranged definition. A statement that opens blocks opens +// them at `first_block` and, for a second block, the index after it. +struct ArrangedStmt { + PlanStmt plan; + int first_block = -1; +}; + +// A block of an arranged definition. +struct ArrangedBlock { + // Indices into `ArrangedDef::stmts`. + llvm::SmallVector stmts; + bool is_loop_block = false; +}; + +// A definition plan's statements, arranged in blocks. The first block is the +// definition's top-level block. +struct ArrangedDef { + llvm::SmallVector stmts; + llvm::SmallVector blocks; +}; + +// Randomly arranges the statements of `plan`, along with a `ReadParams` +// statement at depth 0. Each block gets at least one statement, and ends with a +// statement that isn't a local, so that the statement after each local can read +// it. Guard exits go in distinct loop blocks. +// +// The statements beyond the first in each block go in a block chosen with +// probability proportional to its statements so far, counting loop blocks +// `LoopBlockWeight` times. This gives a wider spread of block sizes than +// choosing uniformly, and larger loop blocks, as in real definitions. +static auto ArrangeDef(const DefPlan& plan, absl::BitGen& rng) -> ArrangedDef { + ArrangedDef def; + def.blocks.emplace_back(); + llvm::SmallVector level_blocks = {0}; + int num_depths = std::max(plan.levels.size(), 1); + for (int depth : llvm::seq(num_depths)) { + llvm::SmallVector exits; + llvm::SmallVector others; + llvm::SmallVector locals; + if (depth < static_cast(plan.levels.size())) { + for (PlanStmt stmt : plan.levels[depth]) { + switch (stmt.kind) { + case PlanKind::GuardExit: + exits.push_back(stmt); + break; + case PlanKind::Local: + locals.push_back(stmt); + break; + default: + others.push_back(stmt); + break; + } + } + } + if (depth == 0) { + others.push_back({.kind = PlanKind::ReadParams, .spelling_index = 0}); + } + std::shuffle(others.begin(), others.end(), rng); + + // The block of each statement placed at this depth. + llvm::SmallVector placed_blocks; + auto place = [&](int block, PlanStmt stmt) { + def.blocks[block].stmts.push_back(def.stmts.size()); + def.stmts.push_back({.plan = stmt}); + placed_blocks.push_back(block); + }; + llvm::SmallVector loop_blocks; + for (int block : level_blocks) { + if (def.blocks[block].is_loop_block) { + loop_blocks.push_back(block); + } + } + CARBON_CHECK(exits.size() <= loop_blocks.size()); + std::shuffle(loop_blocks.begin(), loop_blocks.end(), rng); + for (auto [block, exit] : llvm::zip(loop_blocks, exits)) { + place(block, exit); + } + for (int block : level_blocks) { + if (def.blocks[block].stmts.empty()) { + CARBON_CHECK(!others.empty(), "Not enough statements to end blocks."); + place(block, others.pop_back_val()); + } + } + for (int block : loop_blocks) { + placed_blocks.append(LoopBlockWeight - 1, block); + } + for (PlanStmt stmt : llvm::concat(others, locals)) { + int block = + placed_blocks[absl::Uniform(rng, 0, placed_blocks.size())]; + place(block, stmt); + if (def.blocks[block].is_loop_block) { + placed_blocks.append(LoopBlockWeight - 1, block); + } + } + + for (int block : level_blocks) { + llvm::SmallVector& stmts = def.blocks[block].stmts; + std::shuffle(stmts.begin(), stmts.end(), rng); + auto is_local = [&](int stmt) { + return def.stmts[stmt].plan.kind == PlanKind::Local; + }; + if (is_local(stmts.back())) { + llvm::SmallVector non_locals; + for (int i : llvm::seq(stmts.size())) { + if (!is_local(stmts[i])) { + non_locals.push_back(i); + } + } + std::swap( + stmts.back(), + stmts[non_locals[absl::Uniform(rng, 0, non_locals.size())]]); + } + } + + // Open the blocks for the next depth. + llvm::SmallVector next_blocks; + for (int block : level_blocks) { + for (int i : llvm::seq(def.blocks[block].stmts.size())) { + ArrangedStmt& stmt = def.stmts[def.blocks[block].stmts[i]]; + int num_blocks = NumPlanBlocks(stmt.plan.kind); + if (num_blocks == 0) { + continue; + } + stmt.first_block = def.blocks.size(); + for (auto _ : llvm::seq(num_blocks)) { + next_blocks.push_back(def.blocks.size()); + def.blocks.push_back( + {.is_loop_block = stmt.plan.kind == PlanKind::While}); + } + } + } + level_blocks = std::move(next_blocks); + } + CARBON_CHECK(level_blocks.empty()); + return def; +} + +// Emits the statements of `def` after the accumulator declaration that every +// function begins with. Locals take their names from `locals` in turn, the +// `ReadParams` statement adds `reads`, and guards return `return_value`. +// +// The first operand of each statement after a local is that local, so that +// every local is read. Every other operand, and the target of each update, is a +// random local in scope. +static auto EmitArrangedDef(const ArrangedDef& def, + llvm::ArrayRef locals, + llvm::StringRef reads, llvm::StringRef return_value, + bool is_cpp, absl::BitGen& rng, + llvm::raw_ostream& os) -> void { + llvm::SmallVector scope = {"acc"}; + llvm::StringRef pending = "acc"; + int next_local = 0; + auto pick_local = [&]() { + return scope[absl::Uniform(rng, 0, scope.size())]; + }; + auto emit_expr = [&](llvm::StringRef format) { + while (!format.empty()) { + if (format.starts_with("{0}") || format.starts_with("{1}")) { + os << (pending.empty() ? pick_local() : std::exchange(pending, {})); + format = format.drop_front(3); + } else { + os << format.front(); + format = format.drop_front(); + } + } + }; + auto emit_cond = [&](int spelling_index) { + emit_expr(PlanConds[spelling_index % std::size(PlanConds)]); + }; + auto indent = [&](int depth) { os.indent(2 * depth); }; + + // The blocks being emitted, with the index of the next statement in each, + // and the size of the scope outside it. + struct Frame { + int block; + int next_stmt; + int outer_scope_size; + }; + llvm::SmallVector stack = { + {.block = 0, .next_stmt = 0, .outer_scope_size = 1}}; + while (!stack.empty()) { + Frame& frame = stack.back(); + int depth = stack.size(); + const ArrangedBlock& block = def.blocks[frame.block]; + if (frame.next_stmt == static_cast(block.stmts.size())) { + // End the block, and start the second block of an `else` or `else if`. + scope.truncate(frame.outer_scope_size); + int ended = frame.block; + stack.pop_back(); + if (stack.empty()) { + break; + } + const Frame& owner_frame = stack.back(); + const ArrangedStmt& owner = + def.stmts[def.blocks[owner_frame.block] + .stmts[owner_frame.next_stmt - 1]]; + indent(depth - 1); + if (NumPlanBlocks(owner.plan.kind) == 1 || ended != owner.first_block) { + os << "}\n"; + continue; + } + if (owner.plan.kind == PlanKind::IfElse) { + os << "} else {\n"; + } else { + os << "} else if ("; + emit_cond(owner.plan.spelling_index + 1); + os << ") {\n"; + } + stack.push_back({.block = ended + 1, + .next_stmt = 0, + .outer_scope_size = static_cast(scope.size())}); + continue; + } + + const ArrangedStmt& stmt = def.stmts[block.stmts[frame.next_stmt]]; + ++frame.next_stmt; + PlanStmt planned = stmt.plan; + indent(depth); + switch (planned.kind) { + case PlanKind::Local: { + llvm::StringRef name = locals[next_local++]; + os << (is_cpp ? "int " : "var ") << name + << (is_cpp ? " = " : ": i32 = "); + emit_expr(PlanExprs[planned.spelling_index]); + os << ";\n"; + scope.push_back(name); + pending = name; + break; + } + case PlanKind::Update: + os << pick_local() << " = "; + emit_expr(PlanExprs[planned.spelling_index]); + os << ";\n"; + break; + case PlanKind::ReadParams: + os << pick_local() << " = "; + emit_expr("{0}"); + os << " + " << reads << ";\n"; + break; + case PlanKind::If: + case PlanKind::IfElse: + case PlanKind::ElseIf: + case PlanKind::While: + os << (planned.kind == PlanKind::While ? "while (" : "if ("); + emit_cond(planned.spelling_index); + os << ") {\n"; + stack.push_back({.block = stmt.first_block, + .next_stmt = 0, + .outer_scope_size = static_cast(scope.size())}); + break; + case PlanKind::GuardReturn: + case PlanKind::GuardExit: + os << "if ("; + emit_cond(planned.spelling_index); + os << ") {\n"; + indent(depth + 1); + if (planned.kind == PlanKind::GuardReturn) { + os << "return " << return_value << ";\n"; + } else { + os << (planned.spelling_index % 2 == 0 ? "break;\n" : "continue;\n"); + } + indent(depth); + os << "}\n"; + break; + } + } +} + +// Generates an out-of-line definition for the declaration `sig`, and writes it +// to the provided stream. +// +// The definition declares an `i32` accumulator, `acc`, and then has its plan's +// statements arranged randomly, along with a statement at depth 0 that reads +// every parameter with its consumer template, and `self` in a method with +// `Checksum`. The signature and that statement are each on one line however +// long they are, which the line estimates assume. +auto SourceGen::GenerateOutOfLineDef(ClassGenState& state, + llvm::StringRef class_name, + const FunctionSig& sig, + llvm::raw_ostream& os) -> void { + os << "// TODO: make better comment text\n"; + if (!IsCpp()) { + os << "fn " << class_name << "." << sig.name; + } else { + os << "auto " << class_name << "::" << sig.name; + } + + os << "("; + // For Carbon methods, `self` is the first parameter, as in the declaration. + bool is_carbon_method = sig.is_method && !IsCpp(); + if (is_carbon_method) { + os << "self"; + } + bool first_param = !is_carbon_method; + for (const TypedName& param : sig.params) { + if (!first_param) { + os << ", "; + } + first_param = false; + if (!IsCpp()) { + os << param.name << ": " << param.type; + } else { + os << param.type << " " << param.name; + } + } + os << ") -> " << sig.return_type << " {\n"; + os << (IsCpp() ? " int acc = 0;\n" : " var acc: i32 = 0;\n"); + + RawStringOstream reads; + llvm::ListSeparator read_sep(" + "); + if (sig.is_method) { + reads << read_sep << (IsCpp() ? "Checksum()" : "self.Checksum()"); + } + for (auto [param, consumer] : llvm::zip(sig.params, sig.param_consumers)) { + reads << read_sep; + EmitTemplate(consumer, param.name, reads); + } + + // Locals and parameters draw from the same identifiers of each length, so + // exclude this function's parameter names: C++ rejects a local that + // has the same name as a parameter. + const DefPlan& plan = state.def_plans()[sig.def_plan]; + Set param_names; + for (const TypedName& param : sig.params) { + param_names.Insert(param.name); + } + UniqueIdentifierPopper unique_local_names(*this, state.local_names(), + ¶m_names); + llvm::SmallVector locals; + locals.reserve(plan.locals); + for (auto _ : llvm::seq(plan.locals)) { + locals.push_back(unique_local_names.Pop()); + } + + RawStringOstream return_value; + state.ProduceValue(sig.return_type, return_value); + EmitArrangedDef(ArrangeDef(plan, rng_), locals, reads.TakeStr(), + return_value.TakeStr(), IsCpp(), rng_, os); + os << " return "; + state.ProduceValue(sig.return_type, os); + os << ";\n}\n"; +} + // Generates an inline function definition and writes it to the provided // stream. // // The body adds every parameter to an `i32` accumulator, declares a chain of // `i32` locals, and returns a value of the return type. Reading every parameter // and local keeps the code free of unused-binding warnings. +// +// TODO: Build these definitions from plans, as out-of-line definitions do, so +// that one builder makes every function definition except the fixed shapes of +// getters, predicates, and forwarders. auto SourceGen::GenerateInlineFunctionDef(ClassGenState& state, llvm::StringRef name, int param_count, int local_count, @@ -1384,7 +2304,8 @@ auto SourceGen::GenerateInlineFunctionDef(ClassGenState& state, // Each local after the first reads the previous one. Locals and parameters // draw from the same identifiers of each length, so exclude this function's - // parameter names: C++ rejects a local that redeclares a parameter. + // parameter names: C++ rejects a local that has the same name as a + // parameter. llvm::SmallVector locals; locals.reserve(local_count); UniqueIdentifierPopper unique_local_names(*this, state.local_names(), @@ -1514,10 +2435,11 @@ auto SourceGen::GenerateChecksumFunction(llvm::raw_ostream& os) -> void { // Generate a class definition and write it to the provided stream. // // The structure of the definition is guided by the `params` provided, and it -// consumes the provided state. -auto SourceGen::GenerateClassDef(const ClassParams& params, - ClassGenState& state, llvm::raw_ostream& os) - -> void { +// consumes the provided state. With out-of-line definitions, it appends the +// declarations to define to `out_of_line_defs`. +auto SourceGen::GenerateClassDef( + const ClassParams& params, ClassGenState& state, llvm::raw_ostream& os, + llvm::SmallVectorImpl& out_of_line_defs) -> void { llvm::StringRef name = state.class_names().pop_back_val(); os << "// TODO: make better comment text\n"; os << "class " << name << " {\n"; @@ -1567,13 +2489,22 @@ auto SourceGen::GenerateClassDef(const ClassParams& params, UniqueIdentifierPopper unique_inline_names(*this, state.inline_function_names()); + // Capture each declaration's signature for its out-of-line definition. + bool define_out_of_line = state.define_decls_out_of_line(); + auto capture_sig = [&]() -> FunctionSig* { + if (!define_out_of_line) { + return nullptr; + } + return &out_of_line_defs.emplace_back(OutOfLineDef{.class_name = name}).sig; + }; + llvm::ListSeparator line_sep("\n"); for (auto _ : llvm::seq(params.public_function_decls)) { os << line_sep; GenerateFunctionDecl(state, unique_member_names.Pop(), /*is_private=*/false, /*is_method=*/false, state.public_function_param_counts().pop_back_val(), - /*indent=*/" ", os); + /*indent=*/" ", os, capture_sig()); } for (auto _ : llvm::seq(params.inline_function_defs)) { os << line_sep; @@ -1587,7 +2518,7 @@ auto SourceGen::GenerateClassDef(const ClassParams& params, GenerateFunctionDecl(state, unique_member_names.Pop(), /*is_private=*/false, /*is_method=*/true, state.public_method_param_counts().pop_back_val(), - /*indent=*/" ", os); + /*indent=*/" ", os, capture_sig()); } for (TypedName field : getter_fields) { os << line_sep; @@ -1637,14 +2568,14 @@ auto SourceGen::GenerateClassDef(const ClassParams& params, GenerateFunctionDecl(state, unique_member_names.Pop(), /*is_private=*/true, /*is_method=*/false, state.private_function_param_counts().pop_back_val(), - /*indent=*/" ", os); + /*indent=*/" ", os, capture_sig()); } for (auto _ : llvm::seq(params.private_method_decls)) { os << line_sep; GenerateFunctionDecl(state, unique_member_names.Pop(), /*is_private=*/true, /*is_method=*/true, state.private_method_param_counts().pop_back_val(), - /*indent=*/" ", os); + /*indent=*/" ", os, capture_sig()); } for (const Forwarder& forwarder : forwarders) { os << line_sep; @@ -1669,16 +2600,16 @@ auto SourceGen::GenerateClassDef(const ClassParams& params, fields.push_back(field); } - // With bodies, C++ puts `Make` and `Checksum` in a second public section, - // followed by a private section for the fields. - bool has_bodies = state.has_bodies(); - if (IsCpp() && has_bodies) { + // With definitions, C++ puts `Make` and `Checksum` in a second public + // section, followed by a private section for the fields. + bool has_defs = state.has_defs(); + if (IsCpp() && has_defs) { os << "\n public:\n"; line_sep = llvm::ListSeparator("\n"); } - // Only bodies call `Make` and `Checksum`. - if (has_bodies) { + // Only definitions call `Make` and `Checksum`. + if (has_defs) { os << line_sep; GenerateMakeFunction(state, name, fields, os); os << line_sep; @@ -1691,7 +2622,7 @@ auto SourceGen::GenerateClassDef(const ClassParams& params, os << line_sep; // `tag` comes first, matching its position in `Make`. - if (has_bodies) { + if (has_defs) { os << (IsCpp() ? " int tag;\n" : " private var tag: i32;\n"); } for (const TypedName& field : fields) { diff --git a/toolchain/benchmarking/source_gen.h b/toolchain/benchmarking/source_gen.h index 8bfeb3f7b8a5..625c2ef99a36 100644 --- a/toolchain/benchmarking/source_gen.h +++ b/toolchain/benchmarking/source_gen.h @@ -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 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 params; + llvm::SmallVector 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 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& out_of_line_defs) + -> void; absl::BitGen rng_; llvm::BumpPtrAllocator storage_; diff --git a/toolchain/benchmarking/source_gen_test.cpp b/toolchain/benchmarking/source_gen_test.cpp index d865c607a93f..07f2b193b83a 100644 --- a/toolchain/benchmarking/source_gen_test.cpp +++ b/toolchain/benchmarking/source_gen_test.cpp @@ -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 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; + } } } }