From 0f3b08dd0f90af165b1ad3ebac1e05f3fda71e85 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 18 Nov 2026 22:40:54 -0500 Subject: [PATCH 1/4] agx: derive a register cap for sampled compute from occupancy Compute programs with four or more texture reads spend much of their time waiting on them, and more resident threads hide that wait. Cap their registers so a core keeps 5/8 of its maximum resident threads, trading scratch spills for occupancy. The cap is derived from the device's register file and the occupancy steps rather than keyed on one chip. agx_register_file_halves() gives the per-thread file for each encoding, and agx_sampled_compute_register_cap() takes the largest budget that still reaches the target step. The spills only pay for a large step in resident threads, so a device gets the cap only where it raises them by half again or more: 384 to 640 threads gained on G17C, while 512 to 640 lost 7-10% on G16G with the same sample workload. A device whose file is unknown gets no cap. With the current occupancy table the AGX2 and AGX3C encodings resolve to 160 halves (640 resident threads instead of 384); AGX3B, whose file already reaches 512, gets none. The cap only applies where the launch takes the scratch of its spills. The driver says so with the new optional_spills key bit, from hk_compute_launch_takes_scratch(), the same rule its compute dispatch paths accept scratch by: G18G launches take none, and M5 launches take it only with the kernel's compute resources. Gallium does not set the bit. G18G gets no cap from the derivation either. Borealis's shader cache identity includes that rule, so a binary cached with the cap is not reused on a kernel whose launch refuses its spills. Helpers, preambles, unspillable programs and ray-traversal programs keep their hardware budget. The cap is only an occupancy trade, so the retry after a failed allocation drops it and spills down from the whole file instead of refusing a program that fits there. A unit test pins the derived cap per encoding (160 on G17C and AGX2, none on AGX3B or G18G) and checks on both G17C and G14G (AGX2) that the first allocation spills to the cap, that the retry uses the whole file with zero scratch, and that a key without optional_spills or with fewer than four texture reads keeps the whole file. Signed-off-by: Erik Bourget --- src/asahi/compiler/agx_compile.h | 15 ++ src/asahi/compiler/agx_performance.c | 73 ++++++++ src/asahi/compiler/agx_register_allocate.c | 23 +++ src/asahi/compiler/meson.build | 1 + .../test-sampled-compute-register-cap.cpp | 176 ++++++++++++++++++ src/asahi/vulkan/hk_cmd_buffer.h | 16 ++ src/asahi/vulkan/hk_cmd_dispatch.c | 9 +- src/asahi/vulkan/hk_shader.c | 11 +- 8 files changed, 317 insertions(+), 7 deletions(-) create mode 100644 src/asahi/compiler/test/test-sampled-compute-register-cap.cpp diff --git a/src/asahi/compiler/agx_compile.h b/src/asahi/compiler/agx_compile.h index 44cd11b2ea8f..eeffa409318b 100644 --- a/src/asahi/compiler/agx_compile.h +++ b/src/asahi/compiler/agx_compile.h @@ -540,6 +540,13 @@ struct agx_shader_key { * (4 KiB). Ignored on AGX2, which stays capped at AGX2_MAX_SPILL_SLOTS. */ 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. */ @@ -807,6 +814,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_performance.c b/src/asahi/compiler/agx_performance.c index 80e92bfd5523..44b80eefea6f 100644 --- a/src/asahi/compiler/agx_performance.c +++ b/src/asahi/compiler/agx_performance.c @@ -48,6 +48,79 @@ 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; + } +} + +/* + * 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 two + * properties of the device: + * + * - 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 the cap would not raise its resident threads + * above what its whole file allows, or when its register file is unknown + * (agx_register_file_halves() returns 0). + * + * AGX2 and AGX3C currently resolve to 160: their files (256 and 252 halves) + * 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. G18G gets + * no cap, as it takes no scratch for compute. 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) +{ + /* G18G launches compute without scratch (hk_dispatch_g17g_native() + * refuses it), so the spills the cap trades for threads would refuse the + * launch there. + */ + if (dev->emit_agx3d || dev->encoding == AGX_ISA_ENCODING_AGX3D) + 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 29d723712186..d93168881a6a 100644 --- a/src/asahi/compiler/agx_register_allocate.c +++ b/src/asahi/compiler/agx_register_allocate.c @@ -3338,6 +3338,29 @@ agx_ra_impl(agx_context *ctx, bool disable_remat) 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 + * (ra_budget_cut) drops it and spills down from the whole file, as it + * would without the cap, 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->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) + max_possible_regs = MIN2(max_possible_regs, sampled_cap); + } + /* Match the CEM scratch extent reserved by agx3_pack_binary. */ if (ctx->key->dev.encoding == AGX_ISA_ENCODING_AGX3B) max_possible_regs = MIN2(max_possible_regs, diff --git a/src/asahi/compiler/meson.build b/src/asahi/compiler/meson.build index 02f96c007aad..48319a9a9259 100644 --- a/src/asahi/compiler/meson.build +++ b/src/asahi/compiler/meson.build @@ -718,6 +718,7 @@ if with_tests 'test/test-agx-register-cache.cpp', 'test/test-ra-early-kill.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..5370d821e277 --- /dev/null +++ b/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp @@ -0,0 +1,176 @@ +/* Copyright 2026 Aurora Silicon + * SPDX-License-Identifier: MIT + */ +#include +#include "agx_builder.h" +#include "agx_test.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 the register file and the occupancy steps, not from + * the chip it was tuned on. */ +TEST(SampledComputeRegisterCap, DerivedFromFileAndOccupancy) +{ + /* G17C (AGX3C): exactly the 160 halves it was tuned at. */ + 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); + + /* The other files reach fewer threads than 640 uncapped. */ + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX2), 160u); + /* AGX3B reaches 512 threads uncapped: too small a step for the spills. */ + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3B), 0u); + + /* G18G takes no scratch for compute, so it gets no cap. */ + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3C, true), 0u); + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3D), 0u); + + /* No register file, no cap. */ + EXPECT_EQ(cap_for(AGX_ISA_ENCODING_UNKNOWN), 0u); +} + +/* A compute program with 200 halves live and configurable texture reads: + * with >= 4 texture reads, the first allocation spills to fit the cap; the + * retry after a failed allocation (ra_budget_cut) or a launch without + * optional_spills works from the whole file and needs no spill. */ +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) +{ + void *mem = ralloc_context(NULL); + agx_builder *b = agx_test_builder(mem); + agx_shader_key key = {}; + key.dev.encoding = encoding; + key.dev.chip = chip; + 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; + + 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 values[84]; + /* Each value depends on the previous one, so none rematerializes. */ + for (unsigned i = 0; i < ARRAY_SIZE(values); ++i) { + values[i] = agx_fadd(b, i ? values[i - 1] : agx_uniform(160, AGX_SIZE_32), + agx_uniform(32 + 2 * (i % 64), AGX_SIZE_32)); + } + for (agx_index value : values) + agx_unit_test(b, value); + 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]); + } + } + + 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) +{ + struct { + enum agx_isa_encoding encoding; + enum agx_chip chip; + } targets[] = { + {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C}, + {AGX_ISA_ENCODING_AGX2, AGX_CHIP_G14G}, + }; + + 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)); + EXPECT_LT(max_reg, 160u); + EXPECT_GT(scratch_B, 0u); + + ASSERT_NO_FATAL_FAILURE(allocate_sampled_compute(t.encoding, t.chip, 16, + &max_reg, &scratch_B)); + EXPECT_GE(max_reg, 160u); + EXPECT_EQ(scratch_B, 0u); + } +} + +/* 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; + } targets[] = { + {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C}, + {AGX_ISA_ENCODING_AGX2, AGX_CHIP_G14G}, + }; + + 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)); + EXPECT_GE(max_reg, 160u); + EXPECT_EQ(scratch_B, 0u); + } +} + +/* Compute programs below four texture reads keep the whole file. */ +TEST(SampledComputeRegisterCap, NoCapBelowTextureThreshold) +{ + struct { + enum agx_isa_encoding encoding; + enum agx_chip chip; + } targets[] = { + {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C}, + {AGX_ISA_ENCODING_AGX2, AGX_CHIP_G14G}, + }; + + 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, true, 0)); + EXPECT_GE(max_reg, 160u); + EXPECT_EQ(scratch_B, 0u); + } +} diff --git a/src/asahi/vulkan/hk_cmd_buffer.h b/src/asahi/vulkan/hk_cmd_buffer.h index a2f6c73237df..305036491e7e 100644 --- a/src/asahi/vulkan/hk_cmd_buffer.h +++ b/src/asahi/vulkan/hk_cmd_buffer.h @@ -3081,6 +3081,22 @@ 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() launches no + * scratch on G18G, and hk_dispatch_m5_native() takes it only with the + * kernel's compute resources, which carry the frame on M5. The compiler only + * spills to an occupancy cap (optional_spills) where this holds, so the + * dispatch paths refuse scratch by this same rule. */ +static inline bool +hk_compute_launch_takes_scratch(const struct agx_device *dev) +{ + if (dev->chip == AGX_CHIP_G18G) + return false; + 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 f4d30785cde9..0f5045fe5650 100644 --- a/src/asahi/vulkan/hk_cmd_dispatch.c +++ b/src/asahi/vulkan/hk_cmd_dispatch.c @@ -1807,7 +1807,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 || @@ -2567,9 +2567,10 @@ hk_dispatch_g17g_native(struct hk_cmd_buffer *cmd, struct hk_cs *cs, AGX3_G17P_MAX_SPILL_B) || s->info.stage != MESA_SHADER_COMPUTE || agx_is_indirect(grid) || (!g18 && s->b.info.local_size) || s->b.info.uses_ray_traversal || - (g18 && (s->b.info.scratch_size || linked->b.scratch_size || - s->b.info.agx3_spectpr_scratch_size || - s->b.info.nr_preamble_gprs)) || + (!hk_compute_launch_takes_scratch(&dev->dev) && + (s->b.info.scratch_size || linked->b.scratch_size || + s->b.info.agx3_spectpr_scratch_size)) || + (g18 && s->b.info.nr_preamble_gprs) || (g18 && s->info.g18_unlowered_image) || s->info.agx3_txf_texture_valid || (s->info.agx3_storage_image_valid && !g18) || diff --git a/src/asahi/vulkan/hk_shader.c b/src/asahi/vulkan/hk_shader.c index dd8150ff649b..fbddb3c3f1b9 100644 --- a/src/asahi/vulkan/hk_shader.c +++ b/src/asahi/vulkan/hk_shader.c @@ -209,9 +209,12 @@ hk_fs_structure_key_bits(void) uint64_t hk_physical_device_compiler_flags(const struct hk_physical_device *pdev) { - /* This could be optimized but it doesn't matter. */ - return pdev->dev.debug | - hk_fs_structure_key_bits(); + /* This could be optimized but it doesn't matter. Whether compute + * launches take scratch decides optional_spills, so it names the cache + * too. */ + const bool launch_scratch = hk_compute_launch_takes_scratch(&pdev->dev); + return pdev->dev.debug | hk_fs_structure_key_bits() | + ((uint64_t)launch_scratch << 31); } const nir_shader_compiler_options * @@ -5626,6 +5629,8 @@ hk_compile_nir(struct hk_device *dev, const VkAllocationCallbacks *pAllocator, .no_stop = nir->info.stage == MESA_SHADER_FRAGMENT, .has_scratch = !nir->info.internal, .max_scratch_B = max_scratch_B, + .optional_spills = + !nir->info.internal && hk_compute_launch_takes_scratch(&dev->dev), .promote_constants = true, .promote_textures = true, /* hk_buffer_addr_format() and hk_ubo_addr_format() bound robust From b2392e5ccd5f693eae98a8aaffc0ce609f896e48 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 15:30:37 -0500 Subject: [PATCH 2/4] agx: drop sampled compute cap on RA_MEM exhaustion retry When agx_sampled_compute_register_cap() tightens max_possible_regs, the capped attempt can exhaust RA_MEM (AGX2_MAX_SPILL_SLOTS on AGX2 or max_scratch_B on AGX3) even though the shader fits within the uncapped register file. Previously agx_compile_function_nir_attempt() skipped any retry when ctx->ra_mem_exhausted was set, refusing shaders that compiled before the cap. Track whether the sampled cap actually lowered max_possible_regs (ctx->sampled_cap_applied) and retry once with ctx->disable_sampled_cap set and ra_budget_cut = 0 on any capped RA failure (including ra_mem_exhausted) or AGX3 scratch-frame limit exceedance before falling back to the normal ra_budget_cut retries or refusal. Also drop the redundant emit_agx3d / AGX_ISA_ENCODING_AGX3D early return from agx_sampled_compute_register_cap(), so the helper stays derived from the register file and occupancy steps while optional_spills keeps no-scratch launches (such as G18G) uncapped. Extend test-sampled-compute-register-cap.cpp with RetryOnSpillExhaustionUsesWholeFile (covering RA_MEM exhaustion at 160 halves and whole-file compilation via agx_compile_shader_nir() on G14G and G17C) and G18G optional_spills=false coverage. Signed-off-by: Erik Bourget --- src/asahi/compiler/agx_compile.c | 35 ++- src/asahi/compiler/agx_compiler.h | 6 + src/asahi/compiler/agx_performance.c | 16 +- src/asahi/compiler/agx_register_allocate.c | 12 +- .../test-sampled-compute-register-cap.cpp | 214 ++++++++++++++++-- 5 files changed, 236 insertions(+), 47 deletions(-) diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index 6c690544b3aa..59648e941a16 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -13259,7 +13259,7 @@ agx_compile_function_nir_attempt(nir_shader *nir, nir_function_impl *impl, struct util_dynarray *binary, struct agx_shader_info *out, unsigned *offset_out, unsigned ra_budget_cut, bool disable_remat, bool *retry_without_remat, - bool agx3_reg_float_consts) + bool agx3_reg_float_consts, bool disable_sampled_cap) { const unsigned initial_binary_size = binary->size; const struct agx_shader_info initial_out = *out; @@ -13280,6 +13280,7 @@ agx_compile_function_nir_attempt(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) @@ -13630,6 +13631,19 @@ agx_compile_function_nir_attempt(nir_shader *nir, nir_function_impl *impl, return false; } 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_attempt( + nir, impl, key, binary, out, offset_out, 0, disable_remat, + retry_without_remat, agx3_reg_float_consts, true); + } + /* 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 @@ -13643,7 +13657,7 @@ agx_compile_function_nir_attempt(nir_shader *nir, nir_function_impl *impl, return agx_compile_function_nir_attempt( nir, impl, key, binary, out, offset_out, ra_budget_cut ? ra_budget_cut * 2 : 16, disable_remat, - retry_without_remat, agx3_reg_float_consts); + retry_without_remat, agx3_reg_float_consts, disable_sampled_cap); } agx_set_refusal(ctx, "register allocation found no legal placement", __LINE__); @@ -13738,6 +13752,15 @@ agx_compile_function_nir_attempt(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_attempt( + nir, impl, key, binary, out, offset_out, 0, disable_remat, + retry_without_remat, agx3_reg_float_consts, true); + } agx_set_refusal(ctx, "AGX3 scratch frame exceeds target limit", __LINE__); binary->size = initial_binary_size; @@ -14016,7 +14039,7 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, if (!eligible) return agx_compile_function_nir_attempt(nir, impl, key, binary, out, offset_out, 0, false, NULL, - agx3_reg_float_consts); + agx3_reg_float_consts, false); /* Preserve all compiler-owned state, including earlier main code/rodata. * The first attempt owns a deep NIR clone and a fresh AIR context. */ @@ -14024,7 +14047,7 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, if (!attempt) return agx_compile_function_nir_attempt(nir, impl, key, binary, out, offset_out, 0, false, NULL, - agx3_reg_float_consts); + agx3_reg_float_consts, false); nir_function_impl *attempt_impl = NULL; nir_foreach_function_with_impl(func, candidate, attempt) { @@ -14040,7 +14063,7 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, bool retry = false; bool success = agx_compile_function_nir_attempt( attempt, attempt_impl, key, binary, out, offset_out, 0, false, &retry, - agx3_reg_float_consts); + agx3_reg_float_consts, false); ralloc_free(attempt); if (!retry) return success; @@ -14052,7 +14075,7 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, /* Exactly one retry. Real full-budget spills retain the old refusal. */ return agx_compile_function_nir_attempt(nir, impl, key, binary, out, offset_out, 0, true, NULL, - agx3_reg_float_consts); + agx3_reg_float_consts, false); } /* diff --git a/src/asahi/compiler/agx_compiler.h b/src/asahi/compiler/agx_compiler.h index 02ed001eba91..56185ff77aa4 100644 --- a/src/asahi/compiler/agx_compiler.h +++ b/src/asahi/compiler/agx_compiler.h @@ -759,6 +759,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; diff --git a/src/asahi/compiler/agx_performance.c b/src/asahi/compiler/agx_performance.c index 44b80eefea6f..aa2c40a6ef4f 100644 --- a/src/asahi/compiler/agx_performance.c +++ b/src/asahi/compiler/agx_performance.c @@ -84,23 +84,17 @@ agx_register_file_halves(const struct agx_device_key *dev) * above what its whole file allows, or when its register file is unknown * (agx_register_file_halves() returns 0). * - * AGX2 and AGX3C currently resolve to 160: their files (256 and 252 halves) - * 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. G18G gets - * no cap, as it takes no scratch for compute. All encodings share one + * AGX2, AGX3C, and AGX3D currently resolve to 160: their files (256 and + * 252 halves) 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. Launches that take no scratch (such as G18G) 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) { - /* G18G launches compute without scratch (hk_dispatch_g17g_native() - * refuses it), so the spills the cap trades for threads would refuse the - * launch there. - */ - if (dev->emit_agx3d || dev->encoding == AGX_ISA_ENCODING_AGX3D) - return 0; - const unsigned file = agx_register_file_halves(dev); if (!file) return 0; diff --git a/src/asahi/compiler/agx_register_allocate.c b/src/asahi/compiler/agx_register_allocate.c index d93168881a6a..704cecfde98e 100644 --- a/src/asahi/compiler/agx_register_allocate.c +++ b/src/asahi/compiler/agx_register_allocate.c @@ -3342,12 +3342,12 @@ agx_ra_impl(agx_context *ctx, bool disable_remat) * 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 - * (ra_budget_cut) drops it and spills down from the whole file, as it - * would without the cap, rather than refusing a program that fits there. + * (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 && + 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 && @@ -3357,8 +3357,10 @@ agx_ra_impl(agx_context *ctx, bool disable_remat) if (I->op == AGX_OPCODE_TEXTURE_SAMPLE || I->op == AGX_OPCODE_TEXTURE_LOAD) samples++; } - if (samples >= 4) - max_possible_regs = MIN2(max_possible_regs, sampled_cap); + if (samples >= 4 && sampled_cap < max_possible_regs) { + max_possible_regs = sampled_cap; + ctx->sampled_cap_applied = true; + } } /* Match the CEM scratch extent reserved by agx3_pack_binary. */ diff --git a/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp b/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp index 5370d821e277..448c80547fc4 100644 --- a/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp +++ b/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp @@ -4,6 +4,11 @@ #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) @@ -32,32 +37,34 @@ TEST(SampledComputeRegisterCap, DerivedFromFileAndOccupancy) /* AGX3B reaches 512 threads uncapped: too small a step for the spills. */ EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3B), 0u); - /* G18G takes no scratch for compute, so it gets no cap. */ - EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3C, true), 0u); - EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX3D), 0u); + /* AGX3D also has a 252-half file; launches that take no scratch (G18G) + * keep the cap off via optional_spills = false. */ + 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 200 halves live and configurable texture reads: +/* 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) or a launch without - * optional_spills works from the whole file and needs no spill. */ + * retry after a failed allocation (ra_budget_cut / disable_sampled_cap) or a + * launch without optional_spills works from the whole file. */ 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) +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) { - void *mem = ralloc_context(NULL); agx_builder *b = agx_test_builder(mem); - agx_shader_key key = {}; - key.dev.encoding = encoding; - key.dev.chip = chip; - key.has_scratch = true; - key.optional_spills = optional_spills; - b->shader->key = &key; + *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); @@ -66,6 +73,7 @@ allocate_sampled_compute(enum agx_isa_encoding encoding, enum agx_chip chip, 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) { @@ -82,14 +90,16 @@ allocate_sampled_compute(enum agx_isa_encoding encoding, enum agx_chip chip, false, false); } - agx_index values[84]; + 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 < ARRAY_SIZE(values); ++i) { - values[i] = agx_fadd(b, i ? values[i - 1] : agx_uniform(160, AGX_SIZE_32), + 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 (agx_index value : values) - agx_unit_test(b, value); + 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) { @@ -98,6 +108,22 @@ allocate_sampled_compute(enum agx_isa_encoding encoding, enum agx_chip chip, } } + *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; @@ -137,9 +163,11 @@ TEST(SampledComputeRegisterCap, NoCapWithoutOptionalSpills) struct { enum agx_isa_encoding encoding; enum agx_chip chip; + bool emit_agx3d; } targets[] = { - {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C}, - {AGX_ISA_ENCODING_AGX2, AGX_CHIP_G14G}, + {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) { @@ -147,7 +175,7 @@ TEST(SampledComputeRegisterCap, NoCapWithoutOptionalSpills) unsigned max_reg, scratch_B; ASSERT_NO_FATAL_FAILURE(allocate_sampled_compute( - t.encoding, t.chip, 0, &max_reg, &scratch_B, false)); + t.encoding, t.chip, 0, &max_reg, &scratch_B, false, 4, t.emit_agx3d)); EXPECT_GE(max_reg, 160u); EXPECT_EQ(scratch_B, 0u); } @@ -174,3 +202,139 @@ TEST(SampledComputeRegisterCap, NoCapBelowTextureThreshold) EXPECT_EQ(scratch_B, 0u); } } + +/* When the 160-half cap pushes spill demand past the RA_MEM bound (4 KiB on + * AGX2), compilation drops the cap and retries from the whole register file + * instead of refusing a program that fits there. */ +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; +} + +TEST(SampledComputeRegisterCap, RetryOnSpillExhaustionUsesWholeFile) +{ + /* 1115 live 32-bit values (~2230 halves) exceed AGX2_MAX_SPILL_SLOTS (2048 + * halves) under the 160-half cap, but fit cleanly in the 256-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_AGX2, + AGX_CHIP_G14G, false, 0, false, true, 4, 1115); + 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_AGX2, + AGX_CHIP_G14G, false, 0, true, true, 4, 1115); + 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 G14G (AGX2) and G17C (AGX3C + * with a 4 KiB spill bound). */ + struct { + enum agx_isa_encoding encoding; + enum agx_chip chip; + uint32_t max_scratch_B; + } targets[] = { + {AGX_ISA_ENCODING_AGX2, AGX_CHIP_G14G, 0}, + {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C, 4096}, + }; + + for (const auto &t : targets) { + SCOPED_TRACE(t.chip); + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "sampled cap spill retry"); + 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); + + const bool is_agx3c = t.encoding == AGX_ISA_ENCODING_AGX3C; + nir_def *tex_sum = nir_imm_float(&b, 0.0f); + for (unsigned i = 0; i < 4; ++i) { + nir_def *texture = + nir_bindless_image_agx(&b, nir_imm_int(&b, i * 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( + is_agx3c ? nir_tex_src_backend1 : nir_tex_src_coord, + nir_imm_ivec2(&b, i, 0)); + tex->src[1] = nir_tex_src_for_ssa( + nir_tex_src_lod, + is_agx3c ? nir_imm_intN_t(&b, 0, 16) : nir_imm_int(&b, 0)); + 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)); + } + + constexpr unsigned N = 1115; + std::vector vals(N); + nir_def *prev = base; + for (unsigned i = 0; i < N; ++i) { + prev = nir_fadd(&b, prev, delta); + vals[i] = prev; + } + /* Consume in reverse order so all N values stay live simultaneously. */ + nir_def *sum = tex_sum; + for (int i = N - 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 (is_agx3c) { + ASSERT_TRUE(agx_nir_lower_g17p_indexed_samplers(b.shader, true)); + NIR_PASS(_, b.shader, nir_shader_intrinsics_pass, + lower_test_descriptor_set, nir_metadata_control_flow, NULL); + } else { + agx_nir_lower_texture_for_generation(b.shader, 8); + } + agx_preprocess_nir(b.shader); + + agx_shader_key key = {}; + key.dev.encoding = t.encoding; + key.dev.chip = t.chip; + key.has_scratch = true; + key.optional_spills = true; + key.max_scratch_B = t.max_scratch_B; + key.no_preamble = true; + key.reserved_preamble = 16; + + agx_shader_part part = {}; + ASSERT_TRUE(agx_compile_shader_nir(b.shader, &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(b.shader); + } +} From a064bf402c1517e85571b7fa14c81e7e6e93e1e6 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 17:15:07 -0500 Subject: [PATCH 3/4] borealis: drop redundant G18G scratch check and compiler flag bit hk_dispatch_g17g_native() is only called for AGX_CHIP_G18G, where hk_compute_launch_takes_scratch() unconditionally returns true and scratch_bytes > max_spill (64 KiB) is already checked directly. Drop the redundant !hk_compute_launch_takes_scratch() guard there and update the hk_compute_launch_takes_scratch() comment. Also drop bit 31 from hk_physical_device_compiler_flags(): its sole consumer, hk_cache_identity(), already hashes both dev->chip and all 64 kernel feature bits in dev->params.features, which completely determine hk_compute_launch_takes_scratch(). Signed-off-by: Erik Bourget --- src/asahi/vulkan/hk_cmd_buffer.h | 6 +++--- src/asahi/vulkan/hk_cmd_dispatch.c | 1 - src/asahi/vulkan/hk_shader.c | 9 +++------ 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/asahi/vulkan/hk_cmd_buffer.h b/src/asahi/vulkan/hk_cmd_buffer.h index 3f169e42e5cd..c202aafda28a 100644 --- a/src/asahi/vulkan/hk_cmd_buffer.h +++ b/src/asahi/vulkan/hk_cmd_buffer.h @@ -3789,9 +3789,9 @@ void hk_cmd_dispatch_indirect_addr(VkCommandBuffer command_buffer, /* 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. The compiler only - * spills to an occupancy cap (optional_spills) where this holds, so the - * dispatch paths refuse scratch by this same rule. */ + * 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) { diff --git a/src/asahi/vulkan/hk_cmd_dispatch.c b/src/asahi/vulkan/hk_cmd_dispatch.c index 87fb1fabc692..6fbbac186ae9 100644 --- a/src/asahi/vulkan/hk_cmd_dispatch.c +++ b/src/asahi/vulkan/hk_cmd_dispatch.c @@ -2851,7 +2851,6 @@ hk_dispatch_g17g_native(struct hk_cmd_buffer *cmd, struct hk_cs *cs, (internal && s->info.stage != MESA_SHADER_VERTEX && s->data_size) || (!g18 && agx_is_indirect(grid)) || (g18_indirect && (!grid.ptr || sparse_indirect)) || - (!hk_compute_launch_takes_scratch(&dev->dev) && scratch_bytes) || s->b.info.uses_ray_traversal || (g18 && (s->b.info.nr_preamble_gprs || scratch_bytes > max_spill || diff --git a/src/asahi/vulkan/hk_shader.c b/src/asahi/vulkan/hk_shader.c index 04934963cf2c..e8ed24748c09 100644 --- a/src/asahi/vulkan/hk_shader.c +++ b/src/asahi/vulkan/hk_shader.c @@ -214,12 +214,9 @@ hk_fs_structure_key_bits(void) uint64_t hk_physical_device_compiler_flags(const struct hk_physical_device *pdev) { - /* This could be optimized but it doesn't matter. Whether compute - * launches take scratch decides optional_spills, so it names the cache - * too. */ - const bool launch_scratch = hk_compute_launch_takes_scratch(&pdev->dev); - return pdev->dev.debug | hk_fs_structure_key_bits() | - ((uint64_t)launch_scratch << 31); + /* This could be optimized but it doesn't matter. */ + return pdev->dev.debug | + hk_fs_structure_key_bits(); } uint32_t From aca2656bc5b1fa2ed27c02ddefad1752222ab212 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 23:37:36 -0500 Subject: [PATCH 4/4] agx: require static TPS and bound optional spills for sampled compute cap Hardware A/B testing of the 160-half sampled-compute register cap on G13G (AGX2) and G17C (AGX3C) exposed two separate spill-regression causes, plus a stage-scoping bug in hk_compile_nir(): 1. ISA spill backing (AGX2 vs AGX3 static TPS): AGX2 spills to a helper-backed device-memory stack (agx_scratch) with explicit 2-slot scoreboard waits after each reload, whereas AGX3 uses launch-allocated static thread-private storage (copy/rld with hardware scoreboarding). On G13G, capping sampled compute to 160 halves slowed ALU-heavy sampled compute by +16% to +259% (up to 3.6x) and yielded no meaningful gain on texture-bound workloads (-0.9% to +2.4%, vs -7.0% to -14.5% on G17C for the same shaders). Restrict agx_sampled_compute_register_cap() to encodings with static TPS (AGX3B/AGX3C/AGX3D; AGX3B still resolves to 0 from its 192-half register file). 2. Unbounded optional spills on AGX3C: applying the cap solely on samples >= 4 forced 82-290 spills/fills on ALU-heavy compute shaders with only 8 texture fetches, regressing G17C by +8.7% to +47.9%, and added 54-78 spills (216-312 B scratch) on heavy texture shaders for 0% gain. Add agx_sampled_cap_spills_excessive() and drop the optional cap via the existing whole-file retry in agx_compile_function_nir_attempt() when RA spills exceed 192 B, 48 scalar stores/loads, or 8 loop-weighted spill/fill ops per weighted texture op (counted per loop header). 3. Stage scoping in hk_compile_nir(): software vertex and tessellation-eval variants are retagged to MESA_SHADER_COMPUTE before backend key setup. Require sw_stage == MESA_SHADER_COMPUTE when setting optional_spills so only real Vulkan compute shaders opt into the cap. Signed-off-by: Erik Bourget --- src/asahi/compiler/agx_compile.c | 14 + src/asahi/compiler/agx_compiler.h | 1 + src/asahi/compiler/agx_performance.c | 43 +- src/asahi/compiler/agx_register_allocate.c | 107 ++++ .../test-sampled-compute-register-cap.cpp | 466 +++++++++++++----- src/asahi/vulkan/hk_shader.c | 3 +- 6 files changed, 495 insertions(+), 139 deletions(-) diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index dfc0407a908e..97a55da965cd 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -15169,6 +15169,20 @@ agx_compile_function_nir_attempt(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_attempt( + nir, impl, key, binary, out, offset_out, 0, disable_remat, + retry_without_remat, agx3_reg_float_consts, true); + } + /* 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 diff --git a/src/asahi/compiler/agx_compiler.h b/src/asahi/compiler/agx_compiler.h index 0235082e6a62..17b926cd5a9b 100644 --- a/src/asahi/compiler/agx_compiler.h +++ b/src/asahi/compiler/agx_compiler.h @@ -1428,6 +1428,7 @@ void agx_repair_ssa(agx_context *ctx); void agx_reindex_ssa(agx_context *ctx); void agx_ra(agx_context *ctx); void agx_ra_without_remat(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 5ceea41452f1..9bc0961fa50e 100644 --- a/src/asahi/compiler/agx_performance.c +++ b/src/asahi/compiler/agx_performance.c @@ -66,12 +66,30 @@ agx_register_file_halves(const struct agx_device_key *dev) } } +/* 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 two - * properties of the device: + * 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()). @@ -80,21 +98,26 @@ agx_register_file_halves(const struct agx_device_key *dev) * 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 the cap would not raise its resident threads - * above what its whole file allows, or when its register file is unknown + * 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). * - * AGX2, AGX3C, and AGX3D currently resolve to 160: their files (256 and - * 252 halves) reach 384 threads uncapped, so the cap raises that to 640. + * 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. 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. + * 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; diff --git a/src/asahi/compiler/agx_register_allocate.c b/src/asahi/compiler/agx_register_allocate.c index 2573a32624d7..7ce6115e4467 100644 --- a/src/asahi/compiler/agx_register_allocate.c +++ b/src/asahi/compiler/agx_register_allocate.c @@ -5046,3 +5046,110 @@ agx_ra_without_remat(agx_context *ctx) { agx_ra_impl(ctx, true); } + +/* 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/test/test-sampled-compute-register-cap.cpp b/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp index 7997bc65968e..8e7b8234fbe5 100644 --- a/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp +++ b/src/asahi/compiler/test/test-sampled-compute-register-cap.cpp @@ -19,11 +19,11 @@ cap_for(enum agx_isa_encoding encoding, bool emit_agx3d = false) return agx_sampled_compute_register_cap(&dev); } -/* The cap follows from the register file and the occupancy steps, not from - * the chip it was tuned on. */ +/* 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): exactly the 160 halves it was tuned at. */ + /* 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 = {}; @@ -32,13 +32,14 @@ TEST(SampledComputeRegisterCap, DerivedFromFileAndOccupancy) EXPECT_EQ(agx_register_file_halves(&g17c), 252u); EXPECT_EQ(agx_occupancy_for_register_count(252).max_threads, 384u); - /* The other files reach fewer threads than 640 uncapped. */ - EXPECT_EQ(cap_for(AGX_ISA_ENCODING_AGX2), 160u); + /* 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 a 252-half file; launches without optional_spills keep - * the cap off. */ + /* 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); @@ -133,27 +134,37 @@ allocate_sampled_compute(enum agx_isa_encoding encoding, enum agx_chip chip, TEST(SampledComputeRegisterCap, RetryAfterFailedAllocationUsesWholeFile) { - struct { - enum agx_isa_encoding encoding; - enum agx_chip chip; - } targets[] = { - {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C}, - {AGX_ISA_ENCODING_AGX2, AGX_CHIP_G14G}, - }; + unsigned max_reg, scratch_B; - for (const auto &t : targets) { - SCOPED_TRACE(t.chip); - 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(t.encoding, t.chip, 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); +} - ASSERT_NO_FATAL_FAILURE(allocate_sampled_compute(t.encoding, t.chip, 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); } } @@ -181,31 +192,21 @@ TEST(SampledComputeRegisterCap, NoCapWithoutOptionalSpills) } } -/* Compute programs below four texture reads keep the whole file. */ +/* Compute programs below four texture reads (0 and 3) keep the whole file. */ TEST(SampledComputeRegisterCap, NoCapBelowTextureThreshold) { - struct { - enum agx_isa_encoding encoding; - enum agx_chip chip; - } targets[] = { - {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C}, - {AGX_ISA_ENCODING_AGX2, AGX_CHIP_G14G}, - }; - - for (const auto &t : targets) { - SCOPED_TRACE(t.chip); + for (unsigned tex_loads : {0u, 3u}) { + SCOPED_TRACE(tex_loads); unsigned max_reg, scratch_B; ASSERT_NO_FATAL_FAILURE(allocate_sampled_compute( - t.encoding, t.chip, 0, &max_reg, &scratch_B, true, 0)); + 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); } } -/* When the 160-half cap pushes spill demand past the RA_MEM bound (4 KiB on - * AGX2), compilation drops the cap and retries from the whole register file - * instead of refusing a program that fits there. */ static bool lower_test_descriptor_set(nir_builder *b, nir_intrinsic_instr *intr, void *) { @@ -219,16 +220,78 @@ lower_test_descriptor_set(nir_builder *b, nir_intrinsic_instr *intr, void *) 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) { - /* 1115 live 32-bit values (~2230 halves) exceed AGX2_MAX_SPILL_SLOTS (2048 - * halves) under the 160-half cap, but fit cleanly in the 256-half file. */ + /* 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_AGX2, - AGX_CHIP_G14G, false, 0, false, true, 4, 1115); + 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); @@ -236,8 +299,9 @@ TEST(SampledComputeRegisterCap, RetryOnSpillExhaustionUsesWholeFile) ralloc_free(mem); mem = ralloc_context(NULL); - build_sampled_compute_air(mem, &b, &key, AGX_ISA_ENCODING_AGX2, - AGX_CHIP_G14G, false, 0, true, true, 4, 1115); + 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); @@ -247,94 +311,240 @@ TEST(SampledComputeRegisterCap, RetryOnSpillExhaustionUsesWholeFile) ralloc_free(mem); } - /* Full agx_compile_shader_nir() retry path on G14G (AGX2) and G17C (AGX3C - * with a 4 KiB spill bound). */ - struct { - enum agx_isa_encoding encoding; - enum agx_chip chip; - uint32_t max_scratch_B; - } targets[] = { - {AGX_ISA_ENCODING_AGX2, AGX_CHIP_G14G, 0}, - {AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C, 4096}, - }; + /* 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); - for (const auto &t : targets) { - SCOPED_TRACE(t.chip); - nir_builder b = nir_builder_init_simple_shader( - MESA_SHADER_COMPUTE, &agx_nir_options, "sampled cap spill retry"); - 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); - - const bool is_agx3c = t.encoding == AGX_ISA_ENCODING_AGX3C; - nir_def *tex_sum = nir_imm_float(&b, 0.0f); + 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) { - nir_def *texture = - nir_bindless_image_agx(&b, nir_imm_int(&b, i * 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( - is_agx3c ? nir_tex_src_backend1 : nir_tex_src_coord, - nir_imm_ivec2(&b, i, 0)); - tex->src[1] = nir_tex_src_for_ssa( - nir_tex_src_lod, - is_agx3c ? nir_imm_intN_t(&b, 0, 16) : nir_imm_int(&b, 0)); - 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)); + 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); + } - constexpr unsigned N = 1115; - std::vector vals(N); - nir_def *prev = base; - for (unsigned i = 0; i < N; ++i) { - prev = nir_fadd(&b, prev, delta); - vals[i] = prev; + /* 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); } - /* Consume in reverse order so all N values stay live simultaneously. */ - nir_def *sum = tex_sum; - for (int i = N - 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 (is_agx3c) { - ASSERT_TRUE(agx_nir_lower_g17p_indexed_samplers(b.shader, true)); - NIR_PASS(_, b.shader, nir_shader_intrinsics_pass, - lower_test_descriptor_set, nir_metadata_control_flow, NULL); - } else { - agx_nir_lower_texture_for_generation(b.shader, 8); + for (unsigned i = 0; i < 24; ++i) { + agx_stack_store(b, agx_register(0, AGX_SIZE_64), agx_immediate(16), + AGX_FORMAT_I32, 0x3); } - agx_preprocess_nir(b.shader); + EXPECT_FALSE(agx_sampled_cap_spills_excessive(ctx)); - agx_shader_key key = {}; - key.dev.encoding = t.encoding; - key.dev.chip = t.chip; - key.has_scratch = true; - key.optional_spills = true; - key.max_scratch_B = t.max_scratch_B; - key.no_preamble = true; - key.reserved_preamble = 16; - - agx_shader_part part = {}; - ASSERT_TRUE(agx_compile_shader_nir(b.shader, &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(b.shader); + 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_shader.c b/src/asahi/vulkan/hk_shader.c index e8ed24748c09..7f642fcf57a8 100644 --- a/src/asahi/vulkan/hk_shader.c +++ b/src/asahi/vulkan/hk_shader.c @@ -6369,7 +6369,8 @@ hk_compile_nir(struct hk_device *dev, const VkAllocationCallbacks *pAllocator, .has_scratch = !nir->info.internal, .max_scratch_B = max_scratch_B, .optional_spills = - !nir->info.internal && hk_compute_launch_takes_scratch(&dev->dev), + !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