diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index 270895e9a5b6..c22ade5185d0 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -16213,6 +16213,7 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, struct util_dynarray *binary, struct agx_shader_info *out, unsigned *offset_out, unsigned ra_budget_cut, bool agx3_reg_float_consts, + bool disable_sampled_cap, bool opt_select_shifted_half, bool *did_select_shifted_half) { @@ -16237,6 +16238,7 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, agx_context *ctx = rzalloc(NULL, agx_context); ctx->nir = nir; ctx->ra_budget_cut = ra_budget_cut; + ctx->disable_sampled_cap = disable_sampled_cap; ctx->is_preamble = impl->function->is_preamble; ctx->agx3_reg_float_consts = agx3_reg_float_consts; if (ctx->is_preamble) @@ -16599,6 +16601,20 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, agx_validate(ctx, "agx_ra"); if (ctx->ra_failed) { + /* If the optional sampled-compute occupancy cap tightened the file, + * drop it first and retry from the whole register file before giving + * up (including on RA_MEM exhaustion) or cutting the GPR budget. */ + if (ctx->sampled_cap_applied) { + assert(!disable_sampled_cap && !ra_budget_cut); + ralloc_free(ctx); + binary->size = initial_binary_size; + *out = initial_out; + return agx_compile_function_nir( + nir, impl, key, binary, out, offset_out, 0, + agx3_reg_float_consts, true, opt_select_shifted_half, + did_select_shifted_half); + } + /* Spilling only targets total demand; pinned values can still leave the * shuffle no room. Recompile with an ever smaller spill budget unless * RA_MEM itself was exhausted, where cutting the GPR budget only forces @@ -16612,7 +16628,8 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, return agx_compile_function_nir( nir, impl, key, binary, out, offset_out, ra_budget_cut ? ra_budget_cut * 2 : 16, agx3_reg_float_consts, - opt_select_shifted_half, did_select_shifted_half); + disable_sampled_cap, opt_select_shifted_half, + did_select_shifted_half); } agx_set_refusal(ctx, "register allocation found no legal placement", __LINE__); @@ -16620,6 +16637,21 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, return false; } + /* The sampled-compute cap trades moderate static TPS spills for extra + * resident threads. If it caused a spill storm (too large a spill frame, + * too many scalar spills/fills, or loop-weighted spill traffic outpacing + * texture reads), drop the optional cap and retry from the whole file. */ + if (ctx->sampled_cap_applied && agx_sampled_cap_spills_excessive(ctx)) { + assert(!disable_sampled_cap && !ra_budget_cut); + ralloc_free(ctx); + binary->size = initial_binary_size; + *out = initial_out; + return agx_compile_function_nir( + nir, impl, key, binary, out, offset_out, 0, + agx3_reg_float_consts, true, opt_select_shifted_half, + did_select_shifted_half); + } + /* Apple's G17P compiler publishes a 16-byte scratch footprint for compute, * vertex and fragment shaders that consume a device atomic's return. * The otherwise equivalent return-unused shaders publish zero, and the @@ -16707,6 +16739,16 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, : AGX3_G17P_MAX_SPILL_B; if (frame_B > limit_B) { + if (ctx->sampled_cap_applied) { + assert(!disable_sampled_cap && !ra_budget_cut); + ralloc_free(ctx); + binary->size = initial_binary_size; + *out = initial_out; + return agx_compile_function_nir( + nir, impl, key, binary, out, offset_out, 0, + agx3_reg_float_consts, true, opt_select_shifted_half, + did_select_shifted_half); + } agx_set_refusal(ctx, "AGX3 scratch frame exceeds target limit", __LINE__); binary->size = initial_binary_size; @@ -21362,7 +21404,7 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, bool folded_shifted_half = false; bool compiled = agx_compile_function_nir(nir, impl, key, &binary, &out->info, &offset, 0, false, - opt_select_shifted_half, + false, opt_select_shifted_half, &folded_shifted_half); /* Outside AGX3B the shifted-half fold commits without a speculative pack @@ -21377,7 +21419,7 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, binary.size = saved_size; compiled = agx_compile_function_nir(nir, impl, key, &binary, &out->info, &offset, 0, false, - false, NULL); + false, false, NULL); } /* The G17G packer refuses shapes it has no grounded encoding for and @@ -21393,7 +21435,7 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, folded_shifted_half = false; compiled = agx_compile_function_nir(nir, impl, key, &binary, &out->info, &offset, 0, true, - opt_select_shifted_half, + false, opt_select_shifted_half, &folded_shifted_half); if (!compiled && folded_shifted_half) { if (agx_compiler_debug & AGX_DBG_SHADERS) @@ -21405,7 +21447,7 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, binary.size = saved_size; compiled = agx_compile_function_nir(nir, impl, key, &binary, &out->info, &offset, 0, true, - false, NULL); + false, false, NULL); } } diff --git a/src/asahi/compiler/agx_compile.h b/src/asahi/compiler/agx_compile.h index 2a7457b12822..8dc992a275d8 100644 --- a/src/asahi/compiler/agx_compile.h +++ b/src/asahi/compiler/agx_compile.h @@ -585,6 +585,13 @@ struct agx_shader_key { * AGX3 and AGX2_MAX_SPILL_SLOTS (4 KiB) of spill slots on AGX2. */ uint32_t max_scratch_B; + /* Whether the program's launch also takes the scratch of optional spills, + * such as those of the sampled compute register cap + * (agx_sampled_compute_register_cap()). Some launch paths refuse scratch, + * or bound its size, even where has_scratch is set. + */ + bool optional_spills; + /* Whether we're compiling the helper program used for scratch allocation. * This has special register allocation requirements. */ @@ -879,6 +886,14 @@ struct agx_occupancy { struct agx_occupancy agx_occupancy_for_register_count(unsigned halfregs); unsigned agx_max_registers_for_occupancy(unsigned occupancy); +/* General half-registers one thread can allocate on this device, or 0 when + * the encoding's register file is not known. */ +unsigned agx_register_file_halves(const struct agx_device_key *dev); + +/* Register budget for compute programs with several texture reads, derived + * from the register file and the occupancy steps; 0 means no cap. */ +unsigned agx_sampled_compute_register_cap(const struct agx_device_key *dev); + /* Vertex attributes a vertex prolog can hand to the main shader on this * device through the register ABI (AGX_ABI_VIN_ATTRIB): component i of the * compacted attribute slots occupies half-registers 2 * (8 + i) and the one diff --git a/src/asahi/compiler/agx_compiler.h b/src/asahi/compiler/agx_compiler.h index ce7caef155da..2f719bc48990 100644 --- a/src/asahi/compiler/agx_compiler.h +++ b/src/asahi/compiler/agx_compiler.h @@ -826,6 +826,12 @@ typedef struct { * Retrying with a smaller GPR budget cannot help and only increases spill * pressure. */ bool ra_mem_exhausted; + /* Disable the optional sampled-compute occupancy cap on a retry after a + * capped allocation failed (including on RA_MEM exhaustion). */ + bool disable_sampled_cap; + /* Set by agx_ra_impl() when agx_sampled_compute_register_cap() actually + * lowered max_possible_regs on this attempt. */ + bool sampled_cap_applied; /* Halves taken off the spill budget after a failed allocation, so the * live-range shuffle gets free room (agx_compile_function_nir retries). */ unsigned ra_budget_cut; @@ -1449,6 +1455,7 @@ bool agx_fold_agx3_spill_constant_phis(agx_context *ctx); void agx_repair_ssa(agx_context *ctx); void agx_reindex_ssa(agx_context *ctx); void agx_ra(agx_context *ctx); +bool agx_sampled_cap_spills_excessive(const agx_context *ctx); bool agx_ra_find_regs_simple(const BITSET_WORD *used, unsigned count, unsigned align, unsigned minimum, unsigned limit, unsigned *out); diff --git a/src/asahi/compiler/agx_performance.c b/src/asahi/compiler/agx_performance.c index 1c2e844ab809..9bc0961fa50e 100644 --- a/src/asahi/compiler/agx_performance.c +++ b/src/asahi/compiler/agx_performance.c @@ -48,6 +48,96 @@ agx_max_registers_for_occupancy(unsigned occupancy) return max_regs; } +unsigned +agx_register_file_halves(const struct agx_device_key *dev) +{ + switch (dev->encoding) { + case AGX_ISA_ENCODING_AGX2: + return AGX_NUM_REGS; + case AGX_ISA_ENCODING_AGX3B: + return AGX3B_NUM_REGS; + case AGX_ISA_ENCODING_AGX3C: + /* G18G compiles as AGX3C with emit_agx3d; both files end at r125. */ + return dev->emit_agx3d ? AGX3D_NUM_REGS : AGX3C_NUM_REGS; + case AGX_ISA_ENCODING_AGX3D: + return AGX3D_NUM_REGS; + default: + return 0; + } +} + +/* Encodings whose register spills lower to launch-allocated static + * thread-private storage (copy/rld with hardware scoreboarding) rather than + * AGX2's helper-backed device-memory stack with explicit 2-slot scoreboard + * waits. Optional occupancy-driven spilling only pays on static TPS: measured + * on G13G (AGX2), capping sampled compute to 160 halves adds ~55x higher + * per-core spill cost than on G17C (AGX3C), slowing ALU-heavy sampled compute + * by +16% to +259% while yielding no meaningful gain on texture-bound shaders + * (-0.9% to +2.4%, vs -7.0% to -14.5% on G17C for the same shaders). + */ +static bool +agx_isa_has_static_tps(enum agx_isa_encoding encoding) +{ + return encoding == AGX_ISA_ENCODING_AGX3B || + encoding == AGX_ISA_ENCODING_AGX3C || + encoding == AGX_ISA_ENCODING_AGX3D; +} + +/* + * A compute program that issues several texture reads spends much of its + * time waiting on them, and more resident threads hide that wait. Capping its + * registers trades scratch spills for those threads. The cap follows from + * three properties of the device: + * + * - launch-allocated static thread-private storage (agx_isa_has_static_tps()), + * - the occupancy steps (occupancies[] above): how many threads a core keeps + * resident at each per-thread register budget, and + * - the per-thread register file (agx_register_file_halves()). + * + * The target is 5/8 of the most threads a core keeps resident (the first + * step): 640 of 1024 threads, 20 of 32 SIMD groups. The cap is the largest + * budget that still reaches that step, 160 halves with the current steps. + * Tuned on G17C against the uncapped file and a 192-half cap. + * A device gets no cap when its ISA lacks static TPS (AGX2), when the cap + * would not raise its resident threads by at least 1.5x over what its whole + * file allows, or when its register file is unknown + * (agx_register_file_halves() returns 0). + * + * AGX3C and AGX3D currently resolve to 160: both use static TPS and their + * 252-half files reach 384 threads uncapped, so the cap raises that to 640. + * AGX3B (192 halves) already reaches 512, too small a step, so it gets no + * cap. AGX2 uses helper-backed device-memory stack spills with explicit waits + * and gets no cap. Launches that take no scratch (such as M5 without compute + * resources) leave optional_spills false instead of overriding the derivation + * here. All encodings share one occupancy table; a part whose steps differ + * needs its own table before this derivation is right for it. + */ +unsigned +agx_sampled_compute_register_cap(const struct agx_device_key *dev) +{ + if (!agx_isa_has_static_tps(dev->encoding)) + return 0; + + const unsigned file = agx_register_file_halves(dev); + if (!file) + return 0; + + const unsigned target = occupancies[0].max_threads * 5 / 8; + const unsigned cap = agx_max_registers_for_occupancy(target); + + /* The spills only pay for a large step in resident threads: half again + * as many or more. 384 -> 640 threads gained on G17C; 512 -> 640 lost + * 7-10% on G16G with the same sample workload. + */ + const unsigned capped = agx_occupancy_for_register_count(cap).max_threads; + const unsigned uncapped = + agx_occupancy_for_register_count(file).max_threads; + if (cap >= file || capped * 2 < uncapped * 3) + return 0; + + return cap; +} + /* Crude cycle model for G13G */ enum alu_unit { NONE, diff --git a/src/asahi/compiler/agx_register_allocate.c b/src/asahi/compiler/agx_register_allocate.c index 1b65145fb249..1e5e934ab91e 100644 --- a/src/asahi/compiler/agx_register_allocate.c +++ b/src/asahi/compiler/agx_register_allocate.c @@ -4061,6 +4061,31 @@ agx_ra(agx_context *ctx) max_possible_regs = MIN2(max_possible_regs, AGX_M5_RT_REGISTER_BUDGET); } + /* Keep more threads resident in ordinary compute programs with several + * texture reads (agx_sampled_compute_register_cap() derives the budget). + * Helpers and unspillable programs keep their hardware budget. The cap + * only trades spills for occupancy, so a retry after a failed allocation + * (including RA_MEM exhaustion) drops it and compiles from the whole + * file rather than refusing a program that fits there. + */ + const unsigned sampled_cap = + agx_sampled_compute_register_cap(&ctx->key->dev); + if (sampled_cap && !ctx->ra_budget_cut && !ctx->disable_sampled_cap && + ctx->stage == MESA_SHADER_COMPUTE && !ctx->is_preamble && + !ctx->key->is_helper && ctx->key->has_scratch && + ctx->key->optional_spills && + !(ctx->out && ctx->out->uses_ray_traversal)) { + unsigned samples = 0; + agx_foreach_instr_global(ctx, I) { + if (I->op == AGX_OPCODE_TEXTURE_SAMPLE || I->op == AGX_OPCODE_TEXTURE_LOAD) + samples++; + } + if (samples >= 4 && sampled_cap < max_possible_regs) { + max_possible_regs = sampled_cap; + ctx->sampled_cap_applied = true; + } + } + if (force_spilling) { /* Even when testing spilling, we need enough room for preloaded/exported * regs. @@ -5197,3 +5222,110 @@ agx_ra(agx_context *ctx) free(classes); free(visited); } + +/* Optional occupancy-cap spill cost guard. + * + * Capping a sampled compute shader to 160 halves only pays when the extra + * resident threads hide texture-fetch latency faster than the added static TPS + * spills cost. Measured on G17C (AGX3C): + * - Texture-bound shaders with <= 33 scalar spills/fills and <= 128 B spill + * frames gain -7.0% to -14.5% (and Cyberpunk 2077 T2 hot shaders at 29/33 + * spills gain frame rate). + * - Heavy-spill texture shaders (54–78 spills, 216–312 B) flatten to 0%. + * - ALU-heavy shaders with few texture reads (8 fetches, 82–290 spills) + * regress +8.7% to +47.9% even on G17C. + * + * Reject the optional cap (falling back to the whole register file) when the + * RA spill footprint or scalar spill/fill count exceeds a bounded budget, or + * when loop-weighted spill/fill traffic outpaces loop-weighted texture ops. + */ +#define AGX_SAMPLED_CAP_MAX_SPILL_B 192u +#define AGX_SAMPLED_CAP_MAX_SCALAR_SPILLS 48u +#define AGX_SAMPLED_CAP_MAX_SCALAR_FILLS 48u +#define AGX_SAMPLED_CAP_MAX_OPS_PER_SAMPLE 8u + +bool +agx_sampled_cap_spills_excessive(const agx_context *ctx) +{ + assert(ctx->scratch_size_B >= ctx->spill_base_B); + const unsigned spill_bytes = ctx->scratch_size_B - ctx->spill_base_B; + if (!spill_bytes) + return false; + + if (spill_bytes > AGX_SAMPLED_CAP_MAX_SPILL_B) + return true; + + unsigned nr_blocks = 0; + agx_foreach_block(ctx, block) + nr_blocks = MAX2(nr_blocks, block->index + 1); + + uint8_t *loop_depth = nr_blocks ? calloc(nr_blocks, sizeof(*loop_depth)) + : NULL; + if (loop_depth) { + /* In structured AGX control flow each loop spans [header, last backedge]. + * Iterate per loop header so multiple continue backedges to the same + * header count as a single loop nesting level. */ + agx_foreach_block(ctx, header) { + if (!header->loop_header) + continue; + unsigned last = header->index; + bool has_backedge = false; + agx_foreach_predecessor(header, pred) { + if ((*pred)->index >= header->index) { + last = MAX2(last, (*pred)->index); + has_backedge = true; + } + } + if (!has_backedge) + continue; + for (unsigned i = header->index; i <= last && i < nr_blocks; ++i) { + if (loop_depth[i] < 4) + loop_depth[i]++; + } + } + } + + unsigned scalar_spills = 0; + unsigned scalar_fills = 0; + uint64_t weighted_spill_ops = 0; + uint64_t weighted_samples = 0; + + agx_foreach_block(ctx, block) { + const unsigned depth = + (loop_depth && block->index < nr_blocks) ? loop_depth[block->index] : 0; + const uint64_t weight = UINT64_C(1) << (3u * depth); + + agx_foreach_instr_in_block(block, I) { + if (I->op == AGX_OPCODE_TEXTURE_SAMPLE || + I->op == AGX_OPCODE_TEXTURE_LOAD) { + weighted_samples += weight; + } else if (I->op == AGX_OPCODE_STACK_STORE || + I->op == AGX_OPCODE_STACK_LOAD) { + const bool is_store = I->op == AGX_OPCODE_STACK_STORE; + const agx_index off = I->src[is_store ? 1 : 0]; + if (off.type != AGX_INDEX_IMMEDIATE || + off.value < ctx->spill_base_B) + continue; + + const unsigned comps = util_bitcount(I->mask); + if (is_store) + scalar_spills += comps; + else + scalar_fills += comps; + weighted_spill_ops += (uint64_t)comps * weight; + } + } + } + + free(loop_depth); + + if (scalar_spills > AGX_SAMPLED_CAP_MAX_SCALAR_SPILLS || + scalar_fills > AGX_SAMPLED_CAP_MAX_SCALAR_FILLS) + return true; + + if (weighted_spill_ops > + weighted_samples * AGX_SAMPLED_CAP_MAX_OPS_PER_SAMPLE) + return true; + + return false; +} diff --git a/src/asahi/compiler/meson.build b/src/asahi/compiler/meson.build index 5baff9178ee2..ddcf94e0e54b 100644 --- a/src/asahi/compiler/meson.build +++ b/src/asahi/compiler/meson.build @@ -824,6 +824,7 @@ if with_tests 'test/test-ra-early-kill.cpp', 'test/test-ra-uniform-phi.cpp', 'test/test-rt-register-pressure.cpp', + 'test/test-sampled-compute-register-cap.cpp', 'test/test-uniform-remat.cpp', 'test/test-lower-pseudo.cpp', 'test/test-lower-parallel-copy.cpp', diff --git a/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp b/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp new file mode 100644 index 000000000000..8e7b8234fbe5 --- /dev/null +++ b/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp @@ -0,0 +1,550 @@ +/* Copyright 2026 Aurora Silicon + * SPDX-License-Identifier: MIT + */ +#include +#include "agx_builder.h" +#include "agx_test.h" +extern "C" { +#include "compiler/nir/nir_builder.h" +#include "agx_debug.h" +#include "agx_nir.h" +} + +static unsigned +cap_for(enum agx_isa_encoding encoding, bool emit_agx3d = false) +{ + agx_device_key dev = {}; + dev.encoding = encoding; + dev.emit_agx3d = emit_agx3d; + return agx_sampled_compute_register_cap(&dev); +} + +/* The cap follows from static TPS support, the register file, and the + * occupancy steps, not from the chip it was tuned on. */ +TEST(SampledComputeRegisterCap, DerivedFromFileAndOccupancy) +{ + /* G17C (AGX3C): static TPS + 252-half file -> 160 halves (384 -> 640). */ + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3C), 160u); + EXPECT_EQ(agx_occupancy_for_register_count(160).max_threads, 640u); + agx_device_key g17c = {}; + g17c.encoding = AGX_ISA_ENCODING_AGX3C; + g17c.chip = AGX_CHIP_G17C; + EXPECT_EQ(agx_register_file_halves(&g17c), 252u); + EXPECT_EQ(agx_occupancy_for_register_count(252).max_threads, 384u); + + /* AGX2 uses helper-backed device-memory stack spills with explicit 2-slot + * scoreboard waits rather than static TPS: no optional spill cap. */ + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX2), 0u); + /* AGX3B reaches 512 threads uncapped: too small a step for the spills. */ + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3B), 0u); + + /* AGX3D also has static TPS and a 252-half file; launches without + * optional_spills keep the cap off. */ + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3C, true), 160u); + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3D), 160u); + + /* No register file, no cap. */ + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_UNKNOWN), 0u); +} + +/* A compute program with configurable live halves and texture reads: + * with >= 4 texture reads, the first allocation spills to fit the cap; the + * retry after a failed allocation (ra_budget_cut / disable_sampled_cap) or a + * launch without optional_spills works from the whole file. */ +static void +build_sampled_compute_air(void *mem, agx_builder **b_out, agx_shader_key *key, + enum agx_isa_encoding encoding, enum agx_chip chip, + bool emit_agx3d, unsigned ra_budget_cut, + bool disable_sampled_cap, bool optional_spills, + unsigned tex_loads, unsigned live_vals) +{ + agx_builder *b = agx_test_builder(mem); + *key = {}; + key->dev.encoding = encoding; + key->dev.chip = chip; + key->dev.emit_agx3d = emit_agx3d; + key->has_scratch = true; + key->optional_spills = optional_spills; + b->shader->key = key; + b->shader->out = rzalloc(mem, struct agx_shader_info); + b->shader->stage = MESA_SHADER_COMPUTE; + b->shader->nir = rzalloc(mem, nir_shader); + b->shader->nir->info.stage = MESA_SHADER_COMPUTE; + b->shader->nir->info.workgroup_size[0] = 32; + b->shader->nir->info.workgroup_size[1] = 1; + b->shader->nir->info.workgroup_size[2] = 1; + b->shader->ra_budget_cut = ra_budget_cut; + b->shader->disable_sampled_cap = disable_sampled_cap; + + agx_index texels[4] = {}; + for (unsigned i = 0; i < tex_loads; ++i) { + texels[i] = agx_vec_temp(b->shader, AGX_SIZE_32, 4); + agx_index x = agx_mov(b, agx_uniform(8 + 4 * i, AGX_SIZE_32)); + agx_index y = agx_mov(b, agx_uniform(10 + 4 * i, AGX_SIZE_32)); + agx_index coords = agx_vec_temp(b->shader, AGX_SIZE_32, 2); + agx_instr *collect = agx_collect_to(b, coords, 2); + collect->src[0] = x; + collect->src[1] = y; + agx_texture_load_to(b, texels[i], coords, agx_immediate(0), + agx_immediate(0), agx_immediate(0), agx_immediate(0), + agx_null(), AGX_DIM_2D, AGX_LOD_MODE_LOD_MIN, 0xf, + false, false); + } + + agx_index prev = agx_uniform(160, AGX_SIZE_32); + agx_index *values = ralloc_array(mem, agx_index, live_vals); + /* Each value depends on the previous one, so none rematerializes. */ + for (unsigned i = 0; i < live_vals; ++i) { + values[i] = agx_fadd(b, prev, + agx_uniform(32 + 2 * (i % 64), AGX_SIZE_32)); + prev = values[i]; + } + for (unsigned i = 0; i < live_vals; ++i) + agx_unit_test(b, values[i]); + for (unsigned i = 0; i < tex_loads; ++i) { + agx_instr *split = agx_split(b, 4, texels[i]); + agx_foreach_dest(split, d) { + split->dest[d] = agx_temp(b->shader, AGX_SIZE_32); + agx_unit_test(b, split->dest[d]); + } + } + + *b_out = b; +} + +static void +allocate_sampled_compute(enum agx_isa_encoding encoding, enum agx_chip chip, + unsigned ra_budget_cut, unsigned *max_reg, + unsigned *scratch_B, bool optional_spills = true, + unsigned tex_loads = 4, bool emit_agx3d = false) +{ + void *mem = ralloc_context(NULL); + agx_builder *b = NULL; + agx_shader_key key = {}; + build_sampled_compute_air(mem, &b, &key, encoding, chip, emit_agx3d, + ra_budget_cut, false, optional_spills, tex_loads, + 84); + + agx_ra(b->shader); + ASSERT_FALSE(b->shader->ra_failed); + *max_reg = b->shader->max_reg; + *scratch_B = b->shader->scratch_size_B; + ralloc_free(mem); +} + +TEST(SampledComputeRegisterCap, RetryAfterFailedAllocationUsesWholeFile) +{ + unsigned max_reg, scratch_B; + + ASSERT_NO_FATAL_FAILURE(allocate_sampled_compute( + AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C, 0, &max_reg, &scratch_B)); + EXPECT_LT(max_reg, 160u); + EXPECT_GT(scratch_B, 0u); + + ASSERT_NO_FATAL_FAILURE(allocate_sampled_compute( + AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C, 16, &max_reg, &scratch_B)); + EXPECT_GE(max_reg, 160u); + EXPECT_EQ(scratch_B, 0u); +} + +/* Encodings without launch-allocated static TPS (AGX2) stay uncapped even when + * optional_spills is true and >= 4 texture loads are present. */ +TEST(SampledComputeRegisterCap, NoCapOnAGX2WithoutStaticTPS) +{ + const enum agx_chip chips[] = {AGX_CHIP_G13G, AGX_CHIP_G14G}; + for (enum agx_chip chip : chips) { + SCOPED_TRACE(chip); + void *mem = ralloc_context(NULL); + agx_builder *b = NULL; + agx_shader_key key = {}; + build_sampled_compute_air(mem, &b, &key, AGX_ISA_ENCODING_AGX2, chip, + false, 0, false, true, 4, 84); + agx_ra(b->shader); + ASSERT_FALSE(b->shader->ra_failed); + EXPECT_FALSE(b->shader->sampled_cap_applied); + EXPECT_GE(b->shader->max_reg, 160u); + EXPECT_EQ(b->shader->scratch_size_B, 0u); + ralloc_free(mem); + } +} + +/* A launch that cannot take the cap's spills keeps the whole file. */ +TEST(SampledComputeRegisterCap, NoCapWithoutOptionalSpills) +{ + struct { + enum agx_isa_encoding encoding; + enum agx_chip chip; + bool emit_agx3d; + } targets[] = { + {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C, false}, + {AGX_ISA_ENCODING_AGX2, AGX_CHIP_G14G, false}, + {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G18G, true}, + }; + + for (const auto &t : targets) { + SCOPED_TRACE(t.chip); + unsigned max_reg, scratch_B; + + ASSERT_NO_FATAL_FAILURE(allocate_sampled_compute( + t.encoding, t.chip, 0, &max_reg, &scratch_B, false, 4, t.emit_agx3d)); + EXPECT_GE(max_reg, 160u); + EXPECT_EQ(scratch_B, 0u); + } +} + +/* Compute programs below four texture reads (0 and 3) keep the whole file. */ +TEST(SampledComputeRegisterCap, NoCapBelowTextureThreshold) +{ + for (unsigned tex_loads : {0u, 3u}) { + SCOPED_TRACE(tex_loads); + unsigned max_reg, scratch_B; + + ASSERT_NO_FATAL_FAILURE(allocate_sampled_compute( + AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C, 0, &max_reg, &scratch_B, true, + tex_loads)); + EXPECT_GE(max_reg, 160u); + EXPECT_EQ(scratch_B, 0u); + } +} + +static bool +lower_test_descriptor_set(nir_builder *b, nir_intrinsic_instr *intr, void *) +{ + if (intr->intrinsic != nir_intrinsic_load_descriptor_set_agx) + return false; + + b->cursor = nir_before_instr(&intr->instr); + nir_def_replace( + &intr->def, + nir_load_preamble(b, 1, 64, .base = (int)(4 * nir_intrinsic_desc_set(intr)))); + return true; +} + +static nir_shader * +build_agx3c_sampled_compute_nir(unsigned n_tex, unsigned n_live) +{ + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "sampled cap test"); + b.shader->info.workgroup_size[0] = 32; + b.shader->info.workgroup_size[1] = 1; + b.shader->info.workgroup_size[2] = 1; + + nir_def *gid = + nir_u2u64(&b, nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0)); + nir_def *addr = + nir_iadd(&b, nir_imm_int64(&b, 0x10000), nir_imul_imm(&b, gid, 8)); + nir_def *base = nir_load_global(&b, 1, 32, addr, .align_mul = 4); + nir_def *delta = + nir_load_global(&b, 1, 32, nir_iadd_imm(&b, addr, 4), .align_mul = 4); + + nir_def *tex_sum = nir_imm_float(&b, 0.0f); + for (unsigned i = 0; i < n_tex; ++i) { + nir_def *texture = + nir_bindless_image_agx(&b, nir_imm_int(&b, (i % 4) * 64), .desc_set = 0); + nir_tex_instr *tex = nir_tex_instr_create(b.shader, 3); + tex->op = nir_texop_txf; + tex->sampler_dim = GLSL_SAMPLER_DIM_2D; + tex->coord_components = 2; + tex->dest_type = nir_type_float32; + tex->src[0] = nir_tex_src_for_ssa(nir_tex_src_backend1, + nir_imm_ivec2(&b, i, 0)); + tex->src[1] = + nir_tex_src_for_ssa(nir_tex_src_lod, nir_imm_intN_t(&b, 0, 16)); + tex->src[2] = + nir_tex_src_for_ssa(nir_tex_src_texture_handle, texture); + nir_def_init(&tex->instr, &tex->def, 4, 32); + nir_builder_instr_insert(&b, &tex->instr); + tex_sum = nir_fadd(&b, tex_sum, nir_channel(&b, &tex->def, 0)); + } + + std::vector vals(n_live); + nir_def *prev = base; + for (unsigned i = 0; i < n_live; ++i) { + prev = nir_fadd(&b, prev, delta); + vals[i] = prev; + } + /* Consume in reverse order so all n_live values stay live simultaneously. */ + nir_def *sum = tex_sum; + for (int i = (int)n_live - 1; i >= 0; --i) + sum = nir_fadd(&b, nir_fmul_imm(&b, sum, 1.5f), vals[i]); + nir_store_global(&b, sum, addr, .align_mul = 4); + + if (!agx_nir_lower_g17p_indexed_samplers(b.shader, true)) + return NULL; + NIR_PASS(_, b.shader, nir_shader_intrinsics_pass, lower_test_descriptor_set, + nir_metadata_control_flow, NULL); + agx_preprocess_nir(b.shader); + return b.shader; +} + +/* When the 160-half cap pushes spill demand past the RA_MEM bound (4 KiB), + * compilation drops the cap and retries from the whole register file instead + * of refusing a program that fits there. */ +TEST(SampledComputeRegisterCap, RetryOnSpillExhaustionUsesWholeFile) +{ + /* Direct agx_ra() check on AGX3C with a 4 KiB spill bound: 1115 live 32-bit + * values (~2230 halves) exceed the 2048-half spill bound under the 160-half + * cap, but fit cleanly in the 252-half file. */ + { + void *mem = ralloc_context(NULL); + agx_builder *b = NULL; + agx_shader_key key = {}; + build_sampled_compute_air(mem, &b, &key, AGX_ISA_ENCODING_AGX3C, + AGX_CHIP_G17C, false, 0, false, true, 4, 1115); + key.max_scratch_B = 4096; + agx_ra(b->shader); + EXPECT_TRUE(b->shader->ra_failed); + EXPECT_TRUE(b->shader->ra_mem_exhausted); + EXPECT_TRUE(b->shader->sampled_cap_applied); + ralloc_free(mem); + + mem = ralloc_context(NULL); + build_sampled_compute_air(mem, &b, &key, AGX_ISA_ENCODING_AGX3C, + AGX_CHIP_G17C, false, 0, true, true, 4, 1115); + key.max_scratch_B = 4096; + agx_ra(b->shader); + EXPECT_FALSE(b->shader->ra_failed); + EXPECT_FALSE(b->shader->ra_mem_exhausted); + EXPECT_FALSE(b->shader->sampled_cap_applied); + EXPECT_GE(b->shader->max_reg, 160u); + EXPECT_GT(b->shader->scratch_size_B, 0u); + ralloc_free(mem); + } + + /* Full agx_compile_shader_nir() retry path on G17C with a 4 KiB bound. */ + nir_shader *nir = build_agx3c_sampled_compute_nir(4, 1115); + ASSERT_NE(nir, nullptr); + + agx_shader_key key = {}; + key.dev.encoding = AGX_ISA_ENCODING_AGX3C; + key.dev.chip = AGX_CHIP_G17C; + key.has_scratch = true; + key.optional_spills = true; + key.max_scratch_B = 4096; + key.no_preamble = true; + key.reserved_preamble = 16; + + agx_shader_part part = {}; + ASSERT_TRUE(agx_compile_shader_nir(nir, &key, &part)) + << agx_last_compile_refusal(); + EXPECT_GT(part.info.nr_gprs, 160u); + EXPECT_GT(part.info.scratch_size, 0u); + + free(part.binary); + ralloc_free(nir); +} + +/* ALU-heavy sampled compute shaders where capping to 160 halves forces + * excessive optional spills drop the cap and compile from the whole file. */ +TEST(SampledComputeRegisterCap, ExcessiveSpillsRetryUsesWholeFile) +{ + /* 4 texture loads and 100 live 32-bit values (~200 halves): fits uncapped + * in G17C's 252-half file with zero scratch, whereas capping to 160 halves + * exceeds both the spill-to-sample ratio and spill budget. */ + nir_shader *nir = build_agx3c_sampled_compute_nir(4, 100); + ASSERT_NE(nir, nullptr); + + agx_shader_key key = {}; + key.dev.encoding = AGX_ISA_ENCODING_AGX3C; + key.dev.chip = AGX_CHIP_G17C; + key.has_scratch = true; + key.optional_spills = true; + key.max_scratch_B = 4096; + key.no_preamble = true; + key.reserved_preamble = 16; + + agx_shader_part part = {}; + ASSERT_TRUE(agx_compile_shader_nir(nir, &key, &part)) + << agx_last_compile_refusal(); + EXPECT_GT(part.info.nr_gprs, 160u); + EXPECT_EQ(part.info.scratch_size, 0u); + + free(part.binary); + ralloc_free(nir); +} + +/* Texture-heavy sampled compute shaders with moderate optional spills keep + * the 160-half occupancy cap. */ +TEST(SampledComputeRegisterCap, ModerateSpillsKeepSampledCap) +{ + /* 16 texture loads and 86 live 32-bit values (~172 halves): spills ~16 + * values (~64 B) under the 160-half cap, well within both the spill budget + * and spill-to-sample ratio. */ + nir_shader *nir = build_agx3c_sampled_compute_nir(16, 86); + ASSERT_NE(nir, nullptr); + + agx_shader_key key = {}; + key.dev.encoding = AGX_ISA_ENCODING_AGX3C; + key.dev.chip = AGX_CHIP_G17C; + key.has_scratch = true; + key.optional_spills = true; + key.max_scratch_B = 4096; + key.no_preamble = true; + key.reserved_preamble = 16; + + agx_shader_part part = {}; + ASSERT_TRUE(agx_compile_shader_nir(nir, &key, &part)) + << agx_last_compile_refusal(); + EXPECT_LE(part.info.nr_gprs, 160u); + EXPECT_GT(part.info.scratch_size, 0u); + + free(part.binary); + ralloc_free(nir); +} + +/* Loop-weighted spill traffic outpacing outside texture ops rejects the cap, + * whereas textures inside the same loop justify the same spills. Also verify: + * - multi-backedge loops count as a single nesting level, + * - nested loops compound nesting weight, + * - NIR scratch accesses below spill_base_B are ignored, and + * - multi-component (e.g. 64-bit / mask=0x3) spills count per scalar access + * against the 48-scalar ceiling. */ +TEST(SampledComputeRegisterCap, LoopSpillsWeightedAgainstLoopTextures) +{ + for (bool tex_in_loop : {false, true}) { + SCOPED_TRACE(tex_in_loop); + void *mem = ralloc_context(NULL); + agx_builder *b = agx_test_builder(mem); + agx_context *ctx = b->shader; + ctx->spill_base_B = 64; + ctx->scratch_size_B = 80; /* 16 B RA spill frame above 64 B NIR scratch */ + + agx_block *entry = agx_start_block(ctx); + entry->index = 0; + + agx_block *loop_hdr = rzalloc(ctx, agx_block); + loop_hdr->index = 1; + loop_hdr->loop_header = true; + list_inithead(&loop_hdr->instructions); + list_addtail(&loop_hdr->link, &ctx->blocks); + + /* Two distinct backedges (continue + latch) to the same loop header. */ + agx_block *loop_latch = rzalloc(ctx, agx_block); + loop_latch->index = 2; + list_inithead(&loop_latch->instructions); + list_addtail(&loop_latch->link, &ctx->blocks); + + agx_block_add_successor(entry, loop_hdr); + agx_block_add_successor(loop_hdr, loop_hdr); + agx_block_add_successor(loop_hdr, loop_latch); + agx_block_add_successor(loop_latch, loop_hdr); + + /* NIR scratch accesses below spill_base_B (64 B) must not count. */ + b->cursor = agx_after_block(loop_latch); + for (unsigned i = 0; i < 64; ++i) { + agx_stack_store(b, agx_register(0, AGX_SIZE_32), agx_immediate(0), + AGX_FORMAT_I32, 0xf); + agx_stack_load_to(b, agx_register(0, AGX_SIZE_32), agx_immediate(0), + AGX_FORMAT_I32, 0xf); + } + + /* Emit 4 texture loads either outside or inside the loop. */ + b->cursor = agx_after_block(tex_in_loop ? loop_hdr : entry); + for (unsigned i = 0; i < 4; ++i) { + agx_texture_load_to(b, agx_register(0, AGX_SIZE_32), + agx_register(4, AGX_SIZE_32), agx_immediate(0), + agx_immediate(0), agx_immediate(0), + agx_immediate(0), agx_null(), AGX_DIM_2D, + AGX_LOD_MODE_LOD_MIN, 0x1, false, false); + } + + /* Emit 2 scalar spills + 2 scalar fills in loop_hdr (single nesting + * level despite two backedges -> weight 8 -> 32 weighted spill ops). + * When textures are outside: 32 <= 4*8=32 (just fits!). Adding one more + * 64-bit spill (mask=0x3 -> 2 scalar stores -> +16 weighted = 48 > 32) + * must trip the ratio when textures are outside, while still passing when + * textures are inside (48 <= 32*8=256). */ + b->cursor = agx_after_block(loop_hdr); + for (unsigned i = 0; i < 2; ++i) { + agx_stack_store(b, agx_register(0, AGX_SIZE_32), + agx_immediate(64 + i * 4), AGX_FORMAT_I32, 0x1); + agx_stack_load_to(b, agx_register(0, AGX_SIZE_32), + agx_immediate(64 + i * 4), AGX_FORMAT_I32, 0x1); + } + /* Exactly at 32 == 4*8: passes regardless of tex_in_loop (verifies + * multi-backedge did not double-count loop_hdr to weight 64). */ + EXPECT_FALSE(agx_sampled_cap_spills_excessive(ctx)); + + agx_stack_store(b, agx_register(0, AGX_SIZE_64), agx_immediate(72), + AGX_FORMAT_I32, 0x3); + EXPECT_EQ(agx_sampled_cap_spills_excessive(ctx), !tex_in_loop); + ralloc_free(mem); + } + + /* Nested loop (depth 2 -> weight 64) vs outer texture (depth 1 -> weight 8) + * and 64-bit spill scalar boundary (48 ok, 50 rejected). */ + { + void *mem = ralloc_context(NULL); + agx_builder *b = agx_test_builder(mem); + agx_context *ctx = b->shader; + ctx->spill_base_B = 32; + ctx->scratch_size_B = 128; /* 96 B RA spill frame (<= 192 B) */ + + agx_block *outer = agx_start_block(ctx); + outer->index = 0; + outer->loop_header = true; + + agx_block *inner = rzalloc(ctx, agx_block); + inner->index = 1; + inner->loop_header = true; + list_inithead(&inner->instructions); + list_addtail(&inner->link, &ctx->blocks); + + agx_block_add_successor(outer, inner); + agx_block_add_successor(inner, inner); + agx_block_add_successor(inner, outer); + + /* 2 outer textures (weight 8 -> 16) allows up to 128 weighted spill ops. + * Two scalar stores in inner loop (weight 64 -> 128) fit; adding a third + * (192 > 128) rejects. */ + b->cursor = agx_after_block(outer); + for (unsigned i = 0; i < 2; ++i) { + agx_texture_load_to(b, agx_register(0, AGX_SIZE_32), + agx_register(4, AGX_SIZE_32), agx_immediate(0), + agx_immediate(0), agx_immediate(0), + agx_immediate(0), agx_null(), AGX_DIM_2D, + AGX_LOD_MODE_LOD_MIN, 0x1, false, false); + } + b->cursor = agx_after_block(inner); + agx_stack_store(b, agx_register(0, AGX_SIZE_64), agx_immediate(32), + AGX_FORMAT_I32, 0x3); /* 2 scalars * 64 = 128 */ + EXPECT_FALSE(agx_sampled_cap_spills_excessive(ctx)); + + agx_stack_store(b, agx_register(0, AGX_SIZE_32), agx_immediate(40), + AGX_FORMAT_I32, 0x1); /* +64 = 192 > 128 */ + EXPECT_TRUE(agx_sampled_cap_spills_excessive(ctx)); + ralloc_free(mem); + } + + /* Scalar spill-count ceiling boundary with 64-bit spills (mask=0x3): + * 24 * 2 = 48 scalar stores passes; 25 * 2 = 50 rejects even with ample + * texture loads and small scratch footprint. */ + { + void *mem = ralloc_context(NULL); + agx_builder *b = agx_test_builder(mem); + agx_context *ctx = b->shader; + ctx->spill_base_B = 16; + ctx->scratch_size_B = 80; /* 64 B RA spill frame (<= 192 B) */ + + agx_block *blk = agx_start_block(ctx); + blk->index = 0; + b->cursor = agx_after_block(blk); + for (unsigned i = 0; i < 32; ++i) { + agx_texture_load_to(b, agx_register(0, AGX_SIZE_32), + agx_register(4, AGX_SIZE_32), agx_immediate(0), + agx_immediate(0), agx_immediate(0), + agx_immediate(0), agx_null(), AGX_DIM_2D, + AGX_LOD_MODE_LOD_MIN, 0x1, false, false); + } + for (unsigned i = 0; i < 24; ++i) { + agx_stack_store(b, agx_register(0, AGX_SIZE_64), agx_immediate(16), + AGX_FORMAT_I32, 0x3); + } + EXPECT_FALSE(agx_sampled_cap_spills_excessive(ctx)); + + agx_stack_store(b, agx_register(0, AGX_SIZE_64), agx_immediate(16), + AGX_FORMAT_I32, 0x3); /* 50 > 48 */ + EXPECT_TRUE(agx_sampled_cap_spills_excessive(ctx)); + ralloc_free(mem); + } +} diff --git a/src/asahi/vulkan/hk_cmd_buffer.h b/src/asahi/vulkan/hk_cmd_buffer.h index fd268bdac601..2d1a449e0dcf 100644 --- a/src/asahi/vulkan/hk_cmd_buffer.h +++ b/src/asahi/vulkan/hk_cmd_buffer.h @@ -4361,6 +4361,20 @@ void hk_cmd_dispatch_unaligned(VkCommandBuffer commandBuffer, void hk_cmd_dispatch_indirect_addr(VkCommandBuffer command_buffer, VkDeviceAddress address); +/* Whether a compute launch on this device can take the scratch frame its + * shader's register spills need. hk_dispatch_g17g_native() carries G18G + * scratch through g18_compute_resources, while hk_dispatch_m5_native() + * takes it only with the kernel's compute resources (and refuses scratch + * by this same rule). The compiler only spills to an occupancy cap + * (optional_spills) where this holds. */ +static inline bool +hk_compute_launch_takes_scratch(const struct agx_device *dev) +{ + if (agx_chip_g17_m5(dev->chip)) + return dev->params.features & DRM_ASAHI_FEATURE_COMPUTE_RESOURCES; + return true; +} + static inline void hk_dispatch_with_local_size(struct hk_cmd_buffer *cmd, struct hk_cs *cs, struct hk_shader *s, struct agx_grid grid, diff --git a/src/asahi/vulkan/hk_cmd_dispatch.c b/src/asahi/vulkan/hk_cmd_dispatch.c index b052dd7f5e70..1d0c97561174 100644 --- a/src/asahi/vulkan/hk_cmd_dispatch.c +++ b/src/asahi/vulkan/hk_cmd_dispatch.c @@ -2217,7 +2217,7 @@ hk_dispatch_m5_native(struct hk_cmd_buffer *cmd, struct hk_cs *cs, /* Static TPS addresses are 15-bit halfword offsets. */ !hk_g17p_compute_shader_supported(dev->dev.chip, s, linked, 1u << 16) || ((s->b.info.scratch_size || linked->b.scratch_size) && - !(dev->dev.params.features & DRM_ASAHI_FEATURE_COMPUTE_RESOURCES)) || + !hk_compute_launch_takes_scratch(&dev->dev)) || s->b.info.uses_ray_traversal || s->info.agx3_txf_texture_valid || s->info.agx3_storage_image_valid || s->info.agx3_sampled_storage_valid || s->info.agx3_indexed_storage_valid || diff --git a/src/asahi/vulkan/hk_shader.c b/src/asahi/vulkan/hk_shader.c index c3d38409e62e..ef3306f7bc5e 100644 --- a/src/asahi/vulkan/hk_shader.c +++ b/src/asahi/vulkan/hk_shader.c @@ -6903,6 +6903,9 @@ hk_compile_nir_impl(struct hk_device *dev, const VkAllocationCallbacks *pAllocat .no_stop = nir->info.stage == MESA_SHADER_FRAGMENT, .has_scratch = !nir->info.internal, .max_scratch_B = max_scratch_B, + .optional_spills = + !nir->info.internal && sw_stage == MESA_SHADER_COMPUTE && + hk_compute_launch_takes_scratch(&dev->dev), .promote_constants = true, .promote_textures = true, /* hk_buffer_addr_format() and hk_ubo_addr_format() bound robust