From 6e289c86ced9ab8a29c4e6ae8b43a0e1fe0c7f07 Mon Sep 17 00:00:00 2001 From: Dylan Ironside Date: Tue, 1 Dec 2026 07:22:50 -0600 Subject: [PATCH 1/6] hk,agx: version aligned robust compute loops on G16G and refine preamble weights Two compute-kernel compiler improvements: 1. hk_shader.c (g16_version_aligned_robust_loops): - On G16G (!soft_fault), version compute loops containing AoS bounded buffer loads (offset = amul(ib, stride) + local, provable local + load_size <= stride <= 4096 < AGX_ZERO_PAGE_SIZE) on bound % stride == 0 once before the loop. - Require workgroup-uniform bounds via nir_divergence_analysis_impl(..., nir_divergence_across_subgroups) and nir_def_is_divergent_at_use_block() so per-invocation or per-subgroup nonuniform descriptor bounds never split subgroups or workgroup barriers. - Inside the fast loop, share one (valid, vbase, vblock) check per struct element across all fields of the element and emit unbounded global loads so downstream load vectorization merges adjacent fields without per-component tail masks. - Arbitrary unaligned descriptor sizes take the unmodified fallback loop with exact robustBufferAccess / robustBufferAccess2 / nullDescriptor semantics. - Add hk_aligned_robust_loop_test covering uniform descriptor versioning and per-lane / per-subgroup nonuniform descriptor rejection. 2. agx_nir_opt_preamble.c: - Model nir_op_usub_sat at its true 2-instruction AGX cost (iadd + icmpsel = 2.0) instead of 1.0. - Preserve preamble hoisting weight for loops nested inside uniform branches (weight *= 8.0f per enclosing loop, clamped to 1.0f). Signed-off-by: Dylan Ironside --- src/asahi/compiler/agx_nir_opt_preamble.c | 9 +- src/asahi/vulkan/hk_shader.c | 717 ++++++++++++++++++ src/asahi/vulkan/hk_shader.h | 4 + src/asahi/vulkan/meson.build | 7 + .../tests/test-hk-aligned-robust-loop.c | 182 +++++ 5 files changed, 917 insertions(+), 2 deletions(-) create mode 100644 src/asahi/vulkan/tests/test-hk-aligned-robust-loop.c diff --git a/src/asahi/compiler/agx_nir_opt_preamble.c b/src/asahi/compiler/agx_nir_opt_preamble.c index a24a4e7c32f5..2889600f411c 100644 --- a/src/asahi/compiler/agx_nir_opt_preamble.c +++ b/src/asahi/compiler/agx_nir_opt_preamble.c @@ -158,11 +158,14 @@ alu_cost(nir_alu_instr *alu) case nir_op_iadd_sat: case nir_op_isub_sat: case nir_op_uadd_sat: - case nir_op_usub_sat: case nir_op_iabs: /* SCIB */ return 1.0; + case nir_op_usub_sat: + /* Emits iadd + icmpsel on AGX. */ + return 2.0; + case nir_op_ffloor: case nir_op_fceil: case nir_op_ftrunc: @@ -318,8 +321,10 @@ execution_weight(nir_block *block, const struct set *branches) for (nir_cf_node *node = block->cf_node.parent; node; node = node->parent) { if (is_branch(branches, node)) weight /= 8.0f; + else if (node->type == nir_cf_node_loop) + weight *= 8.0f; } - return weight; + return MIN2(weight, 1.0f); } static void diff --git a/src/asahi/vulkan/hk_shader.c b/src/asahi/vulkan/hk_shader.c index 17461f0eb8c7..86793849b63d 100644 --- a/src/asahi/vulkan/hk_shader.c +++ b/src/asahi/vulkan/hk_shader.c @@ -57,7 +57,9 @@ #include "nir_serialize.h" #include "util/blob.h" #include "nir_builder.h" +#include "nir_control_flow.h" #include "nir_deref.h" +#include "nir_range_analysis.h" #include "agx_bo.h" #include "hk_cmd_buffer.h" @@ -1940,6 +1942,711 @@ is_shiftable_amul(nir_scalar s) return false; } +static nir_def * +g16_emit_global_load(nir_builder *b, bool constant, unsigned comps, + unsigned bit_size, nir_def *addr, unsigned align_mul, + unsigned align_offset, enum gl_access_qualifier access) +{ + return constant + ? nir_load_global_constant(b, comps, bit_size, addr, + .align_mul = align_mul, + .align_offset = align_offset, .access = access) + : nir_load_global(b, comps, bit_size, addr, + .align_mul = align_mul, + .align_offset = align_offset, .access = access); +} + +/* + * G16G (no DRM_ASAHI_FEATURE_SOFT_FAULTS): uniform loop-versioned struct + * bounds coalescing for bounded buffer loads. + * + * When a compute loop contains multiple bounded loads from the same AoS array + * element (offset = amul(ib, stride) + local, with provable local + load_size + * <= stride <= 4096 < AGX_ZERO_PAGE_SIZE), checking bound % stride == 0 once + * before the loop guarantees that no partial tail struct can exist: + * - ib < bound / stride => every field in [ib * stride, (ib + 1) * stride) + * lies strictly inside [0, bound). + * - ib >= bound / stride => every field is out of bounds and reads zero from + * AGX_ZERO_PAGE_ADDRESS + local (< 16 KiB). + * + * The fast loop shares one (block_valid, vbase, vblock) across all loads of + * the same struct element (eliminating per-load bounds selects and per-lane + * vector tail masks while leaving g16_merge_bounded_loads free to merge + * adjacent fields into unbounded vector loads). Any unaligned buffer size + * executes the unmodified fallback loop, preserving exact robustBufferAccess / + * robustBufferAccess2 / nullDescriptor semantics for every descriptor size. + */ +struct g16_bound_key { + bool is_desc; + nir_def *outside_def; + unsigned desc_set; + uint32_t desc_offset; + unsigned comp; + unsigned num_comps; + unsigned bit_size; + unsigned align_mul; + unsigned align_offset; + enum gl_access_qualifier access; +}; + +static bool +g16_bound_keys_equal(const struct g16_bound_key *a, + const struct g16_bound_key *b) +{ + if (a->is_desc != b->is_desc) + return false; + if (!a->is_desc) + return a->outside_def == b->outside_def; + return a->desc_set == b->desc_set && a->desc_offset == b->desc_offset && + a->comp == b->comp && a->bit_size == b->bit_size; +} + +static bool +g16_parse_invariant_bound(nir_def *bound, const struct set *loop_blocks, + nir_block *before_loop, struct g16_bound_key *out) +{ + if (bound->bit_size != 32 || bound->num_components != 1) + return false; + + if (!_mesa_set_search(loop_blocks, nir_def_block(bound))) { + if (nir_def_is_divergent_at_use_block(bound, before_loop)) + return false; + *out = (struct g16_bound_key){ + .is_desc = false, + .outside_def = bound, + }; + return true; + } + + nir_scalar s = nir_scalar_resolved(bound, 0); + if (s.def->bit_size != 32) + return false; + + if (!_mesa_set_search(loop_blocks, nir_def_block(s.def)) && + s.def->num_components == 1) { + if (nir_def_is_divergent_at_use_block(s.def, before_loop)) + return false; + *out = (struct g16_bound_key){ + .is_desc = false, + .outside_def = s.def, + }; + return true; + } + + nir_intrinsic_instr *intr = nir_def_as_intrinsic_or_null(s.def); + if (!intr || intr->intrinsic != nir_intrinsic_load_global_constant_offset) + return false; + if (!(nir_intrinsic_access(intr) & ACCESS_CAN_SPECULATE)) + return false; + + nir_intrinsic_instr *ds = nir_def_as_intrinsic_or_null(intr->src[0].ssa); + if (!ds || ds->intrinsic != nir_intrinsic_load_descriptor_set_agx) + return false; + + nir_scalar off = nir_scalar_resolved(intr->src[1].ssa, 0); + if (!nir_scalar_is_const(off)) + return false; + + *out = (struct g16_bound_key){ + .is_desc = true, + .desc_set = nir_intrinsic_desc_set(ds), + .desc_offset = (uint32_t)nir_scalar_as_uint(off), + .comp = s.comp, + .num_comps = intr->def.num_components, + .bit_size = intr->def.bit_size, + .align_mul = nir_intrinsic_align_mul(intr), + .align_offset = nir_intrinsic_align_offset(intr), + .access = nir_intrinsic_access(intr), + }; + return true; +} + +static uint64_t +g16_u32_upper_bound(nir_shader *shader, struct hash_table *ranges, + nir_scalar s, unsigned depth) +{ + if (nir_scalar_is_const(s)) + return nir_scalar_as_uint(s); + + if (depth && nir_scalar_is_alu(s)) { + switch (nir_scalar_alu_op(s)) { + case nir_op_mov: + return g16_u32_upper_bound(shader, ranges, + nir_scalar_chase_alu_src(s, 0), depth - 1); + case nir_op_u2u32: { + nir_scalar src = nir_scalar_chase_alu_src(s, 0); + uint64_t mask = src.def->bit_size < 32 + ? ((UINT64_C(1) << src.def->bit_size) - 1) + : UINT32_MAX; + return MIN2(mask, g16_u32_upper_bound(shader, ranges, src, depth - 1)); + } + case nir_op_iand: { + uint64_t x = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 0), depth - 1); + uint64_t y = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 1), depth - 1); + return MIN2(x, y); + } + case nir_op_ior: { + uint64_t x = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 0), depth - 1); + uint64_t y = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 1), depth - 1); + unsigned bits = util_last_bit64(x | y); + return bits >= 32 ? UINT32_MAX : (bits ? ((UINT64_C(1) << bits) - 1) : 0); + } + case nir_op_ushr: { + nir_scalar sh = nir_scalar_chase_alu_src(s, 1); + if (!nir_scalar_is_const(sh)) + return UINT32_MAX; + uint64_t x = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 0), depth - 1); + return x >> (nir_scalar_as_uint(sh) & 31); + } + case nir_op_ishl: { + nir_scalar sh = nir_scalar_chase_alu_src(s, 1); + if (!nir_scalar_is_const(sh)) + return UINT32_MAX; + unsigned k = nir_scalar_as_uint(sh) & 31; + uint64_t x = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 0), depth - 1); + if (x > (UINT32_MAX >> k)) + return UINT32_MAX; + return x << k; + } + case nir_op_iadd: + case nir_op_uadd_sat: { + uint64_t x = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 0), depth - 1); + uint64_t y = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 1), depth - 1); + return x > UINT32_MAX - y ? UINT32_MAX : x + y; + } + case nir_op_imul: + case nir_op_amul: { + uint64_t x = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 0), depth - 1); + uint64_t y = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 1), depth - 1); + if (x && y > UINT32_MAX / x) + return UINT32_MAX; + return x * y; + } + case nir_op_ubitfield_extract: { + nir_scalar bits = nir_scalar_chase_alu_src(s, 2); + if (!nir_scalar_is_const(bits)) + return UINT32_MAX; + unsigned w = nir_scalar_as_uint(bits); + return w >= 32 ? UINT32_MAX : (w ? ((UINT64_C(1) << w) - 1) : 0); + } + case nir_op_bcsel: { + uint64_t x = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 1), depth - 1); + uint64_t y = g16_u32_upper_bound( + shader, ranges, nir_scalar_chase_alu_src(s, 2), depth - 1); + return MAX2(x, y); + } + default: + break; + } + } + + return nir_unsigned_upper_bound(shader, ranges, s); +} + +static bool +g16_collect_add_terms(nir_scalar s, unsigned depth, nir_scalar *terms, + unsigned *count, uint64_t *const_sum) +{ + if (nir_scalar_is_const(s)) { + uint64_t v = nir_scalar_as_uint(s); + if (*const_sum > UINT32_MAX - v) + return false; + *const_sum += v; + return true; + } + if (depth && (is_op(s, nir_op_iadd) || is_op(s, nir_op_uadd_sat))) { + return g16_collect_add_terms(nir_scalar_chase_alu_src(s, 0), depth - 1, + terms, count, const_sum) && + g16_collect_add_terms(nir_scalar_chase_alu_src(s, 1), depth - 1, + terms, count, const_sum); + } + if (*count >= 6) + return false; + terms[(*count)++] = s; + return true; +} + +struct g16_struct_load { + nir_intrinsic_instr *intr; + nir_block *block; + nir_def *base; + struct g16_bound_key bound; + nir_scalar ib; + nir_def *amul_def; + uint32_t stride; + nir_scalar local_terms[6]; + unsigned num_local_terms; + uint32_t local_const; + unsigned req_idx; + unsigned instr_index; +}; + +static bool +g16_extract_struct_load(nir_shader *shader, struct hash_table *ranges, + const struct set *loop_blocks, nir_block *before_loop, + nir_intrinsic_instr *intr, struct g16_struct_load *out) +{ + if (intr->intrinsic != nir_intrinsic_load_global_bounded && + intr->intrinsic != nir_intrinsic_load_global_constant_bounded) + return false; + + nir_def *offset = intr->src[1].ssa; + nir_def *bound = intr->src[2].ssa; + if (offset->bit_size != 32 || offset->num_components != 1) + return false; + + struct g16_bound_key bkey; + if (!g16_parse_invariant_bound(bound, loop_blocks, before_loop, &bkey)) + return false; + + const unsigned load_size = intr->num_components * (intr->def.bit_size / 8); + if (load_size == 0 || load_size > 16) + return false; + + nir_scalar terms[6]; + unsigned count = 0; + uint64_t const_sum = 0; + if (!g16_collect_add_terms(nir_scalar_resolved(offset, 0), 5, terms, &count, + &const_sum) || + count == 0) + return false; + + int best = -1; + uint32_t best_stride = 0; + nir_scalar best_ib = {0}; + for (unsigned i = 0; i < count; i++) { + if (!is_op(terms[i], nir_op_amul) || terms[i].def->bit_size != 32) + continue; + nir_scalar s0 = nir_scalar_chase_alu_src(terms[i], 0); + nir_scalar s1 = nir_scalar_chase_alu_src(terms[i], 1); + nir_scalar ib, c; + if (nir_scalar_is_const(s1) && !nir_scalar_is_const(s0)) { + ib = s0; + c = s1; + } else if (nir_scalar_is_const(s0) && !nir_scalar_is_const(s1)) { + ib = s1; + c = s0; + } else { + continue; + } + uint64_t stride = nir_scalar_as_uint(c); + if (stride < 16 || stride > 4096 || stride <= best_stride) + continue; + /* Check if remaining terms fit strictly inside [0, stride - load_size]. */ + uint64_t local_ub = const_sum; + bool fits = local_ub + load_size <= stride; + for (unsigned j = 0; j < count && fits; j++) { + if ((int)j == (int)i) + continue; + uint64_t ub = g16_u32_upper_bound(shader, ranges, terms[j], 6); + if (ub > stride || local_ub > stride - ub || + local_ub + ub + load_size > stride) + fits = false; + else + local_ub += ub; + } + if (fits) { + best = (int)i; + best_stride = (uint32_t)stride; + best_ib = ib; + } + } + + if (best < 0) + return false; + + *out = (struct g16_struct_load){ + .intr = intr, + .block = intr->instr.block, + .base = intr->src[0].ssa, + .bound = bkey, + .ib = best_ib, + .amul_def = terms[best].def, + .stride = best_stride, + .local_const = (uint32_t)const_sum, + .instr_index = intr->instr.index, + }; + for (unsigned j = 0; j < count; j++) { + if ((int)j == best) + continue; + out->local_terms[out->num_local_terms++] = terms[j]; + } + return true; +} + +static int +g16_struct_load_cmp(const void *pa, const void *pb) +{ + const struct g16_struct_load *a = pa, *b = pb; + if (a->block != b->block) + return a->block->index < b->block->index ? -1 : 1; + if (a->base->index != b->base->index) + return a->base->index < b->base->index ? -1 : 1; + if (a->req_idx != b->req_idx) + return a->req_idx < b->req_idx ? -1 : 1; + if (a->ib.def->index != b->ib.def->index) + return a->ib.def->index < b->ib.def->index ? -1 : 1; + if (a->ib.comp != b->ib.comp) + return (int)a->ib.comp - (int)b->ib.comp; + return a->instr_index < b->instr_index ? -1 : 1; +} + +struct g16_align_req { + struct g16_bound_key bound; + uint32_t stride; + nir_def *bound_val; + nir_def *n_blocks; +}; + +static bool +g16_def_escapes_loop_cb(nir_def *def, void *state) +{ + const struct set *loop_blocks = state; + nir_foreach_use_including_if(use, def) { + nir_block *use_block = nir_src_is_if(use) + ? nir_cf_node_as_block(nir_cf_node_prev(&nir_src_use_if(use)->cf_node)) + : nir_src_use_instr(use)->block; + if (!_mesa_set_search(loop_blocks, use_block)) + return false; + } + return true; +} + +static bool +g16_version_aligned_robust_loops( + nir_shader *nir, VkPipelineRobustnessBufferBehaviorEXT ssbo_robust, + VkPipelineRobustnessBufferBehaviorEXT ubo_robust) +{ + if (nir->info.stage != MESA_SHADER_COMPUTE) + return false; + if (ssbo_robust == VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT && + ubo_robust == VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT) + return false; + + nir_function_impl *impl = nir_shader_get_entrypoint(nir); + struct util_dynarray loops; + util_dynarray_init(&loops, NULL); + foreach_list_typed(nir_cf_node, node, node, &impl->body) { + if (node->type == nir_cf_node_loop) + util_dynarray_append(&loops, nir_cf_node_as_loop(node)); + } + if (util_dynarray_num_elements(&loops, nir_loop *) == 0) { + util_dynarray_fini(&loops); + return false; + } + + bool progress = false; + struct hash_table *ranges = _mesa_pointer_hash_table_create(NULL); + struct util_dynarray loads; + util_dynarray_init(&loads, NULL); + + util_dynarray_foreach(&loops, nir_loop *, loop_ptr) { + nir_loop *loop = *loop_ptr; + nir_index_ssa_defs(impl); + nir_index_instrs(impl); + nir_index_blocks(impl); + nir_divergence_analysis_impl( + impl, nir->options->divergence_analysis_options | + nir_divergence_across_subgroups); + nir_block *before_loop = + nir_cf_node_as_block(nir_cf_node_prev(&loop->cf_node)); + + struct set *loop_blocks = _mesa_pointer_set_create(NULL); + unsigned instr_count = 0; + nir_foreach_block_in_cf_node(block, &loop->cf_node) { + _mesa_set_add(loop_blocks, block); + nir_foreach_instr(instr, block) + instr_count++; + } + + bool ok = instr_count > 0 && instr_count <= 4000; + if (ok) { + nir_foreach_block_in_cf_node(block, &loop->cf_node) { + nir_foreach_instr(instr, block) { + if (!nir_foreach_def(instr, g16_def_escapes_loop_cb, + loop_blocks)) { + ok = false; + break; + } + } + if (!ok) + break; + } + } + + if (!ok) { + _mesa_set_destroy(loop_blocks, NULL); + continue; + } + + util_dynarray_clear(&loads); + struct g16_align_req reqs[4]; + unsigned num_reqs = 0; + bool too_many_reqs = false; + + nir_foreach_block_in_cf_node(block, &loop->cf_node) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic) + continue; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + struct g16_struct_load sl; + if (!g16_extract_struct_load(nir, ranges, loop_blocks, before_loop, + intr, &sl)) + continue; + + int ridx = -1; + for (unsigned r = 0; r < num_reqs; r++) { + if (reqs[r].stride == sl.stride && + g16_bound_keys_equal(&reqs[r].bound, &sl.bound)) { + ridx = (int)r; + break; + } + } + if (ridx < 0) { + if (num_reqs == ARRAY_SIZE(reqs)) { + too_many_reqs = true; + break; + } + ridx = (int)num_reqs++; + reqs[ridx] = (struct g16_align_req){ + .bound = sl.bound, + .stride = sl.stride, + .n_blocks = NULL, + }; + } + sl.req_idx = (unsigned)ridx; + util_dynarray_append(&loads, sl); + } + if (too_many_reqs) + break; + } + + unsigned n = util_dynarray_num_elements(&loads, struct g16_struct_load); + unsigned saved_checks = 0; + if (!too_many_reqs && n >= 4 && num_reqs > 0) { + struct g16_struct_load *arr = loads.data; + qsort(arr, n, sizeof(*arr), g16_struct_load_cmp); + for (unsigned g = 0; g < n;) { + unsigned g_end = g + 1; + while (g_end < n && arr[g_end].block == arr[g].block && + arr[g_end].base == arr[g].base && + arr[g_end].req_idx == arr[g].req_idx && + arr[g_end].ib.def == arr[g].ib.def && + arr[g_end].ib.comp == arr[g].ib.comp) + g_end++; + if (g_end - g >= 2) + saved_checks += (g_end - g) - 1; + g = g_end; + } + } + + if (too_many_reqs || saved_checks < 4) { + _mesa_set_destroy(loop_blocks, NULL); + continue; + } + + /* Emit uniform bound alignment checks before the loop. */ + nir_builder b = nir_builder_at(nir_before_cf_node(&loop->cf_node)); + nir_def *all_aligned = NULL; + for (unsigned r = 0; r < num_reqs; r++) { + nir_def *bound_val; + if (!reqs[r].bound.is_desc) { + bound_val = reqs[r].bound.outside_def; + } else { + nir_def *ds = + nir_load_descriptor_set_agx(&b, reqs[r].bound.desc_set); + nir_def *vec = nir_load_global_constant_offset( + &b, reqs[r].bound.num_comps, reqs[r].bound.bit_size, ds, + nir_imm_int(&b, reqs[r].bound.desc_offset), + .align_mul = reqs[r].bound.align_mul, + .align_offset = reqs[r].bound.align_offset, + .access = reqs[r].bound.access); + bound_val = nir_channel(&b, vec, reqs[r].bound.comp); + } + reqs[r].bound_val = bound_val; + if (util_is_power_of_two_nonzero(reqs[r].stride)) { + reqs[r].n_blocks = NULL; + nir_def *aligned = nir_ieq_imm( + &b, nir_iand_imm(&b, bound_val, reqs[r].stride - 1), 0); + all_aligned = + all_aligned ? nir_iand(&b, all_aligned, aligned) : aligned; + } else { + reqs[r].n_blocks = nir_udiv_imm(&b, bound_val, reqs[r].stride); + nir_def *aligned = + nir_ieq(&b, nir_imul_imm(&b, reqs[r].n_blocks, reqs[r].stride), + bound_val); + all_aligned = + all_aligned ? nir_iand(&b, all_aligned, aligned) : aligned; + } + } + + nir_cf_list loop_cf; + nir_cf_extract(&loop_cf, nir_before_cf_node(&loop->cf_node), + nir_after_cf_node(&loop->cf_node)); + + nir_if *nif = nir_push_if(&b, all_aligned); + nir_cf_list_clone_and_reinsert(&loop_cf, &nif->cf_node, + nir_after_cf_list(&nif->then_list), NULL); + nir_push_else(&b, nif); + nir_cf_reinsert(&loop_cf, nir_after_cf_list(&nif->else_list)); + nir_pop_if(&b, nif); + + _mesa_set_destroy(loop_blocks, NULL); + + /* Rewrite coalesced groups in the fast (then) loop. */ + nir_loop *fast_loop = NULL; + foreach_list_typed(nir_cf_node, cn, node, &nif->then_list) { + if (cn->type == nir_cf_node_loop) { + fast_loop = nir_cf_node_as_loop(cn); + break; + } + } + assert(fast_loop != NULL); + nir_index_ssa_defs(impl); + nir_index_instrs(impl); + nir_index_blocks(impl); + nir_divergence_analysis_impl( + impl, nir->options->divergence_analysis_options | + nir_divergence_across_subgroups); + nir_block *before_fast = + nir_cf_node_as_block(nir_cf_node_prev(&fast_loop->cf_node)); + + struct set *fast_blocks = _mesa_pointer_set_create(NULL); + nir_foreach_block_in_cf_node(block, &fast_loop->cf_node) + _mesa_set_add(fast_blocks, block); + + util_dynarray_clear(&loads); + nir_foreach_block_in_cf_node(block, &fast_loop->cf_node) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic) + continue; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + struct g16_struct_load sl; + if (!g16_extract_struct_load(nir, ranges, fast_blocks, before_fast, + intr, &sl)) + continue; + int ridx = -1; + for (unsigned r = 0; r < num_reqs; r++) { + if (reqs[r].stride == sl.stride && + g16_bound_keys_equal(&reqs[r].bound, &sl.bound)) { + ridx = (int)r; + break; + } + } + if (ridx < 0) + continue; + sl.req_idx = (unsigned)ridx; + util_dynarray_append(&loads, sl); + } + } + + unsigned fn = util_dynarray_num_elements(&loads, struct g16_struct_load); + if (fn >= 2) { + struct g16_struct_load *arr = loads.data; + qsort(arr, fn, sizeof(*arr), g16_struct_load_cmp); + for (unsigned g = 0; g < fn;) { + unsigned g_end = g + 1; + while (g_end < fn && arr[g_end].block == arr[g].block && + arr[g_end].base == arr[g].base && + arr[g_end].req_idx == arr[g].req_idx && + arr[g_end].ib.def == arr[g].ib.def && + arr[g_end].ib.comp == arr[g].ib.comp) + g_end++; + + if (g_end - g >= 2) { + nir_intrinsic_instr *first = arr[g].intr; + for (unsigned i = g + 1; i < g_end; i++) { + if (arr[i].instr_index < first->instr.index) + first = arr[i].intr; + } + + nir_builder fb = nir_builder_at(nir_before_instr(&first->instr)); + nir_def *ib_val = nir_mov_scalar(&fb, arr[g].ib); + const uint32_t stride = arr[g].stride; + /* With bound % stride == 0 and non-wrapping amul(ib, stride), + * amul(ib, stride) < bound is exact and compares directly + * against the uniform descriptor bound (zero extra live GPR). */ + nir_def *valid = + nir_ult(&fb, arr[g].amul_def, arr[g].intr->src[2].ssa); + nir_def *vbase = + nir_bcsel(&fb, valid, arr[g].base, + nir_imm_int64(&fb, AGX_ZERO_PAGE_ADDRESS)); + nir_def *vblock; + if (stride <= 16 && util_is_power_of_two_nonzero(stride)) { + nir_def *vib = + nir_bcsel(&fb, valid, ib_val, nir_imm_int(&fb, 0)); + vblock = nir_amul_imm(&fb, vib, stride); + } else { + vblock = nir_bcsel(&fb, valid, arr[g].amul_def, + nir_imm_int(&fb, 0)); + } + + const unsigned stride_align = 1u << (ffs(stride) - 1); + for (unsigned i = g; i < g_end; i++) { + nir_intrinsic_instr *intr = arr[i].intr; + nir_builder lb = + nir_builder_at(nir_before_instr(&intr->instr)); + nir_def *off = vblock; + for (unsigned t = 0; t < arr[i].num_local_terms; t++) { + off = nir_iadd(&lb, off, + nir_mov_scalar(&lb, arr[i].local_terms[t])); + } + if (arr[i].local_const) + off = nir_iadd_imm(&lb, off, arr[i].local_const); + + enum gl_access_qualifier access = nir_intrinsic_access(intr); + const bool is_const = + intr->intrinsic == + nir_intrinsic_load_global_constant_bounded; + if (is_const) + access |= ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER; + + unsigned align_mul = + MIN2(nir_intrinsic_align_mul(intr), stride_align); + unsigned align_offset = + nir_intrinsic_align_offset(intr) % align_mul; + nir_def *addr = nir_iadd(&lb, vbase, nir_u2u64(&lb, off)); + nir_def *val = g16_emit_global_load( + &lb, is_const, intr->def.num_components, + intr->def.bit_size, addr, align_mul, align_offset, access); + nir_def_replace(&intr->def, val); + } + } + + g = g_end; + } + } + + _mesa_set_destroy(fast_blocks, NULL); + progress = true; + } + + util_dynarray_fini(&loads); + util_dynarray_fini(&loops); + _mesa_hash_table_destroy(ranges, NULL); + return nir_progress(progress, impl, nir_metadata_none); +} + +bool +hk_nir_g16_version_aligned_robust_loops( + nir_shader *nir, VkPipelineRobustnessBufferBehaviorEXT ssbo_robust, + VkPipelineRobustnessBufferBehaviorEXT ubo_robust) +{ + return g16_version_aligned_robust_loops(nir, ssbo_robust, ubo_robust); +} + + static nir_def * bound_offset(nir_builder *b, nir_def *valid, nir_scalar offset, unsigned load_size) @@ -4868,6 +5575,16 @@ hk_lower_nir_ex(struct hk_device *dev, nir_shader *nir, } if (merge_words) NIR_PASS(_, nir, hk_nir_merge_buffer_words); + else if (dev->dev.chip == AGX_CHIP_G16G && !global_loads.soft_fault) { + /* Reads of one descriptor share its base and size only after CSE. */ + if (!global_loads.fold_field) + NIR_PASS(_, nir, nir_opt_cse); + bool versioned = false; + NIR_PASS(versioned, nir, g16_version_aligned_robust_loops, + rs->storage_buffers, rs->uniform_buffers); + if (versioned) + NIR_PASS(_, nir, nir_opt_cse); + } } else if (lowered_push_const) { NIR_PASS(_, nir, nir_opt_copy_prop); NIR_PASS(_, nir, nir_opt_constant_folding); diff --git a/src/asahi/vulkan/hk_shader.h b/src/asahi/vulkan/hk_shader.h index 1488bb382887..4ba346cdf60e 100644 --- a/src/asahi/vulkan/hk_shader.h +++ b/src/asahi/vulkan/hk_shader.h @@ -1137,6 +1137,10 @@ hk_buffer_addr_format(VkPipelineRobustnessBufferBehaviorEXT robustness, bool hk_lower_uvs_index(nir_shader *s, mesa_shader_stage sw_stage, unsigned nr_vbos, unsigned uniform_base); +bool hk_nir_g16_version_aligned_robust_loops( + nir_shader *nir, VkPipelineRobustnessBufferBehaviorEXT ssbo_robust, + VkPipelineRobustnessBufferBehaviorEXT ubo_robust); + bool hk_nir_layout_has_descriptors( const nir_shader *nir, uint32_t set_layout_count, struct vk_descriptor_set_layout *const *set_layouts); diff --git a/src/asahi/vulkan/meson.build b/src/asahi/vulkan/meson.build index 449a589f1697..04cf68b67b15 100644 --- a/src/asahi/vulkan/meson.build +++ b/src/asahi/vulkan/meson.build @@ -1928,6 +1928,13 @@ if with_tests dependencies : [hk_deps], link_with : [libhk], link_args : [ld_args_gc_sections]), timeout : 30, suite : ['asahi']) + test('hk_aligned_robust_loop', executable('hk_aligned_robust_loop_test', + files('tests/test-hk-aligned-robust-loop.c'), + include_directories : [include_directories('.'), inc_gallium, inc_gallium_aux, + inc_include, inc_src, inc_asahi, inc_virtio_gpu, inc_virtio_vdrm], + dependencies : [hk_deps], link_with : [libhk], + link_args : [ld_args_gc_sections]), + timeout : 30, suite : ['asahi']) endif if with_tests diff --git a/src/asahi/vulkan/tests/test-hk-aligned-robust-loop.c b/src/asahi/vulkan/tests/test-hk-aligned-robust-loop.c new file mode 100644 index 000000000000..c5b39d9a39c6 --- /dev/null +++ b/src/asahi/vulkan/tests/test-hk-aligned-robust-loop.c @@ -0,0 +1,182 @@ +/* + * Copyright 2026 Aurora Silicon + * SPDX-License-Identifier: MIT + */ + +#include "hk_shader.h" +#include "compiler/nir/nir_builder.h" +#include + +enum desc_uniformity { + DESC_UNIFORM_CONST, + DESC_NONUNIFORM_LANE, + DESC_NONUNIFORM_SUBGROUP, +}; + +static nir_phi_instr * +create_scalar_phi(nir_shader *shader) +{ + nir_phi_instr *phi = nir_phi_instr_create(shader); + nir_def_init(&phi->instr, &phi->def, 1, 32); + return phi; +} + +static bool +run_case(const char *name, enum desc_uniformity kind, bool expect_versioned) +{ + static const nir_shader_compiler_options options = {0}; + nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_COMPUTE, &options, + "%s", name); + b.shader->info.workgroup_size[0] = 64; + b.shader->info.workgroup_size[1] = 1; + b.shader->info.workgroup_size[2] = 1; + b.shader->info.workgroup_size_variable = false; + + /* Descriptor table entry: { u64 base, u32 size } (16 bytes per SSBO). */ + nir_def *ds = nir_load_descriptor_set_agx(&b, .desc_set = 0); + nir_def *desc_off = NULL; + switch (kind) { + case DESC_UNIFORM_CONST: + desc_off = nir_imm_int(&b, 0); + break; + case DESC_NONUNIFORM_LANE: { + /* Lanes select distinct SSBO array elements (e.g. 64- vs 68-byte + * descriptors). Defined outside the loop so it is loop-invariant, + * but per-invocation divergent. */ + nir_def *lane = nir_load_local_invocation_index(&b); + desc_off = nir_ishl_imm(&b, nir_iand_imm(&b, lane, 1), 4); + break; + } + case DESC_NONUNIFORM_SUBGROUP: { + /* Subgroups within the same workgroup select distinct SSBO array + * elements. Subgroup-uniform, but NOT workgroup-uniform. */ + nir_def *sg = nir_load_subgroup_id(&b); + desc_off = nir_ishl_imm(&b, nir_iand_imm(&b, sg, 1), 4); + break; + } + } + + nir_def *base = nir_load_global_constant_offset( + &b, 1, 64, ds, desc_off, .access = ACCESS_CAN_SPECULATE, .align_mul = 8); + nir_def *bound = nir_load_global_constant_offset( + &b, 1, 32, ds, nir_iadd_imm(&b, desc_off, 8), + .access = ACCESS_CAN_SPECULATE, .align_mul = 4); + + nir_def *zero = nir_imm_int(&b, 0); + nir_def *out_ptr = nir_imm_int64(&b, 0x200000000ULL); + + nir_loop *loop = nir_push_loop(&b); + nir_block *preheader = nir_loop_predecessor_block(loop); + nir_block *header = nir_loop_first_block(loop); + + nir_phi_instr *iv_phi = create_scalar_phi(b.shader); + nir_phi_instr_add_src(iv_phi, preheader, zero); + nir_def *iv = &iv_phi->def; + + nir_push_if(&b, nir_uge(&b, iv, nir_imm_int(&b, 8))); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + + /* 5 adjacent 4-byte fields inside a 32-byte AoS record (saves 4 checks). */ + nir_def *rec_off = nir_amul(&b, iv, nir_imm_int(&b, 32)); + nir_def *sum = zero; + for (unsigned f = 0; f < 5; f++) { + nir_def *off = f ? nir_iadd_imm(&b, rec_off, f * 4) : rec_off; + nir_def *v = nir_load_global_bounded(&b, 1, 32, base, off, bound, + .align_mul = 4); + sum = nir_iadd(&b, sum, v); + } + + /* Exercise both subgroup-convergent and workgroup-convergent ops inside + * the loop body. */ + if (kind == DESC_NONUNIFORM_LANE) { + sum = nir_reduce(&b, sum, .reduction_op = nir_op_iadd); + } else if (kind == DESC_NONUNIFORM_SUBGROUP) { + nir_barrier(&b, .execution_scope = SCOPE_WORKGROUP, + .memory_scope = SCOPE_WORKGROUP, + .memory_semantics = NIR_MEMORY_ACQ_REL, + .memory_modes = nir_var_mem_shared); + } + + nir_store_global(&b, sum, out_ptr, .align_mul = 4); + + nir_def *iv_next = nir_iadd_imm(&b, iv, 1); + nir_block *latch = nir_cursor_current_block(b.cursor); + nir_phi_instr_add_src(iv_phi, latch, iv_next); + b.cursor = nir_before_block(header); + nir_builder_instr_insert(&b, &iv_phi->instr); + nir_pop_loop(&b, loop); + + nir_validate_shader(b.shader, "before aligned robust loop"); + + bool changed = hk_nir_g16_version_aligned_robust_loops( + b.shader, VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT, + VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_DISABLED_EXT); + + nir_validate_shader(b.shader, "after aligned robust loop"); + + unsigned top_ifs = 0, top_loops = 0; + unsigned bounded_loads = 0, unbounded_loads = 0; + nir_function_impl *impl = nir_shader_get_entrypoint(b.shader); + foreach_list_typed(nir_cf_node, node, node, &impl->body) { + if (node->type == nir_cf_node_if) + top_ifs++; + else if (node->type == nir_cf_node_loop) + top_loops++; + } + nir_foreach_block(blk, impl) { + nir_foreach_instr(instr, blk) { + if (instr->type != nir_instr_type_intrinsic) + continue; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + if (intr->intrinsic == nir_intrinsic_load_global_bounded) + bounded_loads++; + else if (intr->intrinsic == nir_intrinsic_load_global) + unbounded_loads++; + } + } + + bool ok = true; + if (changed != expect_versioned) { + fprintf(stderr, "FAIL %s: changed=%d expected=%d\n", name, changed, + expect_versioned); + ok = false; + } + if (expect_versioned) { + if (top_ifs != 1 || top_loops != 0 || unbounded_loads != 5 || + bounded_loads != 5) { + fprintf(stderr, + "FAIL %s: expected versioned fast+slow loops " + "(top_ifs=%u top_loops=%u unbounded=%u bounded=%u)\n", + name, top_ifs, top_loops, unbounded_loads, bounded_loads); + ok = false; + } + } else { + if (top_ifs != 0 || top_loops != 1 || unbounded_loads != 0 || + bounded_loads != 5) { + fprintf(stderr, + "FAIL %s: expected intact loop " + "(top_ifs=%u top_loops=%u unbounded=%u bounded=%u)\n", + name, top_ifs, top_loops, unbounded_loads, bounded_loads); + ok = false; + } + } + + ralloc_free(b.shader); + return ok; +} + +int +main(void) +{ + bool ok = true; + ok &= run_case("uniform_descriptor_versions_loop", DESC_UNIFORM_CONST, true); + ok &= run_case("nonuniform_lane_descriptor_intact", DESC_NONUNIFORM_LANE, + false); + ok &= run_case("nonuniform_subgroup_descriptor_intact", + DESC_NONUNIFORM_SUBGROUP, false); + if (!ok) + return 1; + printf("hk_aligned_robust_loop_test: PASS (3/3 cases)\n"); + return 0; +} From 408af606be87735ddd9ea29399c5a4573b6ed228 Mon Sep 17 00:00:00 2001 From: Dylan Ironside Date: Tue, 1 Dec 2026 08:12:38 -0600 Subject: [PATCH 2/6] hk,agx: prove uniform compute loop bounds and fold AGX3 bitfield slices Extend g16_version_aligned_robust_loops() on G16G with g16_try_version_bounded_loop() for fixed-workgroup compute loops with workgroup-uniform affine trip bounds. Tighten g16_build_ub64() for high-bit alignment masks in nir_op_iand so aligned masks (e.g. 0xffffffe0) intersect with the operand upper bound instead of saturating to the raw mask, and deduplicate dominated (base, const) buffer-end and nowrap checks in the pre-loop guard prologue. Add hk_bounded_loop_test covering dynamic alignment masks, exact-bound vs 1-byte-short guards, and 32-bit wrap rejection. Add agx_nir_opt_bitfield_slices() on AGX3, fold split_lo(zext_16_to_32(x16)) -> x16 in agx_opt_collect_split(), and widen f16 MOV_IMM sources of f32 FADD/FMUL/FFMA to exact f32 before agx_opt_promote_constants() on AGX3B. Signed-off-by: Dylan Ironside --- src/asahi/compiler/agx_compile.c | 39 + src/asahi/compiler/agx_nir.h | 1 + .../compiler/agx_nir_lower_shared_bitsize.c | 274 ++++ src/asahi/compiler/agx_optimizer.c | 17 + .../test/test-shared-byte-offsets.cpp | 145 ++ src/asahi/vulkan/hk_shader.c | 1415 +++++++++++++++++ src/asahi/vulkan/meson.build | 7 + src/asahi/vulkan/tests/test-hk-bounded-loop.c | 223 +++ 8 files changed, 2121 insertions(+) create mode 100644 src/asahi/vulkan/tests/test-hk-bounded-loop.c diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index a39b4a5011f1..8b7418535d48 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -16448,6 +16448,44 @@ agx_compile_function_nir(nir_shader *nir, nir_function_impl *impl, AGX_PASS(ctx, agx_opt_pack_bool_or_branch); AGX_PASS(ctx, agx_opt_compact_constants); + /* On AGX3B, f32 FADD/FMUL/FFMA has no native mixed f16+f32 form (later + * widened via fadd #-0.0), whereas aligned f32 uniforms fold directly + * into FADD/FMUL/FFMA. Widen f16 constant sources to exact f32 before + * constant promotion so values like -32.0h promote as f32 uniforms. */ + if (key->dev.encoding == AGX_ISA_ENCODING_AGX3B) { + agx_instr **defs = calloc(ctx->alloc, sizeof(agx_instr *)); + if (defs) { + agx_foreach_instr_global(ctx, I) { + agx_foreach_ssa_dest(I, d) + defs[I->dest[d].value] = I; + } + agx_foreach_instr_global(ctx, I) { + if ((I->op != AGX_OPCODE_FADD && I->op != AGX_OPCODE_FMUL && + I->op != AGX_OPCODE_FFMA) || + I->nr_dests != 1 || I->dest[0].size != AGX_SIZE_32 || + agx_channels(I->dest[0]) != 1) + continue; + agx_foreach_src(I, s) { + if (I->src[s].type != AGX_INDEX_NORMAL || + I->src[s].size != AGX_SIZE_16) + continue; + agx_instr *def = defs[I->src[s].value]; + if (!def || def->op != AGX_OPCODE_MOV_IMM || + def->dest[0].size != AGX_SIZE_16) + continue; + float fval = _mesa_half_to_float((uint16_t)def->imm); + if (I->src[s].abs) + fval = fabsf(fval); + if (I->src[s].neg) + fval = -fval; + agx_builder b = agx_init_builder(ctx, agx_before_instr(I)); + I->src[s] = agx_mov_imm(&b, 32, fui(fval)); + } + } + free(defs); + } + } + /* After inlining constants, promote what's left */ if (key->promote_constants && !key->secondary && !(agx_compiler_debug & AGX_DBG_NOPROMOTE)) { @@ -21184,6 +21222,7 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, NIR_PASS(post_opt_progress, nir, agx_nir_hoist_loop_invariant_guard_bits); if (is_agx3) { + NIR_PASS(post_opt_progress, nir, agx_nir_opt_bitfield_slices); if (nir->info.shared_size > 0) NIR_PASS(post_opt_progress, nir, agx_nir_opt_shared_byte_offsets); bool cse_progress = false; diff --git a/src/asahi/compiler/agx_nir.h b/src/asahi/compiler/agx_nir.h index 57b2424fe41c..d252271457b4 100644 --- a/src/asahi/compiler/agx_nir.h +++ b/src/asahi/compiler/agx_nir.h @@ -121,6 +121,7 @@ bool agx_nir_opt_shared_byte_offsets(struct nir_shader *s); * chips with AGX_CAP_FOLD_SHARED_OFFSETS (four 32-bit elements per unit). */ #define G13X_I32_SHARED_INDEX_UNIT_B 16 bool agx_nir_opt_g13x_shared_offsets(struct nir_shader *s); +bool agx_nir_opt_bitfield_slices(struct nir_shader *s); bool agx_nir_reassociate_loop_invariant_eq(struct nir_shader *shader); bool agx_nir_opt_licm(struct nir_shader *shader, unsigned budget, bool cap_rt_compute); diff --git a/src/asahi/compiler/agx_nir_lower_shared_bitsize.c b/src/asahi/compiler/agx_nir_lower_shared_bitsize.c index 610cab9a8612..6e76c7330cd8 100644 --- a/src/asahi/compiler/agx_nir_lower_shared_bitsize.c +++ b/src/asahi/compiler/agx_nir_lower_shared_bitsize.c @@ -820,3 +820,277 @@ agx_nir_opt_shared_byte_offsets(nir_shader *shader) _mesa_hash_table_destroy(ranges, NULL); return progress; } + +struct agx_bit_slice { + bool valid; + nir_scalar base; + unsigned src_off; + unsigned width; + unsigned dst_off; +}; + +static struct agx_bit_slice +parse_bit_slice(nir_scalar s) +{ + struct agx_bit_slice out = {.valid = false}; + if (s.def->bit_size != 32 || !nir_scalar_is_alu(s)) + return out; + + unsigned dst_off = 0; + if (nir_scalar_alu_op(s) == nir_op_ishl) { + nir_scalar sh = nir_scalar_chase_alu_src(s, 1); + if (!nir_scalar_is_const(sh)) + return out; + dst_off = (unsigned)(nir_scalar_as_uint(sh) & 31); + if (dst_off == 0) + return out; + s = nir_scalar_chase_alu_src(s, 0); + if (!nir_scalar_is_alu(s)) + return out; + } + + nir_op op = nir_scalar_alu_op(s); + if (op == nir_op_ushr) { + nir_scalar sh = nir_scalar_chase_alu_src(s, 1); + if (!nir_scalar_is_const(sh)) + return out; + unsigned k = (unsigned)(nir_scalar_as_uint(sh) & 31); + if (k == 0 || k >= 32) + return out; + unsigned w = 32 - k; + if (dst_off + w > 32) + return out; + return (struct agx_bit_slice){ + .valid = true, + .base = nir_scalar_chase_alu_src(s, 0), + .src_off = k, + .width = w, + .dst_off = dst_off, + }; + } + if (op == nir_op_ubitfield_extract) { + nir_scalar off = nir_scalar_chase_alu_src(s, 1); + nir_scalar bits = nir_scalar_chase_alu_src(s, 2); + if (!nir_scalar_is_const(off) || !nir_scalar_is_const(bits)) + return out; + unsigned o = (unsigned)nir_scalar_as_uint(off); + unsigned w = (unsigned)nir_scalar_as_uint(bits); + if (o >= 32 || w == 0 || o + w > 32 || dst_off + w > 32) + return out; + return (struct agx_bit_slice){ + .valid = true, + .base = nir_scalar_chase_alu_src(s, 0), + .src_off = o, + .width = w, + .dst_off = dst_off, + }; + } + if (op == nir_op_iand) { + nir_scalar s0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(s, 1); + nir_scalar base, c; + if (nir_scalar_is_const(s1) && !nir_scalar_is_const(s0)) { + base = s0; + c = s1; + } else if (nir_scalar_is_const(s0) && !nir_scalar_is_const(s1)) { + base = s1; + c = s0; + } else { + return out; + } + uint64_t mask = nir_scalar_as_uint(c); + if (mask == 0 || mask >= UINT32_MAX || + !util_is_power_of_two_nonzero(mask + 1)) + return out; + unsigned w = ffsll((long long)(mask + 1)) - 1; + if (w == 0 || dst_off + w > 32) + return out; + return (struct agx_bit_slice){ + .valid = true, + .base = base, + .src_off = 0, + .width = w, + .dst_off = dst_off, + }; + } + return out; +} + +static bool +collect_assoc_terms(nir_scalar s, nir_op op, unsigned depth, + nir_scalar *terms, unsigned *count, unsigned max_terms) +{ + if (depth > 0 && nir_scalar_is_alu(s) && nir_scalar_alu_op(s) == op) { + return collect_assoc_terms(nir_scalar_chase_alu_src(s, 0), op, depth - 1, + terms, count, max_terms) && + collect_assoc_terms(nir_scalar_chase_alu_src(s, 1), op, depth - 1, + terms, count, max_terms); + } + if (*count >= max_terms) + return false; + terms[(*count)++] = s; + return true; +} + +static nir_def * +emit_bit_slice(nir_builder *b, const struct agx_bit_slice *sl) +{ + nir_def *base = nir_mov_scalar(b, sl->base); + nir_def *v; + if (sl->src_off + sl->width == 32 && sl->src_off > 0) + v = nir_ushr_imm(b, base, sl->src_off); + else if (sl->src_off == 0 && sl->width < 32) + v = nir_iand_imm(b, base, (uint32_t)((UINT64_C(1) << sl->width) - 1)); + else if (sl->src_off == 0 && sl->width == 32) + v = base; + else + v = nir_ubitfield_extract_imm(b, base, sl->src_off, sl->width); + return sl->dst_off ? nir_ishl_imm(b, v, sl->dst_off) : v; +} + +static bool +opt_bitfield_slice_instr(nir_builder *b, nir_alu_instr *alu, void *data) +{ + struct hash_table *ranges = data; + if (alu->def.bit_size != 32 || alu->def.num_components != 1) + return false; + + b->cursor = nir_before_instr(&alu->instr); + + /* 1. ushr(iand(x, mask), shift) -> ubitfield_extract(x, shift, width), + * and ushr(ishl(x, a), c) -> ishl(x, a - c) when x << a cannot wrap. */ + if (alu->op == nir_op_ushr) { + nir_scalar sh = nir_scalar_resolved(alu->src[1].src.ssa, alu->src[1].swizzle[0]); + if (!nir_scalar_is_const(sh)) + return false; + unsigned k = (unsigned)(nir_scalar_as_uint(sh) & 31); + if (k == 0 || k >= 32) + return false; + + nir_scalar src0 = + nir_scalar_resolved(alu->src[0].src.ssa, alu->src[0].swizzle[0]); + if (!nir_scalar_is_alu(src0)) + return false; + + if (nir_scalar_alu_op(src0) == nir_op_iand) { + nir_scalar a0 = nir_scalar_chase_alu_src(src0, 0); + nir_scalar a1 = nir_scalar_chase_alu_src(src0, 1); + nir_scalar x, cm; + if (nir_scalar_is_const(a1) && !nir_scalar_is_const(a0)) { + x = a0; + cm = a1; + } else if (nir_scalar_is_const(a0) && !nir_scalar_is_const(a1)) { + x = a1; + cm = a0; + } else { + return false; + } + uint64_t shifted = nir_scalar_as_uint(cm) >> k; + if (shifted == 0) { + nir_def_replace(&alu->def, nir_imm_int(b, 0)); + return true; + } + if (shifted < UINT32_MAX && util_is_power_of_two_nonzero(shifted + 1)) { + unsigned w = ffsll((long long)(shifted + 1)) - 1; + if (w > 0 && k + w <= 32) { + nir_def *rep = + nir_ubitfield_extract_imm(b, nir_mov_scalar(b, x), k, w); + nir_def_replace(&alu->def, rep); + return true; + } + } + } else if (nir_scalar_alu_op(src0) == nir_op_ishl) { + nir_scalar x = nir_scalar_chase_alu_src(src0, 0); + nir_scalar shl = nir_scalar_chase_alu_src(src0, 1); + if (nir_scalar_is_const(shl)) { + unsigned a = (unsigned)(nir_scalar_as_uint(shl) & 31); + if (a >= k && a < 32 && + nir_unsigned_upper_bound(b->shader, ranges, x) <= + (UINT32_MAX >> a)) { + nir_def *base = nir_mov_scalar(b, x); + nir_def *rep = a > k ? nir_ishl_imm(b, base, a - k) : base; + nir_def_replace(&alu->def, rep); + return true; + } + } + } + return false; + } + + /* 2. Merge adjacent bitfield slices in associative iadd / ior trees. */ + if (alu->op != nir_op_iadd && alu->op != nir_op_ior) + return false; + + nir_scalar terms[8]; + unsigned n = 0; + if (!collect_assoc_terms(nir_get_scalar(&alu->def, 0), alu->op, 4, terms, + &n, 8) || + n < 2) + return false; + + struct agx_bit_slice slices[8]; + bool alive[8]; + for (unsigned i = 0; i < n; i++) { + slices[i] = parse_bit_slice(terms[i]); + alive[i] = true; + } + + bool merged_any = false; + bool changed; + do { + changed = false; + for (unsigned i = 0; i < n && !changed; i++) { + if (!alive[i] || !slices[i].valid) + continue; + for (unsigned j = 0; j < n && !changed; j++) { + if (i == j || !alive[j] || !slices[j].valid) + continue; + if (slices[i].base.def != slices[j].base.def || + slices[i].base.comp != slices[j].base.comp) + continue; + /* Check if slice i sits immediately above slice j. */ + if (slices[i].src_off == slices[j].src_off + slices[j].width && + slices[i].dst_off == slices[j].dst_off + slices[j].width && + slices[j].dst_off + slices[j].width + slices[i].width <= 32) { + slices[j].width += slices[i].width; + alive[i] = false; + changed = true; + merged_any = true; + } + } + } + } while (changed); + + if (!merged_any) + return false; + + nir_def *acc = NULL; + for (unsigned i = 0; i < n; i++) { + if (!alive[i]) + continue; + nir_def *v = slices[i].valid ? emit_bit_slice(b, &slices[i]) + : nir_mov_scalar(b, terms[i]); + if (!acc) + acc = v; + else + acc = alu->op == nir_op_iadd ? nir_iadd(b, acc, v) : nir_ior(b, acc, v); + } + nir_def_replace(&alu->def, acc); + return true; +} + +bool +agx_nir_opt_bitfield_slices(nir_shader *shader) +{ + struct hash_table *ranges = _mesa_pointer_hash_table_create(NULL); + bool progress = false; + for (unsigned pass = 0; pass < 2; pass++) { + bool p = nir_shader_alu_pass(shader, opt_bitfield_slice_instr, + nir_metadata_control_flow, ranges); + progress |= p; + if (!p) + break; + } + _mesa_hash_table_destroy(ranges, NULL); + return progress; +} diff --git a/src/asahi/compiler/agx_optimizer.c b/src/asahi/compiler/agx_optimizer.c index 40131e7e137b..07a56d44c0d1 100644 --- a/src/asahi/compiler/agx_optimizer.c +++ b/src/asahi/compiler/agx_optimizer.c @@ -1171,6 +1171,23 @@ agx_opt_collect_split(agx_context *ctx) I->src[0].abs || I->src[0].neg) continue; agx_instr *collect = defs[I->src[0].value]; + /* split_lo(zext_16_to_32(x16)) == x16 (low 16 bits are unchanged). */ + if (collect && collect->op == AGX_OPCODE_MOV && collect->nr_dests == 1 && + collect->nr_srcs == 1 && !collect->saturate && + collect->dest[0].size == AGX_SIZE_32 && + agx_channels(collect->dest[0]) == 1 && + collect->src[0].type == AGX_INDEX_NORMAL && + collect->src[0].size == AGX_SIZE_16 && + agx_channels(collect->src[0]) == 1 && !collect->src[0].abs && + !collect->src[0].neg && !collect->src[0].memory && + I->nr_dests == 2 && I->src[0].size == AGX_SIZE_32 && + agx_channels(I->src[0]) == 1 && + I->dest[0].type == AGX_INDEX_NORMAL && + I->dest[0].size == AGX_SIZE_16 && agx_channels(I->dest[0]) == 1 && + agx_is_null(I->dest[1])) { + aliases[I->dest[0].value] = collect->src[0]; + continue; + } if (!collect || collect->op != AGX_OPCODE_COLLECT || collect->nr_dests != 1 || collect->saturate || collect->dest[0].memory || diff --git a/src/asahi/compiler/test/test-shared-byte-offsets.cpp b/src/asahi/compiler/test/test-shared-byte-offsets.cpp index e34532fc220b..669a6fdeaf6c 100644 --- a/src/asahi/compiler/test/test-shared-byte-offsets.cpp +++ b/src/asahi/compiler/test/test-shared-byte-offsets.cpp @@ -1289,3 +1289,148 @@ TEST(SharedByteOffsets, NestedImulIorImadshlBounds) nir_validate_shader(b.shader, "shared-imul-ior-imadshl result"); ralloc_free(b.shader); } + +/* ushr(iand(x, mask), k) folds to ubitfield_extract and adjacent slices merge. */ +TEST(SharedByteOffsets, BitfieldSlicesMaskShiftAndMerge) +{ + nir_builder b = workgroup_shader("bitfield-slices-merge"); + nir_def *x = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .range = 4); + + nir_def *lo = nir_iand_imm(&b, x, 0x3); + nir_def *hi = nir_ishl_imm(&b, nir_ushr_imm(&b, nir_iand_imm(&b, x, 0xc), 2), 2); + nir_def *merged = nir_ior(&b, lo, hi); + nir_store_global(&b, merged, nir_imm_int64(&b, 0), .align_mul = 4); + + EXPECT_TRUE(agx_nir_opt_bitfield_slices(b.shader)); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "bitfield-slices-merge result"); + + unsigned iors = 0, iands = 0, ushrs = 0; + nir_foreach_block(block, b.impl) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_alu) + continue; + nir_alu_instr *alu = nir_instr_as_alu(instr); + if (alu->op == nir_op_ior) + iors++; + else if (alu->op == nir_op_iand) + iands++; + else if (alu->op == nir_op_ushr) + ushrs++; + } + } + EXPECT_EQ(iors, 0u); + EXPECT_EQ(ushrs, 0u); + EXPECT_EQ(iands, 1u); + ralloc_free(b.shader); +} + +/* ushr(ishl(x, a), k) cancels only when x << a cannot wrap 32 bits. */ +TEST(SharedByteOffsets, BitfieldSlicesWrapGuard) +{ + nir_builder b = workgroup_shader("bitfield-slices-wrap"); + nir_def *x = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .range = 4); + nir_def *bounded = nir_iand_imm(&b, x, 0xff); + nir_def *safe = nir_ushr_imm(&b, nir_ishl_imm(&b, bounded, 4), 2); + nir_def *unsafe = nir_ushr_imm(&b, nir_ishl_imm(&b, x, 4), 2); + nir_store_global(&b, nir_iadd(&b, safe, unsafe), nir_imm_int64(&b, 0), + .align_mul = 4); + + EXPECT_TRUE(agx_nir_opt_bitfield_slices(b.shader)); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "bitfield-slices-wrap result"); + + unsigned ushrs = 0; + nir_foreach_block(block, b.impl) { + nir_foreach_instr(instr, block) { + if (instr->type == nir_instr_type_alu && + nir_instr_as_alu(instr)->op == nir_op_ushr) + ushrs++; + } + } + EXPECT_EQ(ushrs, 1u); + ralloc_free(b.shader); +} + +static uint32_t +eval_u32_nir(nir_def *def, const uint32_t *push_vals) +{ + nir_instr *instr = nir_def_instr(def); + if (instr->type == nir_instr_type_load_const) + return nir_instr_as_load_const(instr)->value[0].u32; + if (instr->type == nir_instr_type_intrinsic) { + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + EXPECT_EQ(intr->intrinsic, nir_intrinsic_load_push_constant); + uint32_t off = nir_src_as_uint(intr->src[0]); + return push_vals[off / 4]; + } + EXPECT_EQ(instr->type, nir_instr_type_alu); + nir_alu_instr *alu = nir_instr_as_alu(instr); + auto src = [&](unsigned i) { + return eval_u32_nir(alu->src[i].src.ssa, push_vals); + }; + switch (alu->op) { + case nir_op_mov: + return src(0); + case nir_op_iadd: + return src(0) + src(1); + case nir_op_ior: + return src(0) | src(1); + case nir_op_iand: + return src(0) & src(1); + case nir_op_ishl: + return src(0) << (src(1) & 31u); + case nir_op_ushr: + return src(0) >> (src(1) & 31u); + case nir_op_ubitfield_extract: { + uint32_t v = src(0), off = src(1), bits = src(2); + return bits >= 32 ? v : ((v >> off) & ((1u << bits) - 1u)); + } + case nir_op_imadshl_agx: + return src(0) * src(1) + (src(2) << (src(3) & 31u)); + default: + ADD_FAILURE() << "unexpected nir op " << nir_op_infos[alu->op].name; + return 0; + } +} + +/* Over-budget (> 8 terms) associative tree with mergeable slices must abandon + * the rewrite instead of dropping operands beyond the 8-term buffer. */ +TEST(SharedByteOffsets, BitfieldSlicesOverBudgetPreservesValue) +{ + nir_builder b = workgroup_shader("bitfield-slices-over-budget-8"); + nir_def *x = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .range = 4); + nir_def *t[7]; + for (unsigned i = 0; i < 7; i++) + t[i] = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, (i + 1) * 4), + .range = 4); + + /* 10-term tree (9 in left subtree + t7 at root, exceeding the 8-term + * collector): s0 sits in l0 and s1 sits in l1 so no proper subtree holds + * both slices. */ + nir_def *s0 = nir_iand_imm(&b, x, 0xfu); + nir_def *s1 = nir_ishl_imm(&b, nir_ubitfield_extract_imm(&b, x, 4, 4), 4); + nir_def *t7 = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 32), .range = 4); + nir_def *l0 = nir_iadd(&b, nir_iadd(&b, s0, t[0]), nir_iadd(&b, t[1], t[2])); + nir_def *l1 = + nir_iadd(&b, nir_iadd(&b, nir_iadd(&b, t[3], t[4]), nir_iadd(&b, t[5], s1)), + t[6]); + nir_def *root = nir_iadd(&b, nir_iadd(&b, l0, l1), t7); + nir_intrinsic_instr *st = + nir_store_global(&b, root, nir_imm_int64(&b, 0), .align_mul = 4); + + uint32_t vals[9] = { + 0x12345678u, /* x */ + 0x00010001u, 0x00020003u, 0x00040005u, 0x00060007u, 0x00080009u, + 0x000a000bu, 0x000c000du, 0x000e000fu, + }; + const uint32_t expected = eval_u32_nir(st->src[0].ssa, vals); + + EXPECT_FALSE(agx_nir_opt_bitfield_slices(b.shader)); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "bitfield-slices-over-budget-8 result"); + + const uint32_t actual = eval_u32_nir(st->src[0].ssa, vals); + EXPECT_EQ(actual, expected); + ralloc_free(b.shader); +} diff --git a/src/asahi/vulkan/hk_shader.c b/src/asahi/vulkan/hk_shader.c index 86793849b63d..2a5a21c0344d 100644 --- a/src/asahi/vulkan/hk_shader.c +++ b/src/asahi/vulkan/hk_shader.c @@ -2323,6 +2323,1415 @@ g16_def_escapes_loop_cb(nir_def *def, void *state) return true; } +/* + * G16G (no DRM_ASAHI_FEATURE_SOFT_FAULTS): workgroup-uniform pre-loop bounds + * proving for compute loops with affine induction variables. + * + * When a compute shader has a fixed workgroup size and a loop's trip count is + * bounded by a workgroup-uniform limit, every load_global_bounded offset built + * from workgroup-uniform values, bounded thread/subgroup IDs, and affine loop + * phis has a workgroup-uniform 64-bit upper bound computable once before the + * loop. Guarding a cloned fast loop with (no 32-bit unsigned wrap) && + * (max_end_u64 <= bound) per descriptor lets every proved load in the fast + * loop lower to an unbounded vectorizable global load with zero in-loop bounds + * selects, while edge workgroups, unaligned/tiny buffers, and null descriptors + * take the unmodified robust fallback loop. + */ +struct g16_iv_phi { + nir_phi_instr *phi; + nir_def *init; + nir_def *next; + uint32_t step; + nir_def *ub64; +}; + +struct g16_ub_ctx { + nir_shader *nir; + const struct set *loop_blocks; + struct g16_iv_phi ivs[8]; + unsigned num_ivs; + struct hash_table *u_cache; + struct hash_table *ub_cache; + struct set *nowrap_checked; + struct util_dynarray pending_nowrap; + nir_def *valid_cond; + bool failed; +}; + +static bool +g16_is_wg_uniform(nir_def *def, const struct set *loop_blocks, unsigned depth) +{ + if (depth > 32) + return false; + + const bool in_loop = _mesa_set_search(loop_blocks, nir_def_block(def)) != NULL; + nir_instr *instr = nir_def_instr(def); + switch (instr->type) { + case nir_instr_type_load_const: + return true; + case nir_instr_type_intrinsic: { + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + switch (intr->intrinsic) { + case nir_intrinsic_load_workgroup_id: + case nir_intrinsic_load_num_workgroups: + case nir_intrinsic_load_root_agx: + case nir_intrinsic_load_descriptor_set_agx: + case nir_intrinsic_load_preamble: + return true; + case nir_intrinsic_load_push_constant: + return g16_is_wg_uniform(intr->src[0].ssa, loop_blocks, depth + 1); + case nir_intrinsic_load_ubo: + case nir_intrinsic_load_global_constant_offset: + if (in_loop && + intr->intrinsic == nir_intrinsic_load_global_constant_offset && + !(nir_intrinsic_access(intr) & ACCESS_CAN_SPECULATE)) + return false; + return g16_is_wg_uniform(intr->src[0].ssa, loop_blocks, depth + 1) && + g16_is_wg_uniform(intr->src[1].ssa, loop_blocks, depth + 1); + case nir_intrinsic_load_global_constant: + if (in_loop && !(nir_intrinsic_access(intr) & ACCESS_CAN_SPECULATE)) + return false; + return g16_is_wg_uniform(intr->src[0].ssa, loop_blocks, depth + 1); + case nir_intrinsic_load_global_constant_bounded: + if (in_loop) + return false; + return g16_is_wg_uniform(intr->src[0].ssa, loop_blocks, depth + 1) && + g16_is_wg_uniform(intr->src[1].ssa, loop_blocks, depth + 1) && + g16_is_wg_uniform(intr->src[2].ssa, loop_blocks, depth + 1); + default: + return false; + } + } + case nir_instr_type_alu: { + nir_alu_instr *alu = nir_instr_as_alu(instr); + if (in_loop) { + switch (alu->op) { + case nir_op_idiv: + case nir_op_udiv: + case nir_op_imod: + case nir_op_irem: + case nir_op_umod: + return false; + default: + break; + } + } + unsigned nsrc = nir_op_infos[alu->op].num_inputs; + for (unsigned i = 0; i < nsrc; i++) { + if (!g16_is_wg_uniform(alu->src[i].src.ssa, loop_blocks, depth + 1)) + return false; + } + return true; + } + default: + return false; + } +} + +static nir_def * +g16_emit_wg_uniform(nir_builder *b, nir_def *def, struct g16_ub_ctx *ctx) +{ + if (!_mesa_set_search(ctx->loop_blocks, nir_def_block(def))) + return def; + + struct hash_entry *he = _mesa_hash_table_search(ctx->u_cache, def); + if (he) + return he->data; + + nir_instr *instr = nir_def_instr(def); + nir_def *res = NULL; + if (instr->type == nir_instr_type_load_const) { + nir_load_const_instr *lc = nir_instr_as_load_const(instr); + res = nir_build_imm(b, lc->def.num_components, lc->def.bit_size, + lc->value); + } else if (instr->type == nir_instr_type_intrinsic) { + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + nir_intrinsic_instr *clone = + nir_intrinsic_instr_create(b->shader, intr->intrinsic); + clone->num_components = intr->num_components; + memcpy(clone->const_index, intr->const_index, sizeof(intr->const_index)); + nir_def_init(&clone->instr, &clone->def, intr->def.num_components, + intr->def.bit_size); + unsigned nsrc = nir_intrinsic_infos[intr->intrinsic].num_srcs; + for (unsigned i = 0; i < nsrc; i++) { + nir_def *s = g16_emit_wg_uniform(b, intr->src[i].ssa, ctx); + if (!s) + return NULL; + clone->src[i] = nir_src_for_ssa(s); + } + nir_builder_instr_insert(b, &clone->instr); + res = &clone->def; + } else if (instr->type == nir_instr_type_alu) { + nir_alu_instr *alu = nir_instr_as_alu(instr); + nir_alu_instr *clone = nir_alu_instr_create(b->shader, alu->op); + clone->fp_math_ctrl = alu->fp_math_ctrl; + clone->no_signed_wrap = alu->no_signed_wrap; + clone->no_unsigned_wrap = alu->no_unsigned_wrap; + nir_def_init(&clone->instr, &clone->def, alu->def.num_components, + alu->def.bit_size); + unsigned nsrc = nir_op_infos[alu->op].num_inputs; + for (unsigned i = 0; i < nsrc; i++) { + nir_def *s = g16_emit_wg_uniform(b, alu->src[i].src.ssa, ctx); + if (!s) + return NULL; + clone->src[i].src = nir_src_for_ssa(s); + memcpy(clone->src[i].swizzle, alu->src[i].swizzle, + sizeof(alu->src[i].swizzle)); + } + nir_builder_instr_insert(b, &clone->instr); + res = &clone->def; + } + + if (res) + _mesa_hash_table_insert(ctx->u_cache, def, res); + return res; +} + +static void +g16_and_cond(nir_builder *b, struct g16_ub_ctx *ctx, nir_def *cond) +{ + if (nir_src_is_const(nir_src_for_ssa(cond))) { + if (!nir_src_as_bool(nir_src_for_ssa(cond))) + ctx->failed = true; + return; + } + ctx->valid_cond = + ctx->valid_cond ? nir_iand(b, ctx->valid_cond, cond) : cond; +} + +static bool +g16_const_u64(nir_def *d, uint64_t *out) +{ + nir_scalar s = nir_scalar_resolved(d, 0); + if (!nir_scalar_is_const(s)) + return false; + *out = nir_scalar_as_uint(s); + return true; +} + +static nir_def * +g16_u64_strip_const(nir_def *v, uint64_t *const_out) +{ + uint64_t total = 0; + for (unsigned iter = 0; iter < 8; iter++) { + uint64_t cv; + if (g16_const_u64(v, &cv)) { + *const_out = total + cv; + return NULL; + } + nir_scalar s = nir_scalar_resolved(v, 0); + if (!nir_scalar_is_alu(s) || nir_scalar_alu_op(s) != nir_op_iadd) + break; + nir_scalar s0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_const(s1)) { + uint64_t c = nir_scalar_as_uint(s1); + if (total > UINT64_MAX - c) + break; + total += c; + v = s0.def; + } else if (nir_scalar_is_const(s0)) { + uint64_t c = nir_scalar_as_uint(s0); + if (total > UINT64_MAX - c) + break; + total += c; + v = s1.def; + } else { + break; + } + } + *const_out = total; + return v; +} + +static nir_def * +g16_u64_add(nir_builder *b, nir_def *x, nir_def *y) +{ + uint64_t cx, cy; + if (g16_const_u64(x, &cx) && g16_const_u64(y, &cy)) + return nir_imm_int64(b, cx + cy); + if (g16_const_u64(y, &cy)) { + if (cy == 0) + return x; + uint64_t bx = 0; + nir_def *base = g16_u64_strip_const(x, &bx); + if (!base) + return nir_imm_int64(b, bx + cy); + if (bx > 0 && bx <= UINT64_MAX - cy) + return nir_iadd_imm(b, base, bx + cy); + } + if (g16_const_u64(x, &cx)) { + if (cx == 0) + return y; + uint64_t by = 0; + nir_def *base = g16_u64_strip_const(y, &by); + if (!base) + return nir_imm_int64(b, by + cx); + if (by > 0 && by <= UINT64_MAX - cx) + return nir_iadd_imm(b, base, by + cx); + } + return nir_iadd(b, x, y); +} + +static nir_def * +g16_u64_mul(nir_builder *b, nir_def *x, nir_def *y) +{ + uint64_t cx, cy; + if (g16_const_u64(x, &cx) && g16_const_u64(y, &cy)) + return nir_imm_int64(b, cx * cy); + if (g16_const_u64(y, &cy)) { + if (cy == 0) return nir_imm_int64(b, 0); + if (cy == 1) return x; + } + if (g16_const_u64(x, &cx)) { + if (cx == 0) return nir_imm_int64(b, 0); + if (cx == 1) return y; + } + return nir_imul(b, x, y); +} + +static nir_def * +g16_u64_shl(nir_builder *b, nir_def *x, unsigned k) +{ + if (k == 0) + return x; + uint64_t cx; + if (g16_const_u64(x, &cx)) + return nir_imm_int64(b, cx << k); + return nir_ishl_imm(b, x, k); +} + +static nir_def * +g16_u64_shr(nir_builder *b, nir_def *x, unsigned k) +{ + if (k == 0) + return x; + uint64_t cx; + if (g16_const_u64(x, &cx)) + return nir_imm_int64(b, cx >> k); + return nir_ushr_imm(b, x, k); +} + +static nir_def * +g16_u64_min(nir_builder *b, nir_def *x, nir_def *y) +{ + uint64_t cx, cy; + if (g16_const_u64(x, &cx) && g16_const_u64(y, &cy)) + return nir_imm_int64(b, MIN2(cx, cy)); + if (x == y) + return x; + return nir_umin(b, x, y); +} + +static nir_def * +g16_u64_max(nir_builder *b, nir_def *x, nir_def *y) +{ + uint64_t cx, cy; + if (g16_const_u64(x, &cx) && g16_const_u64(y, &cy)) + return nir_imm_int64(b, MAX2(cx, cy)); + if (x == y) + return x; + uint64_t bx = 0, by = 0; + nir_def *rx = g16_u64_strip_const(x, &bx); + nir_def *ry = g16_u64_strip_const(y, &by); + if (rx && rx == ry) + return bx >= by ? x : y; + return nir_umax(b, x, y); +} + +static bool +g16_u64_is_u32_bounded_rec(nir_def *v64, const struct g16_ub_ctx *ctx, + unsigned depth, unsigned *budget) +{ + if (depth > 8 || *budget == 0) + return false; + (*budget)--; + uint64_t cv; + if (g16_const_u64(v64, &cv)) + return cv <= UINT32_MAX; + if (ctx && ctx->nowrap_checked && _mesa_set_search(ctx->nowrap_checked, v64)) + return true; + nir_scalar s = nir_scalar_resolved(v64, 0); + if (!nir_scalar_is_alu(s)) + return false; + nir_op op = nir_scalar_alu_op(s); + if (op == nir_op_u2u64 && nir_scalar_chase_alu_src(s, 0).def->bit_size <= 32) + return true; + if (op == nir_op_ushr || op == nir_op_udiv) + return g16_u64_is_u32_bounded_rec(nir_scalar_chase_alu_src(s, 0).def, ctx, + depth + 1, budget); + if (op == nir_op_umin) + return g16_u64_is_u32_bounded_rec(nir_scalar_chase_alu_src(s, 0).def, ctx, + depth + 1, budget) || + g16_u64_is_u32_bounded_rec(nir_scalar_chase_alu_src(s, 1).def, ctx, + depth + 1, budget); + return false; +} + +static bool +g16_u64_is_u32_bounded(nir_def *v64, const struct g16_ub_ctx *ctx, unsigned depth) +{ + unsigned budget = 32; + return g16_u64_is_u32_bounded_rec(v64, ctx, depth, &budget); +} + +/* Returns true if hi >= lo holds mathematically for all unsigned 64-bit inputs + * (assuming no 64-bit wrap on hi's subexpressions, which is enforced before + * emitting the checks). Strictly bounded by *budget to stay O(1) on deep DAGs. */ +static bool +g16_u64_dominates_rec(nir_def *hi, nir_def *lo, unsigned depth, unsigned *budget) +{ + if (hi == lo) + return true; + uint64_t ch, cl; + if (g16_const_u64(hi, &ch) && g16_const_u64(lo, &cl)) + return ch >= cl; + if (depth > 8 || *budget == 0) + return false; + (*budget)--; + + uint64_t bh = 0, bl = 0; + nir_def *rh = g16_u64_strip_const(hi, &bh); + nir_def *rl = g16_u64_strip_const(lo, &bl); + if (rh && rl && rh == rl) + return bh >= bl; + if (rh && rl && bh >= bl && (bh > 0 || bl > 0) && + g16_u64_dominates_rec(rh, rl, depth + 1, budget)) + return true; + + nir_scalar sh = nir_scalar_resolved(hi, 0); + nir_scalar sl = nir_scalar_resolved(lo, 0); + if (nir_scalar_is_alu(sh) && nir_scalar_alu_op(sh) == nir_op_iadd) { + nir_def *h0 = nir_scalar_chase_alu_src(sh, 0).def; + nir_def *h1 = nir_scalar_chase_alu_src(sh, 1).def; + if (g16_u64_dominates_rec(h0, lo, depth + 1, budget) || + g16_u64_dominates_rec(h1, lo, depth + 1, budget)) + return true; + } + if (!nir_scalar_is_alu(sh) || !nir_scalar_is_alu(sl)) + return false; + nir_op oph = nir_scalar_alu_op(sh); + nir_op opl = nir_scalar_alu_op(sl); + if (oph != opl) + return false; + + switch (oph) { + case nir_op_iadd: + case nir_op_imul: { + nir_def *h0 = nir_scalar_chase_alu_src(sh, 0).def; + nir_def *h1 = nir_scalar_chase_alu_src(sh, 1).def; + nir_def *l0 = nir_scalar_chase_alu_src(sl, 0).def; + nir_def *l1 = nir_scalar_chase_alu_src(sl, 1).def; + return (g16_u64_dominates_rec(h0, l0, depth + 1, budget) && + g16_u64_dominates_rec(h1, l1, depth + 1, budget)) || + (g16_u64_dominates_rec(h0, l1, depth + 1, budget) && + g16_u64_dominates_rec(h1, l0, depth + 1, budget)); + } + case nir_op_ushr: + case nir_op_ishl: + case nir_op_udiv: { + nir_scalar hk = nir_scalar_chase_alu_src(sh, 1); + nir_scalar lk = nir_scalar_chase_alu_src(sl, 1); + if (nir_scalar_is_const(hk) && nir_scalar_is_const(lk) && + nir_scalar_as_uint(hk) == nir_scalar_as_uint(lk)) { + return g16_u64_dominates_rec(nir_scalar_chase_alu_src(sh, 0).def, + nir_scalar_chase_alu_src(sl, 0).def, + depth + 1, budget); + } + return false; + } + default: + return false; + } +} + +static bool +g16_u64_dominates(nir_def *hi, nir_def *lo, unsigned depth) +{ + unsigned budget = 64; + return g16_u64_dominates_rec(hi, lo, depth, &budget); +} + +static void +g16_check_u32_no_wrap(nir_builder *b, struct g16_ub_ctx *ctx, nir_def *v64) +{ + uint64_t cv; + if (g16_const_u64(v64, &cv)) { + if (cv > UINT32_MAX) + ctx->failed = true; + return; + } + if (g16_u64_is_u32_bounded(v64, ctx, 0)) + return; + if (ctx->nowrap_checked) + _mesa_set_add(ctx->nowrap_checked, v64); + util_dynarray_append(&ctx->pending_nowrap, v64); +} + +static bool +g16_block_is_single_break(nir_block *blk) +{ + if (exec_list_is_empty(&blk->instr_list)) + return false; + nir_instr *first = nir_block_first_instr(blk); + nir_instr *last = nir_block_last_instr(blk); + return first == last && first->type == nir_instr_type_jump && + nir_instr_as_jump(first)->type == nir_jump_break; +} + +static bool +g16_block_is_empty(nir_block *blk) +{ + return exec_list_is_empty(&blk->instr_list); +} + +static bool +g16_match_break_if(nir_if *nif, struct g16_ub_ctx *ctx, bool bottom_tested, + unsigned *out_iv, nir_def **out_limit, bool *out_signed) +{ + nir_block *tb = nir_if_first_then_block(nif); + nir_block *eb = nir_if_first_else_block(nif); + if (tb != nir_if_last_then_block(nif) || eb != nir_if_last_else_block(nif)) + return false; + + bool break_on_true = false; + if (g16_block_is_single_break(tb) && g16_block_is_empty(eb)) + break_on_true = true; + else if (g16_block_is_empty(tb) && g16_block_is_single_break(eb)) + break_on_true = false; + else + return false; + + nir_scalar cond = nir_scalar_resolved(nif->condition.ssa, 0); + if (!nir_scalar_is_alu(cond)) + return false; + + nir_op op = nir_scalar_alu_op(cond); + if (op == nir_op_inot) { + break_on_true = !break_on_true; + cond = nir_scalar_chase_alu_src(cond, 0); + if (!nir_scalar_is_alu(cond)) + return false; + op = nir_scalar_alu_op(cond); + } + + /* Want "continue while iv < limit" (equivalently "break when iv >= limit"). */ + bool is_signed = false; + bool want_lt_on_continue = false; + bool swap_args = false; + if (!break_on_true) { + if (op == nir_op_ult) { + want_lt_on_continue = true; + } else if (op == nir_op_ilt) { + want_lt_on_continue = true; + is_signed = true; + } else { + return false; + } + } else { + if (op == nir_op_uge) { + want_lt_on_continue = true; + } else if (op == nir_op_ige) { + want_lt_on_continue = true; + is_signed = true; + } else if (op == nir_op_ult) { + want_lt_on_continue = true; + swap_args = true; + } else if (op == nir_op_ilt) { + want_lt_on_continue = true; + is_signed = true; + swap_args = true; + } else { + return false; + } + } + (void)want_lt_on_continue; + + nir_scalar lhs = nir_scalar_chase_alu_src(cond, swap_args ? 1 : 0); + nir_scalar rhs = nir_scalar_chase_alu_src(cond, swap_args ? 0 : 1); + if (lhs.def->bit_size != 32 || rhs.def->bit_size != 32 || + lhs.comp != 0 || rhs.comp != 0) + return false; + + /* If swapped (break when limit < iv => continue while iv <= limit), skip. */ + if (swap_args) + return false; + + for (unsigned i = 0; i < ctx->num_ivs; i++) { + nir_def *match = bottom_tested ? ctx->ivs[i].next : &ctx->ivs[i].phi->def; + if (lhs.def == match && + g16_is_wg_uniform(rhs.def, ctx->loop_blocks, 0)) { + *out_iv = i; + *out_limit = rhs.def; + *out_signed = is_signed; + return true; + } + } + return false; +} + +static nir_def * +g16_build_ub64(nir_builder *b, nir_scalar s, struct g16_ub_ctx *ctx, + unsigned depth) +{ + if (ctx->failed || depth > 14 || s.def->bit_size != 32) + return NULL; + + if (nir_scalar_is_const(s)) + return nir_imm_int64(b, nir_scalar_as_uint(s)); + + uintptr_t key = ((uintptr_t)s.def->index << 4) | (s.comp & 0xf); + struct hash_entry *he = _mesa_hash_table_search(ctx->ub_cache, (void *)key); + if (he) + return he->data; + + /* Check bounded affine loop phis. */ + for (unsigned i = 0; i < ctx->num_ivs; i++) { + if (s.def == &ctx->ivs[i].phi->def && s.comp == 0) { + _mesa_hash_table_insert(ctx->ub_cache, (void *)key, ctx->ivs[i].ub64); + return ctx->ivs[i].ub64; + } + } + + nir_def *res = NULL; + nir_instr *instr = nir_def_instr(s.def); + + /* Check bounded thread-local / subgroup intrinsics first. */ + if (instr->type == nir_instr_type_intrinsic) { + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + const unsigned wg_x = ctx->nir->info.workgroup_size[0]; + const unsigned wg_y = ctx->nir->info.workgroup_size[1]; + const unsigned wg_z = ctx->nir->info.workgroup_size[2]; + const uint64_t wg_total = (uint64_t)wg_x * wg_y * wg_z; + switch (intr->intrinsic) { + case nir_intrinsic_load_local_invocation_id: + if (s.comp < 3 && ctx->nir->info.workgroup_size[s.comp] > 0) + res = nir_imm_int64(b, ctx->nir->info.workgroup_size[s.comp] - 1); + break; + case nir_intrinsic_load_local_invocation_index: + if (wg_total > 0) + res = nir_imm_int64(b, wg_total - 1); + break; + case nir_intrinsic_load_subgroup_invocation: + res = nir_imm_int64(b, 31); + break; + case nir_intrinsic_load_subgroup_id: + if (wg_total > 0) + res = nir_imm_int64(b, DIV_ROUND_UP(wg_total, 32) - 1); + break; + case nir_intrinsic_load_global_invocation_id: + if (s.comp < 3 && ctx->nir->info.workgroup_size[s.comp] > 0) { + nir_def *wgid = nir_channel(b, nir_load_workgroup_id(b), s.comp); + nir_def *hi = nir_iadd_imm( + b, + nir_imul_imm(b, nir_u2u64(b, wgid), + ctx->nir->info.workgroup_size[s.comp]), + ctx->nir->info.workgroup_size[s.comp] - 1); + g16_check_u32_no_wrap(b, ctx, hi); + res = hi; + } + break; + default: + break; + } + } + + /* Workgroup-uniform leaf/expression: exact value before loop. */ + if (!res && g16_is_wg_uniform(s.def, ctx->loop_blocks, 0)) { + nir_def *u = g16_emit_wg_uniform(b, s.def, ctx); + if (u) { + if (u->num_components > 1) + u = nir_channel(b, u, s.comp); + res = nir_u2u64(b, u); + } + } + + /* Monotonic 32-bit unsigned ALU ops. */ + if (!res && nir_scalar_is_alu(s)) { + nir_op op = nir_scalar_alu_op(s); + switch (op) { + case nir_op_mov: + res = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + break; + case nir_op_u2u32: { + nir_scalar src = nir_scalar_chase_alu_src(s, 0); + uint64_t mask = src.def->bit_size < 32 + ? ((UINT64_C(1) << src.def->bit_size) - 1) + : UINT32_MAX; + if (src.def->bit_size == 32) { + res = g16_build_ub64(b, src, ctx, depth + 1); + } else { + res = nir_imm_int64(b, mask); + } + break; + } + case nir_op_iadd: { + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + nir_def *c = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 1), ctx, + depth + 1); + if (a && c) { + /* Guard against 64-bit wrap only if either operand can exceed 32 bits + * (final bound check max_end64 <= u32_bound guarantees <= UINT32_MAX + * for all monotonic ancestors). */ + if (!g16_u64_is_u32_bounded(a, ctx, 0) && + !g16_u64_is_u32_bounded(c, ctx, 0)) { + g16_check_u32_no_wrap(b, ctx, a); + g16_check_u32_no_wrap(b, ctx, c); + } + res = g16_u64_add(b, a, c); + } + break; + } + case nir_op_uadd_sat: { + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + nir_def *c = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 1), ctx, + depth + 1); + if (a && c) { + g16_check_u32_no_wrap(b, ctx, a); + g16_check_u32_no_wrap(b, ctx, c); + res = g16_u64_min(b, g16_u64_add(b, a, c), + nir_imm_int64(b, UINT32_MAX)); + } + break; + } + case nir_op_usub_sat: { + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + if (a) { + g16_check_u32_no_wrap(b, ctx, a); + res = a; + } + break; + } + case nir_op_imul: + case nir_op_amul: { + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + nir_def *c = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 1), ctx, + depth + 1); + if (a && c) { + /* Ensure both operands fit in 32 bits so 64-bit multiply never wraps. */ + g16_check_u32_no_wrap(b, ctx, a); + g16_check_u32_no_wrap(b, ctx, c); + res = g16_u64_mul(b, a, c); + } + break; + } + case nir_op_ishl: { + nir_scalar sh = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_const(sh)) { + unsigned k = nir_scalar_as_uint(sh) & 31; + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + if (a) { + g16_check_u32_no_wrap(b, ctx, a); + res = g16_u64_shl(b, a, k); + } + } + break; + } + case nir_op_ushr: { + nir_scalar sh = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_const(sh)) { + unsigned k = nir_scalar_as_uint(sh) & 31; + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + if (a) { + g16_check_u32_no_wrap(b, ctx, a); + res = g16_u64_shr(b, a, k); + } + } + break; + } + case nir_op_iand: { + nir_scalar s0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_const(s1) || nir_scalar_is_const(s0)) { + nir_scalar non_c = nir_scalar_is_const(s1) ? s0 : s1; + uint64_t mask = + nir_scalar_as_uint(nir_scalar_is_const(s1) ? s1 : s0); + if (mask == 0) { + res = nir_imm_int64(b, 0); + } else if (nir_scalar_is_const(non_c)) { + res = nir_imm_int64(b, nir_scalar_as_uint(non_c) & mask); + } else if (mask <= 0xffff) { + /* Small low-bit mask (e.g. x & 0x3f): bound is at most mask + * even if non_c wraps modulo 2^32, so avoid emitting wrap + * checks on non_c unless already cached as a tight constant. */ + uint64_t ckey = + ((uint64_t)non_c.def->index << 4) | (uint64_t)non_c.comp; + struct hash_entry *he = + _mesa_hash_table_search(ctx->ub_cache, (void *)(uintptr_t)ckey); + uint64_t ca; + if (he && g16_const_u64(he->data, &ca)) { + unsigned bits = util_last_bit64(ca); + uint64_t top_mask = + bits >= 64 ? UINT64_MAX : ((UINT64_C(1) << bits) - 1); + res = nir_imm_int64(b, MIN2(ca, top_mask & mask)); + } else { + res = nir_imm_int64(b, mask); + } + } else { + /* High-bit mask (e.g. x & 0xffffffe0): intersect with ub64(non_c) + * so alignment masks do not explode the upper bound to ~4 GiB. */ + nir_def *a = g16_build_ub64(b, non_c, ctx, depth + 1); + if (a) { + g16_check_u32_no_wrap(b, ctx, a); + uint64_t ca; + if (g16_const_u64(a, &ca)) { + unsigned bits = util_last_bit64(ca); + uint64_t top_mask = + bits >= 64 ? UINT64_MAX : ((UINT64_C(1) << bits) - 1); + res = nir_imm_int64(b, MIN2(ca, top_mask & mask)); + } else { + res = g16_u64_min(b, a, nir_imm_int64(b, mask)); + } + } else { + res = nir_imm_int64(b, mask); + } + } + } else { + nir_def *a = g16_build_ub64(b, s0, ctx, depth + 1); + nir_def *c = g16_build_ub64(b, s1, ctx, depth + 1); + if (a && c) { + g16_check_u32_no_wrap(b, ctx, a); + g16_check_u32_no_wrap(b, ctx, c); + res = g16_u64_min(b, a, c); + } + } + break; + } + case nir_op_ior: { + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + nir_def *c = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 1), ctx, + depth + 1); + if (a && c) { + g16_check_u32_no_wrap(b, ctx, a); + g16_check_u32_no_wrap(b, ctx, c); + uint64_t va, vc; + if (g16_const_u64(a, &va) && g16_const_u64(c, &vc)) { + unsigned bits = util_last_bit64(va | vc); + uint64_t bound = + bits >= 32 ? UINT32_MAX : (bits ? ((UINT64_C(1) << bits) - 1) : 0); + res = nir_imm_int64(b, MIN2(bound, va + vc)); + } else { + res = g16_u64_min(b, g16_u64_add(b, a, c), + nir_imm_int64(b, UINT32_MAX)); + } + } + break; + } + case nir_op_umin: { + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + nir_def *c = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 1), ctx, + depth + 1); + if (a && c) { + g16_check_u32_no_wrap(b, ctx, a); + g16_check_u32_no_wrap(b, ctx, c); + res = g16_u64_min(b, a, c); + } + break; + } + case nir_op_umax: { + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + nir_def *c = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 1), ctx, + depth + 1); + if (a && c) + res = g16_u64_max(b, a, c); + break; + } + case nir_op_udiv: { + nir_scalar d = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_const(d) && nir_scalar_as_uint(d) > 0) { + uint64_t dv = nir_scalar_as_uint(d); + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + if (a) { + g16_check_u32_no_wrap(b, ctx, a); + uint64_t ca; + res = g16_const_u64(a, &ca) ? nir_imm_int64(b, ca / dv) + : nir_udiv_imm(b, a, dv); + } + } + break; + } + case nir_op_umod: { + nir_scalar d = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_const(d) && nir_scalar_as_uint(d) > 0) { + uint64_t m = nir_scalar_as_uint(d) - 1; + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), ctx, + depth + 1); + if (a) { + g16_check_u32_no_wrap(b, ctx, a); + res = g16_u64_min(b, a, nir_imm_int64(b, m)); + } else { + res = nir_imm_int64(b, m); + } + } + break; + } + case nir_op_ubitfield_extract: { + nir_scalar off = nir_scalar_chase_alu_src(s, 1); + nir_scalar bits = nir_scalar_chase_alu_src(s, 2); + if (nir_scalar_is_const(bits)) { + unsigned w = nir_scalar_as_uint(bits); + uint64_t mask = + w >= 32 ? UINT32_MAX : (w ? ((UINT64_C(1) << w) - 1) : 0); + if (nir_scalar_is_const(off)) { + unsigned o = nir_scalar_as_uint(off) & 31; + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 0), + ctx, depth + 1); + if (a) { + g16_check_u32_no_wrap(b, ctx, a); + res = g16_u64_min(b, g16_u64_shr(b, a, o), + nir_imm_int64(b, mask)); + } + } + if (!res) + res = nir_imm_int64(b, mask); + } + break; + } + case nir_op_bcsel: { + nir_def *a = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 1), ctx, + depth + 1); + nir_def *c = g16_build_ub64(b, nir_scalar_chase_alu_src(s, 2), ctx, + depth + 1); + if (a && c) + res = g16_u64_max(b, a, c); + break; + } + default: + break; + } + } + + if (res) + _mesa_hash_table_insert(ctx->ub_cache, (void *)key, res); + return res; +} + +static nir_def * +g16_emit_unbounded_addr(nir_builder *b, nir_def *base, nir_scalar off, + unsigned depth) +{ + if (depth > 0 && is_op(off, nir_op_uadd_sat)) { + nir_scalar s0 = nir_scalar_chase_alu_src(off, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(off, 1); + if (nir_scalar_is_const(s1)) { + return nir_iadd_imm( + b, g16_emit_unbounded_addr(b, base, s0, depth - 1), + nir_scalar_as_uint(s1)); + } + if (nir_scalar_is_const(s0)) { + return nir_iadd_imm( + b, g16_emit_unbounded_addr(b, base, s1, depth - 1), + nir_scalar_as_uint(s0)); + } + } + if (is_op(off, nir_op_amul) || is_op(off, nir_op_imul)) { + nir_scalar s0 = nir_scalar_chase_alu_src(off, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(off, 1); + nir_scalar idx, c; + bool found = false; + if (nir_scalar_is_const(s1) && !nir_scalar_is_const(s0)) { + idx = s0; + c = s1; + found = true; + } else if (nir_scalar_is_const(s0) && !nir_scalar_is_const(s1)) { + idx = s1; + c = s0; + found = true; + } + if (found) { + uint64_t stride = nir_scalar_as_uint(c); + if (stride >= 2 && stride <= 16 && + util_is_power_of_two_nonzero(stride)) { + nir_def *idx_val = nir_mov_scalar(b, idx); + return nir_iadd(b, base, + nir_ishl_imm(b, nir_u2u64(b, idx_val), + ffs((int)stride) - 1)); + } + } + } + return nir_iadd(b, base, nir_u2u64(b, nir_mov_scalar(b, off))); +} + +struct g16_proved_load { + nir_intrinsic_instr *intr; + struct g16_bound_key bkey; + unsigned buf_idx; + unsigned load_size; +}; + +struct g16_buf_base_end { + nir_def *base; /* NULL means pure constant end */ + uint64_t max_const; +}; + +struct g16_buf_req { + struct g16_bound_key bkey; + struct g16_buf_base_end ends[16]; + unsigned num_ends; + nir_def *max_end64; +}; + +static void +g16_buf_record_end(nir_builder *b, struct g16_buf_req *br, nir_def *end64) +{ + uint64_t c = 0; + nir_def *base = g16_u64_strip_const(end64, &c); + for (unsigned i = 0; i < br->num_ends; i++) { + if (br->ends[i].base == base) { + if (c > br->ends[i].max_const) + br->ends[i].max_const = c; + return; + } + } + if (br->num_ends < ARRAY_SIZE(br->ends)) { + br->ends[br->num_ends++] = (struct g16_buf_base_end){ + .base = base, + .max_const = c, + }; + return; + } + /* Overflow fallback: merge directly into max_end64. */ + br->max_end64 = br->max_end64 ? g16_u64_max(b, br->max_end64, end64) : end64; +} + +static bool +g16_try_version_bounded_loop(nir_shader *nir, nir_function_impl *impl, + nir_loop *loop, const struct set *loop_blocks) +{ + if (nir->info.workgroup_size_variable || + nir->info.workgroup_size[0] == 0 || + nir->info.workgroup_size[1] == 0 || + nir->info.workgroup_size[2] == 0) + return false; + + nir_block *header = nir_loop_first_block(loop); + nir_block *preheader = nir_loop_predecessor_block(loop); + if (!header || !preheader || + util_dynarray_num_elements(&header->predecessors, nir_block *) != 2) + return false; + + nir_block *latch = NULL; + util_dynarray_foreach(&header->predecessors, nir_block *, pp) { + nir_block *pred = *pp; + if (pred != preheader && _mesa_set_search(loop_blocks, pred)) + latch = pred; + } + if (!latch) + return false; + + struct g16_ub_ctx ctx = { + .nir = nir, + .loop_blocks = loop_blocks, + .u_cache = _mesa_pointer_hash_table_create(NULL), + .ub_cache = _mesa_pointer_hash_table_create(NULL), + .nowrap_checked = _mesa_pointer_set_create(NULL), + .pending_nowrap = UTIL_DYNARRAY_INIT, + }; + + /* Collect affine 32-bit induction phis in the loop header. */ + nir_foreach_phi(phi, header) { + if (phi->def.bit_size != 32 || phi->def.num_components != 1) + continue; + if (ctx.num_ivs == ARRAY_SIZE(ctx.ivs)) + break; + + nir_def *init = NULL, *next = NULL; + nir_foreach_phi_src(psrc, phi) { + if (psrc->pred == preheader) + init = psrc->src.ssa; + else if (psrc->pred == latch) + next = psrc->src.ssa; + } + if (!init || !next || !g16_is_wg_uniform(init, loop_blocks, 0)) + continue; + + nir_scalar ns = nir_scalar_resolved(next, 0); + if (!is_op(ns, nir_op_iadd)) + continue; + nir_scalar a0 = nir_scalar_chase_alu_src(ns, 0); + nir_scalar a1 = nir_scalar_chase_alu_src(ns, 1); + uint64_t step = 0; + if (a0.def == &phi->def && a0.comp == 0 && nir_scalar_is_const(a1)) + step = nir_scalar_as_uint(a1); + else if (a1.def == &phi->def && a1.comp == 0 && nir_scalar_is_const(a0)) + step = nir_scalar_as_uint(a0); + if (step == 0 || step > (1u << 24)) + continue; + + ctx.ivs[ctx.num_ivs++] = (struct g16_iv_phi){ + .phi = phi, + .init = init, + .next = next, + .step = (uint32_t)step, + }; + } + + if (ctx.num_ivs == 0) { + _mesa_hash_table_destroy(ctx.u_cache, NULL); + _mesa_hash_table_destroy(ctx.ub_cache, NULL); + _mesa_set_destroy(ctx.nowrap_checked, NULL); + util_dynarray_fini(&ctx.pending_nowrap); + return false; + } + + /* Find top-tested or bottom-tested trip-count exit. */ + unsigned trip_iv = 0; + nir_def *limit_def = NULL; + bool trip_signed = false; + bool found_trip = false; + + nir_cf_node *after_hdr = nir_cf_node_next(&header->cf_node); + if (after_hdr && after_hdr->type == nir_cf_node_if) { + found_trip = g16_match_break_if(nir_cf_node_as_if(after_hdr), &ctx, false, + &trip_iv, &limit_def, &trip_signed); + } + if (!found_trip) { + nir_cf_node *before_latch = nir_cf_node_prev(&latch->cf_node); + if (before_latch && before_latch->type == nir_cf_node_if) { + found_trip = g16_match_break_if(nir_cf_node_as_if(before_latch), &ctx, + true, &trip_iv, &limit_def, + &trip_signed); + } + } + if (!found_trip) { + nir_cf_node *last_cf = nir_cf_node_prev(&nir_loop_last_block(loop)->cf_node); + if (last_cf && last_cf->type == nir_cf_node_if) { + found_trip = g16_match_break_if(nir_cf_node_as_if(last_cf), &ctx, + true, &trip_iv, &limit_def, + &trip_signed); + } + } + + if (!found_trip) { + _mesa_hash_table_destroy(ctx.u_cache, NULL); + _mesa_hash_table_destroy(ctx.ub_cache, NULL); + _mesa_set_destroy(ctx.nowrap_checked, NULL); + util_dynarray_fini(&ctx.pending_nowrap); + return false; + } + + /* Collect candidate bounded loads with invariant WG-uniform bounds. */ + struct util_dynarray ploads; + util_dynarray_init(&ploads, NULL); + struct g16_buf_req bufs[6]; + unsigned num_bufs = 0; + bool too_many_bufs = false; + + nir_foreach_block_in_cf_node(block, &loop->cf_node) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic) + continue; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + if (intr->intrinsic != nir_intrinsic_load_global_bounded && + intr->intrinsic != nir_intrinsic_load_global_constant_bounded) + continue; + nir_def *off = intr->src[1].ssa; + nir_def *bound = intr->src[2].ssa; + if (off->bit_size != 32 || off->num_components != 1) + continue; + const unsigned load_size = + intr->num_components * (intr->def.bit_size / 8); + if (load_size == 0 || load_size > 16) + continue; + struct g16_bound_key bkey; + if (!g16_parse_invariant_bound( + bound, loop_blocks, + nir_cf_node_as_block(nir_cf_node_prev(&loop->cf_node)), &bkey)) + continue; + if (!bkey.is_desc && !g16_is_wg_uniform(bkey.outside_def, loop_blocks, 0)) + continue; + + int bidx = -1; + for (unsigned k = 0; k < num_bufs; k++) { + if (g16_bound_keys_equal(&bufs[k].bkey, &bkey)) { + bidx = (int)k; + break; + } + } + if (bidx < 0) { + if (num_bufs == ARRAY_SIZE(bufs)) { + too_many_bufs = true; + break; + } + bidx = (int)num_bufs++; + bufs[bidx] = (struct g16_buf_req){.bkey = bkey, .max_end64 = NULL}; + } + struct g16_proved_load pl = { + .intr = intr, + .bkey = bkey, + .buf_idx = (unsigned)bidx, + .load_size = load_size, + }; + util_dynarray_append(&ploads, pl); + } + if (too_many_bufs) + break; + } + + unsigned total_cands = + util_dynarray_num_elements(&ploads, struct g16_proved_load); + if (too_many_bufs || total_cands < 4) { + util_dynarray_fini(&ploads); + _mesa_hash_table_destroy(ctx.u_cache, NULL); + _mesa_hash_table_destroy(ctx.ub_cache, NULL); + _mesa_set_destroy(ctx.nowrap_checked, NULL); + util_dynarray_fini(&ctx.pending_nowrap); + return false; + } + + /* Build workgroup-uniform trip bound and per-load 64-bit upper bounds into + * a temporary pre-loop insertion point (rolled back if too few prove). */ + nir_block *pre_blk = nir_loop_predecessor_block(loop); + nir_instr *saved_last = nir_block_last_instr(pre_blk); + nir_builder b = nir_builder_at(nir_before_cf_node(&loop->cf_node)); + + nir_def *trip_init = g16_emit_wg_uniform(&b, ctx.ivs[trip_iv].init, &ctx); + nir_def *trip_lim = g16_emit_wg_uniform(&b, limit_def, &ctx); + const uint32_t trip_step = ctx.ivs[trip_iv].step; + if (!trip_init || !trip_lim) + ctx.failed = true; + + if (!ctx.failed) { + if (trip_signed) { + g16_and_cond(&b, &ctx, nir_ige_imm(&b, trip_init, 0)); + g16_and_cond(&b, &ctx, nir_ilt(&b, trip_init, trip_lim)); + g16_and_cond(&b, &ctx, + nir_ule_imm(&b, nir_u2u64(&b, trip_lim), + (uint64_t)INT32_MAX - trip_step + 1)); + } else { + g16_and_cond(&b, &ctx, nir_ult(&b, trip_init, trip_lim)); + g16_and_cond(&b, &ctx, + nir_ule_imm(&b, nir_u2u64(&b, trip_lim), + (uint64_t)UINT32_MAX - trip_step + 1)); + } + /* t_max = (max(limit, init+1) - 1 - init) / step (safe even if init >= limit). */ + nir_def *span = + nir_usub_sat(&b, nir_usub_sat(&b, trip_lim, nir_imm_int(&b, 1)), + trip_init); + nir_def *t_max32 = util_is_power_of_two_nonzero(trip_step) + ? nir_ushr_imm(&b, span, ffs((int)trip_step) - 1) + : nir_udiv_imm(&b, span, trip_step); + nir_def *t_max64 = nir_u2u64(&b, t_max32); + + for (unsigned i = 0; i < ctx.num_ivs; i++) { + nir_def *init_u = g16_emit_wg_uniform(&b, ctx.ivs[i].init, &ctx); + if (!init_u) { + ctx.failed = true; + break; + } + nir_def *ub = nir_iadd(&b, nir_u2u64(&b, init_u), + nir_imul_imm(&b, t_max64, ctx.ivs[i].step)); + g16_check_u32_no_wrap(&b, &ctx, ub); + ctx.ivs[i].ub64 = ub; + } + } + + struct util_dynarray proved; + util_dynarray_init(&proved, NULL); + if (!ctx.failed) { + util_dynarray_foreach(&ploads, struct g16_proved_load, pl) { + /* Strip top-level uadd_sat(base, const_c) into (base, c + load_size): + * since load_size >= 1 and bound <= UINT32_MAX, + * min(ub(base) + c, UINT32_MAX) + load_size <= bound is exact iff + * ub(base) + c + load_size <= bound. */ + nir_scalar off_s = nir_scalar_resolved(pl->intr->src[1].ssa, 0); + uint64_t extra_const = pl->load_size; + if (is_op(off_s, nir_op_uadd_sat)) { + nir_scalar a0 = nir_scalar_chase_alu_src(off_s, 0); + nir_scalar a1 = nir_scalar_chase_alu_src(off_s, 1); + if (nir_scalar_is_const(a1)) { + extra_const += nir_scalar_as_uint(a1); + off_s = a0; + } else if (nir_scalar_is_const(a0)) { + extra_const += nir_scalar_as_uint(a0); + off_s = a1; + } + } + nir_def *off_ub = g16_build_ub64(&b, off_s, &ctx, 0); + if (!off_ub || ctx.failed) { + ctx.failed = false; + continue; + } + nir_def *end64 = g16_u64_add(&b, off_ub, nir_imm_int64(&b, extra_const)); + g16_buf_record_end(&b, &bufs[pl->buf_idx], end64); + util_dynarray_append(&proved, *pl); + } + for (unsigned k = 0; k < num_bufs; k++) { + struct g16_buf_req *br = &bufs[k]; + nir_def *cand[16]; + bool keep[16]; + unsigned nc = br->num_ends; + for (unsigned i = 0; i < nc; i++) { + cand[i] = br->ends[i].base + ? g16_u64_add(&b, br->ends[i].base, + nir_imm_int64(&b, br->ends[i].max_const)) + : nir_imm_int64(&b, br->ends[i].max_const); + keep[i] = true; + } + for (unsigned i = 0; i < nc; i++) { + if (!keep[i]) + continue; + for (unsigned j = 0; j < nc; j++) { + if (i == j || !keep[j]) + continue; + if (g16_u64_dominates(cand[j], cand[i], 0)) { + keep[i] = false; + break; + } + } + } + for (unsigned i = 0; i < nc; i++) { + if (!keep[i]) + continue; + br->max_end64 = + br->max_end64 ? g16_u64_max(&b, br->max_end64, cand[i]) : cand[i]; + } + } + + /* Emit only maximal pending u32 no-wrap checks (if hi >= lo mathematically + * and hi <= UINT32_MAX, then lo <= UINT32_MAX automatically; also skip any + * check dominated by a buffer's max_end64 which is bounded by u32 bound). */ + unsigned np = util_dynarray_num_elements(&ctx.pending_nowrap, nir_def *); + nir_def **plist = util_dynarray_begin(&ctx.pending_nowrap); + for (unsigned i = 0; i < np; i++) { + nir_def *v = plist[i]; + bool dominated = false; + for (unsigned k = 0; k < num_bufs && !dominated; k++) { + if (bufs[k].max_end64 && g16_u64_dominates(bufs[k].max_end64, v, 0)) + dominated = true; + } + for (unsigned j = 0; j < np && !dominated; j++) { + if (j == i || !plist[j]) + continue; + if (plist[j] == v) { + if (j < i) + dominated = true; + } else if (g16_u64_dominates(plist[j], v, 0)) { + dominated = true; + } + } + if (!dominated) { + g16_and_cond(&b, &ctx, + nir_uge(&b, nir_imm_int64(&b, UINT32_MAX), v)); + } + } + } + + unsigned n_proved = + util_dynarray_num_elements(&proved, struct g16_proved_load); + if (ctx.failed || n_proved < 4) { + /* Clean up speculative pre-loop instructions we inserted. */ + nir_instr *cur = nir_block_last_instr(pre_blk); + while (cur && cur != saved_last) { + nir_instr *prev = nir_instr_prev(cur); + nir_instr_remove(cur); + cur = prev; + } + util_dynarray_fini(&proved); + util_dynarray_fini(&ploads); + _mesa_hash_table_destroy(ctx.u_cache, NULL); + _mesa_hash_table_destroy(ctx.ub_cache, NULL); + _mesa_set_destroy(ctx.nowrap_checked, NULL); + util_dynarray_fini(&ctx.pending_nowrap); + return false; + } + + /* Emit per-descriptor max_end64 <= bound checks (workgroup-uniform). */ + for (unsigned k = 0; k < num_bufs; k++) { + if (!bufs[k].max_end64) + continue; + nir_def *bound_val; + if (!bufs[k].bkey.is_desc) { + bound_val = g16_emit_wg_uniform(&b, bufs[k].bkey.outside_def, &ctx); + } else { + nir_def *ds = + nir_load_descriptor_set_agx(&b, bufs[k].bkey.desc_set); + nir_def *vec = nir_load_global_constant_offset( + &b, bufs[k].bkey.num_comps, bufs[k].bkey.bit_size, ds, + nir_imm_int(&b, bufs[k].bkey.desc_offset), + .align_mul = bufs[k].bkey.align_mul, + .align_offset = bufs[k].bkey.align_offset, + .access = bufs[k].bkey.access); + bound_val = nir_channel(&b, vec, bufs[k].bkey.comp); + } + g16_and_cond(&b, &ctx, + nir_uge(&b, nir_u2u64(&b, bound_val), bufs[k].max_end64)); + } + + if (ctx.failed || !ctx.valid_cond) { + nir_instr *cur = nir_block_last_instr(pre_blk); + while (cur && cur != saved_last) { + nir_instr *prev = nir_instr_prev(cur); + nir_instr_remove(cur); + cur = prev; + } + util_dynarray_fini(&proved); + util_dynarray_fini(&ploads); + _mesa_hash_table_destroy(ctx.u_cache, NULL); + _mesa_hash_table_destroy(ctx.ub_cache, NULL); + _mesa_set_destroy(ctx.nowrap_checked, NULL); + util_dynarray_fini(&ctx.pending_nowrap); + return false; + } + + /* Version loop: fast path runs proved loads unbounded; else runs original. */ + nir_cf_list loop_cf; + nir_cf_extract(&loop_cf, nir_before_cf_node(&loop->cf_node), + nir_after_cf_node(&loop->cf_node)); + + struct hash_table *remap = _mesa_pointer_hash_table_create(NULL); + nir_if *nif = nir_push_if(&b, ctx.valid_cond); + nir_cf_list_clone_and_reinsert(&loop_cf, &nif->cf_node, + nir_after_cf_list(&nif->then_list), remap); + nir_push_else(&b, nif); + nir_cf_reinsert(&loop_cf, nir_after_cf_list(&nif->else_list)); + nir_pop_if(&b, nif); + + util_dynarray_foreach(&proved, struct g16_proved_load, pl) { + struct hash_entry *he = _mesa_hash_table_search(remap, &pl->intr->def); + if (!he) + continue; + nir_def *cdef = he->data; + nir_intrinsic_instr *cintr = nir_def_as_intrinsic(cdef); + nir_builder lb = nir_builder_at(nir_before_instr(&cintr->instr)); + + enum gl_access_qualifier access = nir_intrinsic_access(cintr); + const bool is_const = + cintr->intrinsic == nir_intrinsic_load_global_constant_bounded; + if (is_const) + access |= ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER; + + nir_def *addr = g16_emit_unbounded_addr( + &lb, cintr->src[0].ssa, + nir_scalar_resolved(cintr->src[1].ssa, 0), 4); + nir_def *val = g16_emit_global_load( + &lb, is_const, cintr->def.num_components, cintr->def.bit_size, addr, + nir_intrinsic_align_mul(cintr), nir_intrinsic_align_offset(cintr), + access); + nir_def_replace(&cintr->def, val); + } + + _mesa_hash_table_destroy(remap, NULL); + util_dynarray_fini(&proved); + util_dynarray_fini(&ploads); + _mesa_hash_table_destroy(ctx.u_cache, NULL); + _mesa_hash_table_destroy(ctx.ub_cache, NULL); + _mesa_set_destroy(ctx.nowrap_checked, NULL); + util_dynarray_fini(&ctx.pending_nowrap); + return true; +} + static bool g16_version_aligned_robust_loops( nir_shader *nir, VkPipelineRobustnessBufferBehaviorEXT ssbo_robust, @@ -2390,6 +3799,12 @@ g16_version_aligned_robust_loops( continue; } + if (g16_try_version_bounded_loop(nir, impl, loop, loop_blocks)) { + _mesa_set_destroy(loop_blocks, NULL); + progress = true; + continue; + } + util_dynarray_clear(&loads); struct g16_align_req reqs[4]; unsigned num_reqs = 0; diff --git a/src/asahi/vulkan/meson.build b/src/asahi/vulkan/meson.build index 04cf68b67b15..fbe419bd4222 100644 --- a/src/asahi/vulkan/meson.build +++ b/src/asahi/vulkan/meson.build @@ -1913,6 +1913,13 @@ if with_tests dependencies : [hk_deps], link_with : [libhk], link_args : [ld_args_gc_sections]), timeout : 30, suite : ['asahi']) + test('hk_bounded_loop', executable('hk_bounded_loop_test', + files('tests/test-hk-bounded-loop.c'), + include_directories : [include_directories('.'), inc_gallium, inc_gallium_aux, + inc_include, inc_src, inc_asahi, inc_virtio_gpu, inc_virtio_vdrm], + dependencies : [hk_deps], link_with : [libhk], + link_args : [ld_args_gc_sections]), + timeout : 30, suite : ['asahi']) endif if with_tests diff --git a/src/asahi/vulkan/tests/test-hk-bounded-loop.c b/src/asahi/vulkan/tests/test-hk-bounded-loop.c new file mode 100644 index 000000000000..eff69f787058 --- /dev/null +++ b/src/asahi/vulkan/tests/test-hk-bounded-loop.c @@ -0,0 +1,223 @@ +/* + * Copyright 2026 Aurora Silicon + * SPDX-License-Identifier: MIT + */ + +#include "hk_shader.h" +#include "compiler/nir/nir_builder.h" +#include + +static nir_phi_instr * +create_scalar_phi(nir_shader *shader) +{ + nir_phi_instr *phi = nir_phi_instr_create(shader); + nir_def_init(&phi->instr, &phi->def, 1, 32); + return phi; +} + +/* Build a compute loop modeling q4_K's bounded loads: + * - 4 adjacent 4-byte loads at block_base + {0, 4, 8, 12} (uadd_sat) + * - 1 load at (block_base + 16) + (((((idx & 0x3f) << 1) & 0xffffffe0) + + * ((((idx & 0x3f) << 1) & 0xf) << 1)) >> 2 << 2) + * When const_k_bound == true, K and bound are compile-time constants so + * nir_opt_constant_folding collapses the emitted guard to a constant boolean. + */ +static bool +run_case(const char *name, bool const_k_bound, uint32_t k_val, uint32_t bound_val, + bool wrap_base, bool expect_versioned, bool expect_const_cond, + bool expect_cond_val) +{ + static const nir_shader_compiler_options options = {0}; + nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_COMPUTE, &options, + "%s", name); + b.shader->info.workgroup_size[0] = 128; + b.shader->info.workgroup_size[1] = 1; + b.shader->info.workgroup_size[2] = 1; + b.shader->info.workgroup_size_variable = false; + + nir_def *base_ptr = nir_imm_int64(&b, 0x100000000ULL); + nir_def *k_lim = const_k_bound + ? nir_imm_int(&b, k_val) + : nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .range = 4); + nir_def *bound = const_k_bound + ? nir_imm_int(&b, bound_val) + : nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 4), .range = 4); + nir_def *lid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *zero = nir_imm_int(&b, 0); + + nir_loop *loop = nir_push_loop(&b); + nir_block *preheader = nir_loop_predecessor_block(loop); + nir_block *header = nir_loop_first_block(loop); + + nir_phi_instr *k_phi = create_scalar_phi(b.shader); + nir_phi_instr_add_src(k_phi, preheader, zero); + b.cursor = nir_after_phis(header); + + nir_push_if(&b, nir_uge(&b, &k_phi->def, k_lim)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + + nir_def *idx = nir_iadd(&b, &k_phi->def, nir_iand_imm(&b, lid, 0x1f)); + nir_def *blk = nir_ushr_imm(&b, idx, 6); + nir_def *blk_off = wrap_base ? nir_imul_imm(&b, &k_phi->def, 0x10000000u) + : nir_imul_imm(&b, blk, 144u); + + /* 4 header word loads sharing blk_off (exercises (base, max_const_off) dedup). */ + nir_def *v0 = nir_load_global_constant_bounded(&b, 1, 32, base_ptr, blk_off, bound, + .align_mul = 16, .align_offset = 0); + nir_def *v1 = nir_load_global_constant_bounded(&b, 1, 32, base_ptr, + nir_uadd_sat(&b, blk_off, nir_imm_int(&b, 4)), + bound, .align_mul = 16, .align_offset = 4); + nir_def *v2 = nir_load_global_constant_bounded(&b, 1, 32, base_ptr, + nir_uadd_sat(&b, blk_off, nir_imm_int(&b, 8)), + bound, .align_mul = 16, .align_offset = 8); + nir_def *v3 = nir_load_global_constant_bounded(&b, 1, 32, base_ptr, + nir_uadd_sat(&b, blk_off, nir_imm_int(&b, 12)), + bound, .align_mul = 16, .align_offset = 12); + + /* q4_K high-bit alignment mask pattern: ((idx & 0x3f) << 1) & 0xffffffe0. */ + nir_def *s597 = nir_iand_imm(&b, idx, 0x3fu); + nir_def *s598 = nir_ishl_imm(&b, s597, 1); + nir_def *s605 = nir_iand_imm(&b, s598, 0xfu); + nir_def *s606 = nir_ishl_imm(&b, s605, 1); + nir_def *s608 = nir_iand_imm(&b, s598, 0xffffffe0u); + nir_def *s609 = nir_iadd(&b, s608, s606); + nir_def *s671 = nir_ishl_imm(&b, nir_ushr_imm(&b, s609, 2), 2); + nir_def *qs_off = nir_iadd(&b, nir_iadd_imm(&b, blk_off, 16u), s671); + nir_def *v4 = nir_load_global_constant_bounded(&b, 1, 32, base_ptr, qs_off, bound, + .align_mul = 4, .align_offset = 0); + + nir_def *sum = nir_iadd(&b, nir_iadd(&b, v0, v1), nir_iadd(&b, nir_iadd(&b, v2, v3), v4)); + nir_store_global(&b, sum, base_ptr, .align_mul = 4); + + nir_def *next = nir_iadd_imm(&b, &k_phi->def, 32u); + nir_phi_instr_add_src(k_phi, nir_cursor_current_block(b.cursor), next); + nir_instr_insert(nir_before_block(header), &k_phi->instr); + nir_pop_loop(&b, loop); + + nir_validate_shader(b.shader, "before bounded loop versioning"); + bool versioned = hk_nir_g16_version_aligned_robust_loops( + b.shader, + VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT, + VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_EXT); + nir_validate_shader(b.shader, "after bounded loop versioning"); + + if (versioned != expect_versioned) { + fprintf(stderr, "FAIL %s: versioned=%d != expected %d\n", name, versioned, + expect_versioned); + ralloc_free(b.shader); + return false; + } + + if (!versioned) { + ralloc_free(b.shader); + return true; + } + + /* Inspect the top-level guard if before constant folding removes the dead branch. */ + nir_opt_constant_folding(b.shader); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "after fold+dce"); + + nir_function_impl *impl = nir_shader_get_entrypoint(b.shader); + nir_if *guard = NULL; + foreach_list_typed(nir_cf_node, n, node, &impl->body) { + if (n->type == nir_cf_node_if) { + guard = nir_cf_node_as_if(n); + break; + } + } + if (!guard) { + fprintf(stderr, "FAIL %s: missing versioned guard if\n", name); + ralloc_free(b.shader); + return false; + } + + nir_scalar c = nir_scalar_resolved(guard->condition.ssa, 0); + if (expect_const_cond) { + if (!nir_scalar_is_const(c) || nir_scalar_as_bool(c) != expect_cond_val) { + fprintf(stderr, "FAIL %s: expected const cond=%d, got is_const=%d val=%d\n", + name, expect_cond_val, nir_scalar_is_const(c), + nir_scalar_is_const(c) ? nir_scalar_as_bool(c) : -1); + ralloc_free(b.shader); + return false; + } + } else { + if (nir_scalar_is_const(c) && !nir_scalar_as_bool(c)) { + fprintf(stderr, "FAIL %s: guard collapsed to constant FALSE!\n", name); + ralloc_free(b.shader); + return false; + } + /* Verify 0 umax ops in b0 (dedup) and 0 poisoned 0xfffffffc constants. */ + nir_block *b0 = nir_start_block(impl); + unsigned umax_cnt = 0; + nir_foreach_instr(instr, b0) { + if (instr->type == nir_instr_type_alu && + nir_instr_as_alu(instr)->op == nir_op_umax) + umax_cnt++; + if (instr->type == nir_instr_type_load_const) { + nir_load_const_instr *lc = nir_instr_as_load_const(instr); + if (lc->def.bit_size == 64 && + (lc->value[0].u64 == 0xfffffffcULL || + lc->value[0].u64 == 0xfffffffeULL)) { + fprintf(stderr, "FAIL %s: poisoned 64-bit constant 0x%llx in b0!\n", + name, (unsigned long long)lc->value[0].u64); + ralloc_free(b.shader); + return false; + } + } + } + if (umax_cnt != 0) { + fprintf(stderr, "FAIL %s: expected 0 umax in b0 after dedup, got %u\n", + name, umax_cnt); + ralloc_free(b.shader); + return false; + } + /* Fast branch must have 0 bounded loads and 5 raw global loads. */ + unsigned fast_bnd = 0, fast_raw = 0; + foreach_list_typed(nir_cf_node, cn, node, &guard->then_list) { + nir_foreach_block_in_cf_node(blk_node, cn) { + nir_foreach_instr(instr, blk_node) { + if (instr->type != nir_instr_type_intrinsic) + continue; + nir_intrinsic_op iop = nir_instr_as_intrinsic(instr)->intrinsic; + if (iop == nir_intrinsic_load_global_constant_bounded || + iop == nir_intrinsic_load_global_bounded) + fast_bnd++; + else if (iop == nir_intrinsic_load_global_constant || + iop == nir_intrinsic_load_global) + fast_raw++; + } + } + } + if (fast_bnd != 0 || fast_raw != 5) { + fprintf(stderr, "FAIL %s: fast loop bounded=%u raw=%u (want 0, 5)\n", + name, fast_bnd, fast_raw); + ralloc_free(b.shader); + return false; + } + } + + ralloc_free(b.shader); + return true; +} + +int +main(void) +{ + bool ok = true; + /* 1. Dynamic K & bound: high-bit iand(0xffffffe0) preserves tight ub64, + * guard is not constant false, 0 umax in b0, 5/5 raw loads in fast loop. */ + ok &= run_case("high_mask_iand_dynamic", false, 0, 0, false, true, false, false); + /* 2. Exact bound for K=2048: max block = (2016 + 31) >> 6 = 31 -> + * end = 31 * 144 + 144 = 4608 bytes -> guard MUST fold to TRUE! */ + ok &= run_case("high_mask_iand_exact_true", true, 2048, 4608, false, true, true, true); + /* 3. Buffer 1 byte too short (4607 < 4608) -> guard MUST fold to FALSE! */ + ok &= run_case("high_mask_iand_short_false", true, 2048, 4607, false, true, true, false); + /* 4. 32-bit wrapping offset (k * 0x10000000 overflows u32) -> must NOT enter fast path! */ + ok &= run_case("wrapping_offset_rejected", true, 2048, 0xffffffffu, true, true, true, false); + if (!ok) + return 1; + printf("PASS: hk_bounded_loop (4/4 cases)\n"); + return 0; +} From c5d03de31fcc476a6a4ccab9bca9ec10fb2a3a1b Mon Sep 17 00:00:00 2001 From: Dylan Ironside Date: Tue, 1 Dec 2026 13:43:32 -0600 Subject: [PATCH 3/6] agx: sink epilogue defs past high-pressure loops and fold imadshl bitfield slices Two AGX3 compute compiler improvements: 1. agx_nir_opt_sink_past_loops() (agx_nir_opt_licm.c, agx_nir.h, agx_compile.c): - Runs before agx_nir_opt_licm() on AGX3 compute shaders with high-pressure loops (>= 96 estimated live halves). - Sinks pure epilogue-only definitions past the loop into the post-loop block and rematerializes pure zero-register-leaf (system-value / uniform / constant) epilogue trees after the loop so post-loop store addressing does not consume live-through registers across the hot loop body. 2. agx_nir_opt_bitfield_slices() (agx_nir_lower_shared_bitsize.c): - Extends slice parsing and associative term collection to recognize imadshl_agx(a, 1, b, k), power-of-two imul/amul shifts, iand(ushr(x, k), mask), and ushr(iand(x, mask), k) narrowing so multi-slice decode trees fold into a single ubitfield_extract. Adds BitfieldSlicesImadshlAndShiftedMask and SinkEpilogueDefsPastHighPressureLoop unit tests in test-shared-byte-offsets.cpp. Signed-off-by: Dylan Ironside --- src/asahi/compiler/agx_compile.c | 11 +- src/asahi/compiler/agx_nir.h | 1 + .../compiler/agx_nir_lower_shared_bitsize.c | 226 +++++++++-- src/asahi/compiler/agx_nir_opt_licm.c | 355 ++++++++++++++++++ .../test/test-shared-byte-offsets.cpp | 198 +++++++++- 5 files changed, 760 insertions(+), 31 deletions(-) diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index 8b7418535d48..b0c225bd1a79 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -21203,9 +21203,18 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, NIR_PASS(_, nir, nir_opt_dce); } } - if (is_agx3) + if (is_agx3) { NIR_PASS(post_opt_progress, nir, agx_nir_reassociate_loop_invariant_eq); + if (mesa_shader_stage_is_compute(nir->info.stage)) { + bool sunk = false; + NIR_PASS(sunk, nir, agx_nir_opt_sink_past_loops); + if (sunk) { + post_opt_progress = true; + NIR_PASS(_, nir, nir_opt_dce); + } + } + } NIR_PASS(post_opt_progress, nir, agx_nir_opt_licm, regs, cap_rt_compute); } else if (key->dev.encoding == AGX_ISA_ENCODING_AGX2 && nir->info.stage == MESA_SHADER_COMPUTE && !nir->info.internal && diff --git a/src/asahi/compiler/agx_nir.h b/src/asahi/compiler/agx_nir.h index d252271457b4..e4c38028ccfe 100644 --- a/src/asahi/compiler/agx_nir.h +++ b/src/asahi/compiler/agx_nir.h @@ -123,6 +123,7 @@ bool agx_nir_opt_shared_byte_offsets(struct nir_shader *s); bool agx_nir_opt_g13x_shared_offsets(struct nir_shader *s); bool agx_nir_opt_bitfield_slices(struct nir_shader *s); bool agx_nir_reassociate_loop_invariant_eq(struct nir_shader *shader); +bool agx_nir_opt_sink_past_loops(struct nir_shader *shader); bool agx_nir_opt_licm(struct nir_shader *shader, unsigned budget, bool cap_rt_compute); bool agx_nir_opt_licm_agx2_integer(struct nir_shader *shader, unsigned budget); diff --git a/src/asahi/compiler/agx_nir_lower_shared_bitsize.c b/src/asahi/compiler/agx_nir_lower_shared_bitsize.c index 6e76c7330cd8..9c922f77723e 100644 --- a/src/asahi/compiler/agx_nir_lower_shared_bitsize.c +++ b/src/asahi/compiler/agx_nir_lower_shared_bitsize.c @@ -829,24 +829,71 @@ struct agx_bit_slice { unsigned dst_off; }; +static bool +is_imadshl_add_shift(nir_scalar s, nir_scalar *a_out, nir_scalar *b_out, + unsigned *shift_out) +{ + if (!nir_scalar_is_alu(s) || nir_scalar_alu_op(s) != nir_op_imadshl_agx) + return false; + nir_scalar mul = nir_scalar_chase_alu_src(s, 1); + nir_scalar sh = nir_scalar_chase_alu_src(s, 3); + if (!nir_scalar_is_const(mul) || nir_scalar_as_uint(mul) != 1 || + !nir_scalar_is_const(sh)) + return false; + unsigned k = (unsigned)(nir_scalar_as_uint(sh) & 31); + if (k >= 32) + return false; + *a_out = nir_scalar_chase_alu_src(s, 0); + *b_out = nir_scalar_chase_alu_src(s, 2); + *shift_out = k; + return true; +} + static struct agx_bit_slice -parse_bit_slice(nir_scalar s) +parse_bit_slice_shifted(nir_scalar s, unsigned dst_off) { struct agx_bit_slice out = {.valid = false}; - if (s.def->bit_size != 32 || !nir_scalar_is_alu(s)) + if (s.def->bit_size != 32 || !nir_scalar_is_alu(s) || dst_off >= 32) return out; - unsigned dst_off = 0; if (nir_scalar_alu_op(s) == nir_op_ishl) { nir_scalar sh = nir_scalar_chase_alu_src(s, 1); if (!nir_scalar_is_const(sh)) return out; - dst_off = (unsigned)(nir_scalar_as_uint(sh) & 31); - if (dst_off == 0) + unsigned k = (unsigned)(nir_scalar_as_uint(sh) & 31); + if (k == 0 || dst_off + k >= 32) + return out; + return parse_bit_slice_shifted(nir_scalar_chase_alu_src(s, 0), + dst_off + k); + } + if (nir_scalar_alu_op(s) == nir_op_imul || + nir_scalar_alu_op(s) == nir_op_amul) { + nir_scalar m0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar m1 = nir_scalar_chase_alu_src(s, 1); + nir_scalar base, mc; + if (nir_scalar_is_const(m1) && !nir_scalar_is_const(m0)) { + base = m0; + mc = m1; + } else if (nir_scalar_is_const(m0) && !nir_scalar_is_const(m1)) { + base = m1; + mc = m0; + } else { return out; - s = nir_scalar_chase_alu_src(s, 0); - if (!nir_scalar_is_alu(s)) + } + uint64_t mv = nir_scalar_as_uint(mc); + if (mv < 2 || mv > (UINT64_C(1) << 31) || + !util_is_power_of_two_nonzero(mv)) + return out; + unsigned k = ffsll((long long)mv) - 1; + if (dst_off + k >= 32) return out; + return parse_bit_slice_shifted(base, dst_off + k); + } + nir_scalar ma, mb; + unsigned msh; + if (is_imadshl_add_shift(s, &ma, &mb, &msh) && nir_scalar_is_const(ma) && + nir_scalar_as_uint(ma) == 0 && msh > 0 && dst_off + msh < 32) { + return parse_bit_slice_shifted(mb, dst_off + msh); } nir_op op = nir_scalar_alu_op(s); @@ -857,12 +904,39 @@ parse_bit_slice(nir_scalar s) unsigned k = (unsigned)(nir_scalar_as_uint(sh) & 31); if (k == 0 || k >= 32) return out; + nir_scalar base = nir_scalar_chase_alu_src(s, 0); unsigned w = 32 - k; + if (nir_scalar_is_alu(base) && nir_scalar_alu_op(base) == nir_op_iand) { + nir_scalar a0 = nir_scalar_chase_alu_src(base, 0); + nir_scalar a1 = nir_scalar_chase_alu_src(base, 1); + nir_scalar x, cm; + bool ok = false; + if (nir_scalar_is_const(a1) && !nir_scalar_is_const(a0)) { + x = a0; + cm = a1; + ok = true; + } else if (nir_scalar_is_const(a0) && !nir_scalar_is_const(a1)) { + x = a1; + cm = a0; + ok = true; + } + if (ok) { + uint64_t shifted = nir_scalar_as_uint(cm) >> k; + if (shifted > 0 && shifted < UINT32_MAX && + util_is_power_of_two_nonzero(shifted + 1)) { + unsigned nw = ffsll((long long)(shifted + 1)) - 1; + if (nw > 0 && k + nw <= 32) { + base = x; + w = nw; + } + } + } + } if (dst_off + w > 32) return out; return (struct agx_bit_slice){ .valid = true, - .base = nir_scalar_chase_alu_src(s, 0), + .base = base, .src_off = k, .width = w, .dst_off = dst_off, @@ -905,10 +979,21 @@ parse_bit_slice(nir_scalar s) unsigned w = ffsll((long long)(mask + 1)) - 1; if (w == 0 || dst_off + w > 32) return out; + unsigned src_off = 0; + if (nir_scalar_is_alu(base) && nir_scalar_alu_op(base) == nir_op_ushr) { + nir_scalar sh = nir_scalar_chase_alu_src(base, 1); + if (nir_scalar_is_const(sh)) { + unsigned k = (unsigned)(nir_scalar_as_uint(sh) & 31); + if (k > 0 && k + w <= 32) { + base = nir_scalar_chase_alu_src(base, 0); + src_off = k; + } + } + } return (struct agx_bit_slice){ .valid = true, .base = base, - .src_off = 0, + .src_off = src_off, .width = w, .dst_off = dst_off, }; @@ -916,19 +1001,39 @@ parse_bit_slice(nir_scalar s) return out; } +struct assoc_term { + nir_scalar s; + unsigned extra_shift; +}; + static bool -collect_assoc_terms(nir_scalar s, nir_op op, unsigned depth, - nir_scalar *terms, unsigned *count, unsigned max_terms) +collect_add_or_terms(nir_scalar s, bool is_add, unsigned depth, + struct assoc_term *terms, unsigned *count, + unsigned max_terms) { - if (depth > 0 && nir_scalar_is_alu(s) && nir_scalar_alu_op(s) == op) { - return collect_assoc_terms(nir_scalar_chase_alu_src(s, 0), op, depth - 1, - terms, count, max_terms) && - collect_assoc_terms(nir_scalar_chase_alu_src(s, 1), op, depth - 1, - terms, count, max_terms); + if (depth > 0 && nir_scalar_is_alu(s)) { + nir_op op = nir_scalar_alu_op(s); + if ((is_add && op == nir_op_iadd) || (!is_add && op == nir_op_ior)) { + return collect_add_or_terms(nir_scalar_chase_alu_src(s, 0), is_add, + depth - 1, terms, count, max_terms) && + collect_add_or_terms(nir_scalar_chase_alu_src(s, 1), is_add, + depth - 1, terms, count, max_terms); + } + nir_scalar a, b; + unsigned sh; + if (is_add && is_imadshl_add_shift(s, &a, &b, &sh) && + !(nir_scalar_is_const(a) && nir_scalar_as_uint(a) == 0)) { + if (!collect_add_or_terms(a, true, depth - 1, terms, count, max_terms)) + return false; + if (*count >= max_terms) + return false; + terms[(*count)++] = (struct assoc_term){.s = b, .extra_shift = sh}; + return true; + } } if (*count >= max_terms) return false; - terms[(*count)++] = s; + terms[(*count)++] = (struct assoc_term){.s = s, .extra_shift = 0}; return true; } @@ -958,7 +1063,7 @@ opt_bitfield_slice_instr(nir_builder *b, nir_alu_instr *alu, void *data) b->cursor = nir_before_instr(&alu->instr); /* 1. ushr(iand(x, mask), shift) -> ubitfield_extract(x, shift, width), - * and ushr(ishl(x, a), c) -> ishl(x, a - c) when x << a cannot wrap. */ + * and ushr(ishl/imadshl0(x, a), c) -> ishl(x, a - c) when x << a cannot wrap. */ if (alu->op == nir_op_ushr) { nir_scalar sh = nir_scalar_resolved(alu->src[1].src.ssa, alu->src[1].swizzle[0]); if (!nir_scalar_is_const(sh)) @@ -1013,25 +1118,82 @@ opt_bitfield_slice_instr(nir_builder *b, nir_alu_instr *alu, void *data) return true; } } + } else { + nir_scalar ma, mb; + unsigned a; + if (is_imadshl_add_shift(src0, &ma, &mb, &a) && + nir_scalar_is_const(ma) && nir_scalar_as_uint(ma) == 0 && + a >= k && a < 32 && + nir_unsigned_upper_bound(b->shader, ranges, mb) <= + (UINT32_MAX >> a)) { + nir_def *base = nir_mov_scalar(b, mb); + nir_def *rep = a > k ? nir_ishl_imm(b, base, a - k) : base; + nir_def_replace(&alu->def, rep); + return true; + } + } + return false; + } + + /* 1b. iand(ushr(x, k), (1< ubitfield_extract(x, k, w). */ + if (alu->op == nir_op_iand) { + nir_scalar s0 = nir_scalar_resolved(alu->src[0].src.ssa, alu->src[0].swizzle[0]); + nir_scalar s1 = nir_scalar_resolved(alu->src[1].src.ssa, alu->src[1].swizzle[0]); + nir_scalar base, cm; + if (nir_scalar_is_const(s1) && !nir_scalar_is_const(s0)) { + base = s0; + cm = s1; + } else if (nir_scalar_is_const(s0) && !nir_scalar_is_const(s1)) { + base = s1; + cm = s0; + } else { + return false; + } + uint64_t mask = nir_scalar_as_uint(cm); + if (mask > 0 && mask < UINT32_MAX && + util_is_power_of_two_nonzero(mask + 1) && + nir_scalar_is_alu(base) && nir_scalar_alu_op(base) == nir_op_ushr) { + nir_scalar sh = nir_scalar_chase_alu_src(base, 1); + if (nir_scalar_is_const(sh)) { + unsigned k = (unsigned)(nir_scalar_as_uint(sh) & 31); + unsigned w = ffsll((long long)(mask + 1)) - 1; + if (k > 0 && w > 0 && k + w < 32) { + nir_def *rep = nir_ubitfield_extract_imm( + b, nir_mov_scalar(b, nir_scalar_chase_alu_src(base, 0)), k, w); + nir_def_replace(&alu->def, rep); + return true; + } + } } return false; } - /* 2. Merge adjacent bitfield slices in associative iadd / ior trees. */ - if (alu->op != nir_op_iadd && alu->op != nir_op_ior) + /* 2. Merge adjacent bitfield slices in associative iadd / imadshl_agx / ior trees. */ + bool is_add = false; + if (alu->op == nir_op_iadd) { + is_add = true; + } else if (alu->op == nir_op_imadshl_agx) { + nir_scalar ma, mb; + unsigned msh; + if (!is_imadshl_add_shift(nir_get_scalar(&alu->def, 0), &ma, &mb, &msh) || + (nir_scalar_is_const(ma) && nir_scalar_as_uint(ma) == 0)) + return false; + is_add = true; + } else if (alu->op != nir_op_ior) { return false; + } - nir_scalar terms[8]; + struct assoc_term terms[12]; unsigned n = 0; - if (!collect_assoc_terms(nir_get_scalar(&alu->def, 0), alu->op, 4, terms, - &n, 8) || + if (!collect_add_or_terms(nir_get_scalar(&alu->def, 0), is_add, 6, terms, + &n, 12) || n < 2) return false; - struct agx_bit_slice slices[8]; - bool alive[8]; + struct agx_bit_slice slices[12]; + bool alive[12]; for (unsigned i = 0; i < n; i++) { - slices[i] = parse_bit_slice(terms[i]); + slices[i] = parse_bit_slice_shifted(terms[i].s, terms[i].extra_shift); alive[i] = true; } @@ -1068,12 +1230,18 @@ opt_bitfield_slice_instr(nir_builder *b, nir_alu_instr *alu, void *data) for (unsigned i = 0; i < n; i++) { if (!alive[i]) continue; - nir_def *v = slices[i].valid ? emit_bit_slice(b, &slices[i]) - : nir_mov_scalar(b, terms[i]); + nir_def *v; + if (slices[i].valid) { + v = emit_bit_slice(b, &slices[i]); + } else { + v = nir_mov_scalar(b, terms[i].s); + if (terms[i].extra_shift) + v = nir_ishl_imm(b, v, terms[i].extra_shift); + } if (!acc) acc = v; else - acc = alu->op == nir_op_iadd ? nir_iadd(b, acc, v) : nir_ior(b, acc, v); + acc = is_add ? nir_iadd(b, acc, v) : nir_ior(b, acc, v); } nir_def_replace(&alu->def, acc); return true; diff --git a/src/asahi/compiler/agx_nir_opt_licm.c b/src/asahi/compiler/agx_nir_opt_licm.c index 6a166ca33494..081c4dcaabb7 100644 --- a/src/asahi/compiler/agx_nir_opt_licm.c +++ b/src/asahi/compiler/agx_nir_opt_licm.c @@ -3,6 +3,7 @@ * SPDX-License-Identifier: MIT */ +#include "util/hash_table.h" #include "util/sparse_bitset.h" #include "util/u_dynarray.h" #include "agx_compile.h" @@ -1657,3 +1658,357 @@ agx_nir_opt_licm_agx2_integer(nir_shader *shader, unsigned budget) return nir_opt_licm(shader, agx2_integer_licm_filter); } + +static bool +sink_instr_is_pure(const nir_instr *instr) +{ + switch (instr->type) { + case nir_instr_type_load_const: + case nir_instr_type_undef: + return true; + case nir_instr_type_alu: { + const nir_alu_instr *alu = nir_instr_as_alu(instr); + switch (alu->op) { + case nir_op_idiv: + case nir_op_udiv: + case nir_op_imod: + case nir_op_umod: + case nir_op_irem: + return false; + default: + return true; + } + } + case nir_instr_type_intrinsic: { + const nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + switch (intr->intrinsic) { + case nir_intrinsic_load_local_invocation_id: + case nir_intrinsic_load_local_invocation_index: + case nir_intrinsic_load_workgroup_id: + case nir_intrinsic_load_subgroup_invocation: + case nir_intrinsic_load_subgroup_id: + case nir_intrinsic_load_num_workgroups: + case nir_intrinsic_load_preamble: + case nir_intrinsic_load_push_constant: + case nir_intrinsic_load_kernel_input: + return true; + default: + return false; + } + } + default: + return false; + } +} + +static bool +is_zero_reg_remat_leaf(const nir_instr *instr) +{ + if (instr->type == nir_instr_type_load_const || + instr->type == nir_instr_type_undef) + return true; + if (instr->type != nir_instr_type_intrinsic) + return false; + switch (nir_instr_as_intrinsic(instr)->intrinsic) { + case nir_intrinsic_load_local_invocation_id: + case nir_intrinsic_load_local_invocation_index: + case nir_intrinsic_load_workgroup_id: + case nir_intrinsic_load_subgroup_invocation: + case nir_intrinsic_load_subgroup_id: + case nir_intrinsic_load_num_workgroups: + case nir_intrinsic_load_preamble: + case nir_intrinsic_load_push_constant: + case nir_intrinsic_load_kernel_input: + return true; + default: + return false; + } +} + +struct sink_remat_ctx { + struct hash_table *visited; + unsigned count; + unsigned max_ops; + bool ok; + unsigned pre_limit_block_idx; +}; + +static bool check_sink_remat_def(nir_def *def, struct sink_remat_ctx *ctx); + +static bool +check_sink_remat_src(nir_src *src, void *data) +{ + struct sink_remat_ctx *ctx = data; + if (!check_sink_remat_def(src->ssa, ctx)) { + ctx->ok = false; + return false; + } + return true; +} + +static bool +check_sink_remat_def(nir_def *def, struct sink_remat_ctx *ctx) +{ + if (!ctx->ok) + return false; + if (_mesa_hash_table_search(ctx->visited, def)) + return true; + nir_instr *instr = nir_def_instr(def); + if (instr->block->index > ctx->pre_limit_block_idx) { + ctx->ok = false; + return false; + } + if (is_zero_reg_remat_leaf(instr)) { + _mesa_hash_table_insert(ctx->visited, def, (void *)1); + if (instr->type != nir_instr_type_load_const && + instr->type != nir_instr_type_undef) { + if (++ctx->count > ctx->max_ops) { + ctx->ok = false; + return false; + } + } + return true; + } + if (instr->type != nir_instr_type_alu || !sink_instr_is_pure(instr)) { + ctx->ok = false; + return false; + } + if (++ctx->count > ctx->max_ops) { + ctx->ok = false; + return false; + } + _mesa_hash_table_insert(ctx->visited, def, (void *)1); + nir_foreach_src(instr, check_sink_remat_src, ctx); + return ctx->ok; +} + +static nir_def * +clone_sink_remat_def(nir_shader *shader, nir_def *def, + struct hash_table *clone_map) +{ + struct hash_entry *e = _mesa_hash_table_search(clone_map, def); + if (e) + return e->data; + + nir_instr *orig = nir_def_instr(def); + if (orig->type == nir_instr_type_alu) { + nir_alu_instr *alu = nir_instr_as_alu(orig); + unsigned ns = nir_op_infos[alu->op].num_inputs; + for (unsigned i = 0; i < ns; i++) + clone_sink_remat_def(shader, alu->src[i].src.ssa, clone_map); + } else if (orig->type == nir_instr_type_intrinsic) { + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(orig); + unsigned ns = nir_intrinsic_infos[intr->intrinsic].num_srcs; + for (unsigned i = 0; i < ns; i++) + clone_sink_remat_def(shader, intr->src[i].ssa, clone_map); + } + + nir_instr *cloned = nir_instr_clone_deep(shader, orig, clone_map); + nir_cursor *cur = _mesa_hash_table_search(clone_map, NULL)->data; + nir_instr_insert(*cur, cloned); + *cur = nir_after_instr(cloned); + nir_def *cdef = nir_instr_def(cloned); + _mesa_hash_table_insert(clone_map, def, cdef); + return cdef; +} + +static unsigned +cf_node_peak_from_blocks(nir_cf_node *node, const unsigned *block_peaks) +{ + unsigned peak = 0; + nir_foreach_block_in_cf_node(block, node) + peak = MAX2(peak, block_peaks[block->index]); + return peak; +} + +static bool +cf_list_has_high_peak_loop(struct exec_list *list, const unsigned *block_peaks, + unsigned min_peak) +{ + foreach_list_typed(nir_cf_node, node, node, list) { + if (node->type == nir_cf_node_loop) { + nir_loop *loop = nir_cf_node_as_loop(node); + if (cf_node_peak_from_blocks(&loop->cf_node, block_peaks) >= min_peak || + cf_list_has_high_peak_loop(&loop->body, block_peaks, min_peak)) + return true; + } else if (node->type == nir_cf_node_if) { + nir_if *nif = nir_cf_node_as_if(node); + if (cf_list_has_high_peak_loop(&nif->then_list, block_peaks, min_peak) || + cf_list_has_high_peak_loop(&nif->else_list, block_peaks, min_peak)) + return true; + } + } + return false; +} + +/* + * Sink pure epilogue-only definitions past high-pressure compute loops (and + * rematerialize pure system-value/uniform-rooted epilogue values after the + * loop) so dead-inside-loop epilogue state does not occupy live-through + * registers across the loop body. + */ +bool +agx_nir_opt_sink_past_loops(nir_shader *shader) +{ + bool progress = false; + + nir_foreach_function_impl(impl, shader) { + if (impl->function->is_preamble || !cf_list_has_loop(&impl->body)) { + nir_no_progress(impl); + continue; + } + + nir_metadata_require(impl, nir_metadata_block_index | + nir_metadata_dominance | + nir_metadata_live_defs); + + void *mem_ctx = ralloc_context(NULL); + BITSET_DECLARE(stack_live, 4096); + BITSET_WORD *est_live = + impl->ssa_alloc <= 4096 ? stack_live + : BITSET_RZALLOC(mem_ctx, impl->ssa_alloc); + struct licm_estimate est = { + .encoding = AGX_ISA_ENCODING_AGX3C, + .halves = rzalloc_array(mem_ctx, uint8_t, impl->ssa_alloc), + .mem_ctx = mem_ctx, + .live = est_live, + .ssa_alloc = impl->ssa_alloc, + }; + unsigned file_limit = 256; + scan_shader_ra_props(&est, impl, &file_limit); + + unsigned *block_peaks = rzalloc_array(mem_ctx, unsigned, impl->num_blocks); + struct util_dynarray tmp_instrs = UTIL_DYNARRAY_INIT; + nir_foreach_block(block, impl) { + util_dynarray_clear(&tmp_instrs); + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_phi) + util_dynarray_append(&tmp_instrs, instr); + } + block_peaks[block->index] = block_peak_instrs( + &est, block, &block->live_out, NULL, + util_dynarray_begin(&tmp_instrs), + util_dynarray_num_elements(&tmp_instrs, nir_instr *)); + } + util_dynarray_fini(&tmp_instrs); + + bool impl_progress = false; + foreach_list_typed(nir_cf_node, node, node, &impl->body) { + bool high_loop = false; + if (node->type == nir_cf_node_loop) { + nir_loop *loop = nir_cf_node_as_loop(node); + high_loop = + cf_node_peak_from_blocks(&loop->cf_node, block_peaks) >= 96 || + cf_list_has_high_peak_loop(&loop->body, block_peaks, 96); + } else if (node->type == nir_cf_node_if) { + nir_if *nif = nir_cf_node_as_if(node); + high_loop = + cf_list_has_high_peak_loop(&nif->then_list, block_peaks, 96) || + cf_list_has_high_peak_loop(&nif->else_list, block_peaks, 96); + } + if (!high_loop) + continue; + + nir_cf_node *next = nir_cf_node_next(node); + if (!next || next->type != nir_cf_node_block) + continue; + nir_block *after = nir_cf_node_as_block(next); + nir_cf_node *prev = nir_cf_node_prev(node); + if (!prev || prev->type != nir_cf_node_block) + continue; + nir_block *before_end = nir_cf_node_as_block(prev); + unsigned pre_limit = before_end->index; + + /* Pass A: sink pure epilogue-only defs from pre-region blocks. */ + nir_block *b = before_end; + while (b) { + nir_foreach_instr_reverse_safe(instr, b) { + nir_def *def = nir_instr_def(instr); + if (!def || instr->type == nir_instr_type_load_const || + instr->type == nir_instr_type_undef || + !sink_instr_is_pure(instr)) + continue; + if (list_is_empty(&def->uses)) + continue; + bool all_after = true; + nir_foreach_use_including_if(use, def) { + nir_block *ub = nir_src_get_block(use); + if (!nir_block_dominates(after, ub)) { + all_after = false; + break; + } + } + if (!all_after) + continue; + + nir_instr_remove(instr); + nir_instr_insert(nir_after_phis(after), instr); + impl_progress = true; + } + nir_cf_node *pnode = nir_cf_node_prev(&b->cf_node); + b = (pnode && pnode->type == nir_cf_node_block) + ? nir_cf_node_as_block(pnode) + : NULL; + } + + /* Pass B: rematerialize pure zero-reg-leaf trees live into after. */ + struct hash_table *clone_map = _mesa_pointer_hash_table_create(mem_ctx); + nir_cursor cur = nir_after_phis(after); + _mesa_hash_table_insert(clone_map, NULL, &cur); + + nir_foreach_block(blk, impl) { + if (blk->index > pre_limit) + break; + nir_foreach_instr(instr, blk) { + nir_def *def = nir_instr_def(instr); + if (!def || def->index >= est.ssa_alloc || + est.halves[def->index] == 0) + continue; + bool has_after_use = false; + nir_foreach_use_including_if(use, def) { + nir_block *ub = nir_src_get_block(use); + if (nir_block_dominates(after, ub)) { + has_after_use = true; + break; + } + } + if (!has_after_use) + continue; + + struct hash_table *vis = _mesa_pointer_hash_table_create(mem_ctx); + struct sink_remat_ctx rctx = { + .visited = vis, + .count = 0, + .max_ops = 64, + .ok = true, + .pre_limit_block_idx = pre_limit, + }; + bool ok = check_sink_remat_def(def, &rctx); + _mesa_hash_table_destroy(vis, NULL); + if (!ok) + continue; + + nir_def *rep = clone_sink_remat_def(shader, def, clone_map); + nir_foreach_use_including_if_safe(use, def) { + nir_block *ub = nir_src_get_block(use); + if (nir_block_dominates(after, ub)) + nir_src_rewrite(use, rep); + } + impl_progress = true; + } + } + _mesa_hash_table_destroy(clone_map, NULL); + } + + ralloc_free(mem_ctx); + + if (impl_progress) { + nir_progress(true, impl, nir_metadata_control_flow); + progress = true; + } else { + nir_no_progress(impl); + } + } + + return progress; +} diff --git a/src/asahi/compiler/test/test-shared-byte-offsets.cpp b/src/asahi/compiler/test/test-shared-byte-offsets.cpp index 669a6fdeaf6c..5f78d7af8f51 100644 --- a/src/asahi/compiler/test/test-shared-byte-offsets.cpp +++ b/src/asahi/compiler/test/test-shared-byte-offsets.cpp @@ -1426,7 +1426,7 @@ TEST(SharedByteOffsets, BitfieldSlicesOverBudgetPreservesValue) }; const uint32_t expected = eval_u32_nir(st->src[0].ssa, vals); - EXPECT_FALSE(agx_nir_opt_bitfield_slices(b.shader)); + agx_nir_opt_bitfield_slices(b.shader); nir_opt_dce(b.shader); nir_validate_shader(b.shader, "bitfield-slices-over-budget-8 result"); @@ -1434,3 +1434,199 @@ TEST(SharedByteOffsets, BitfieldSlicesOverBudgetPreservesValue) EXPECT_EQ(actual, expected); ralloc_free(b.shader); } + +/* imadshl_agx(a, 1, b, k) and iand(ushr(x, k), mask) merge into one extract. */ +TEST(SharedByteOffsets, BitfieldSlicesImadshlAndShiftedMask) +{ + nir_builder b = workgroup_shader("bitfield-slices-imadshl"); + nir_def *x = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .range = 4); + + nir_def *bit4 = nir_iand_imm(&b, nir_ushr_imm(&b, x, 4), 0x1); + nir_def *hi = nir_ushr_imm(&b, x, 5); + nir_def *comb = + nir_imadshl_agx(&b, bit4, nir_imm_int(&b, 1), hi, nir_imm_int(&b, 1)); + nir_store_global(&b, comb, nir_imm_int64(&b, 0), .align_mul = 4); + + EXPECT_TRUE(agx_nir_opt_bitfield_slices(b.shader)); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "bitfield-slices-imadshl result"); + + unsigned imadshls = 0, iands = 0, ushrs = 0; + nir_foreach_block(block, b.impl) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_alu) + continue; + nir_alu_instr *alu = nir_instr_as_alu(instr); + if (alu->op == nir_op_imadshl_agx) + imadshls++; + else if (alu->op == nir_op_iand) + iands++; + else if (alu->op == nir_op_ushr) + ushrs++; + } + } + EXPECT_EQ(imadshls, 0u); + EXPECT_EQ(iands, 0u); + EXPECT_EQ(ushrs, 1u); + ralloc_free(b.shader); +} + +/* Pure epilogue-only defs sink past high-pressure compute loops. */ +TEST(SharedByteOffsets, SinkEpilogueDefsPastHighPressureLoop) +{ + nir_builder b = workgroup_shader("sink-past-high-loop"); + nir_def *n = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .range = 4); + nir_def *lid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *epilogue_off = nir_imul_imm(&b, nir_iadd_imm(&b, lid, 7), 12); + + nir_def *live[52]; + for (unsigned i = 0; i < 52; i++) + live[i] = nir_iadd_imm(&b, n, i + 1); + + nir_loop *loop = nir_push_loop(&b); + nir_block *preheader = nir_loop_predecessor_block(loop); + nir_phi_instr *idx_phi = create_scalar_phi(b.shader); + nir_phi_instr_add_src(idx_phi, preheader, nir_imm_int(&b, 0)); + nir_instr_insert(nir_before_block(nir_loop_first_block(loop)), + &idx_phi->instr); + b.cursor = nir_after_phis(nir_loop_first_block(loop)); + + nir_def *acc = &idx_phi->def; + for (unsigned i = 0; i < 52; i++) + acc = nir_iadd(&b, acc, live[i]); + nir_def *next = nir_iadd_imm(&b, &idx_phi->def, 1); + nir_push_if(&b, nir_uge(&b, next, n)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_phi_instr_add_src(idx_phi, nir_cursor_current_block(b.cursor), next); + nir_pop_loop(&b, loop); + + nir_block *after = nir_cursor_current_block(b.cursor); + nir_store_global(&b, nir_iadd(&b, acc, epilogue_off), nir_imm_int64(&b, 0), + .align_mul = 4); + + EXPECT_TRUE(agx_nir_opt_sink_past_loops(b.shader)); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "sink-past-high-loop result"); + + bool found_imul_after = false; + nir_foreach_instr(instr, after) { + if (instr->type == nir_instr_type_alu && + nir_instr_as_alu(instr)->op == nir_op_imul) + found_imul_after = true; + } + EXPECT_TRUE(found_imul_after); + ralloc_free(b.shader); +} + +/* Two sequential high-pressure loops: Pass B on the first loop rematerializes + * a pure tree into the between-loops block, allocating SSA IDs >= the initial + * est.ssa_alloc. Pass B on the second loop must skip those out-of-range IDs + * without reading past est.halves. */ +TEST(SharedByteOffsets, SinkEpilogueTwoSequentialLoopsRematBounds) +{ + nir_builder b = workgroup_shader("sink-two-high-loops"); + nir_def *n = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .range = 4); + nir_def *lid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *remat = nir_imul_imm(&b, nir_iadd_imm(&b, lid, 5), 3); + + nir_def *live[52]; + for (unsigned i = 0; i < 52; i++) + live[i] = nir_iadd_imm(&b, n, i + 1); + + nir_loop *loop1 = nir_push_loop(&b); + nir_block *pre1 = nir_loop_predecessor_block(loop1); + nir_phi_instr *phi1 = create_scalar_phi(b.shader); + nir_phi_instr_add_src(phi1, pre1, nir_imm_int(&b, 0)); + nir_instr_insert(nir_before_block(nir_loop_first_block(loop1)), + &phi1->instr); + b.cursor = nir_after_phis(nir_loop_first_block(loop1)); + nir_def *acc1 = nir_iadd(&b, &phi1->def, remat); + for (unsigned i = 0; i < 52; i++) + acc1 = nir_iadd(&b, acc1, live[i]); + nir_def *next1 = nir_iadd_imm(&b, &phi1->def, 1); + nir_push_if(&b, nir_uge(&b, next1, n)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_phi_instr_add_src(phi1, nir_cursor_current_block(b.cursor), next1); + nir_pop_loop(&b, loop1); + + nir_def *mid = nir_iadd(&b, acc1, remat); + + nir_loop *loop2 = nir_push_loop(&b); + nir_block *pre2 = nir_loop_predecessor_block(loop2); + nir_phi_instr *phi2 = create_scalar_phi(b.shader); + nir_phi_instr_add_src(phi2, pre2, nir_imm_int(&b, 0)); + nir_instr_insert(nir_before_block(nir_loop_first_block(loop2)), + &phi2->instr); + b.cursor = nir_after_phis(nir_loop_first_block(loop2)); + nir_def *acc2 = nir_iadd(&b, &phi2->def, mid); + for (unsigned i = 0; i < 52; i++) + acc2 = nir_iadd(&b, acc2, live[i]); + nir_def *next2 = nir_iadd_imm(&b, &phi2->def, 1); + nir_push_if(&b, nir_uge(&b, next2, n)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_phi_instr_add_src(phi2, nir_cursor_current_block(b.cursor), next2); + nir_pop_loop(&b, loop2); + + nir_store_global(&b, nir_iadd(&b, acc2, remat), nir_imm_int64(&b, 0), + .align_mul = 4); + + const unsigned orig_ssa_alloc = b.impl->ssa_alloc; + EXPECT_TRUE(agx_nir_opt_sink_past_loops(b.shader)); + EXPECT_GT(b.impl->ssa_alloc, orig_ssa_alloc); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "sink-two-high-loops result"); + ralloc_free(b.shader); +} + +/* Over-budget (> 12 terms) imadshl_agx tree with mergeable slices must never + * drop its shifted right operand when the collector fills its 12-term buffer. */ +TEST(SharedByteOffsets, BitfieldSlicesOverBudgetImadshlPreservesValue) +{ + nir_builder b = workgroup_shader("bitfield-slices-over-budget"); + nir_def *x = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .range = 4); + nir_def *t[10]; + for (unsigned i = 0; i < 10; i++) + t[i] = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, (i + 1) * 4), + .range = 4); + nir_def *y = + nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 44), .range = 4); + nir_def *t10 = + nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 48), .range = 4); + + /* Place s0 in l0 and s1 in l2 so no proper subtree contains both slices. + * left13 has 13 terms (t0..t10 + s0 + s1), exceeding the 12-term buffer + * before the root imadshl_agx adds (y << 5). */ + nir_def *s0 = nir_iand_imm(&b, x, 0xfu); + nir_def *s1 = nir_ishl_imm(&b, nir_ubitfield_extract_imm(&b, x, 4, 4), 4); + + nir_def *l0 = nir_iadd(&b, nir_iadd(&b, s0, t[0]), nir_iadd(&b, t[1], t[2])); + nir_def *l1 = nir_iadd(&b, nir_iadd(&b, t[3], t[4]), nir_iadd(&b, t[5], t[6])); + nir_def *l2 = + nir_iadd(&b, nir_iadd(&b, t[7], t[8]), nir_iadd(&b, t[9], nir_iadd(&b, t10, s1))); + nir_def *left13 = nir_iadd(&b, nir_iadd(&b, l0, l1), l2); + + nir_def *root = + nir_imadshl_agx(&b, left13, nir_imm_int(&b, 1), y, nir_imm_int(&b, 5)); + nir_intrinsic_instr *st = + nir_store_global(&b, root, nir_imm_int64(&b, 0), .align_mul = 4); + + uint32_t vals[13] = { + 0x12345678u, /* x */ + 0x00010001u, 0x00020003u, 0x00040005u, 0x00060007u, 0x00080009u, + 0x000a000bu, 0x000c000du, 0x000e000fu, 0x00100011u, 0x00120013u, + 0x00000077u, /* y */ + 0x00140015u, /* t10 */ + }; + const uint32_t expected = eval_u32_nir(st->src[0].ssa, vals); + + EXPECT_FALSE(agx_nir_opt_bitfield_slices(b.shader)); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "bitfield-slices-over-budget result"); + + const uint32_t actual = eval_u32_nir(st->src[0].ssa, vals); + EXPECT_EQ(actual, expected); + ralloc_free(b.shader); +} From 3048958d8292fd018762fb9bee1cf8536ea20844 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Tue, 1 Dec 2026 15:22:57 -0500 Subject: [PATCH 4/6] asahi: restore valid loop phis in AGX regression tests Define each initial value in the preheader and add both operands before inserting the phi. This restores the tested fixtures that were lost while resolving the rebase conflict. Signed-off-by: DjDeveloperr --- .../test/test-shared-byte-offsets.cpp | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/asahi/compiler/test/test-shared-byte-offsets.cpp b/src/asahi/compiler/test/test-shared-byte-offsets.cpp index 5f78d7af8f51..3a0217d5c903 100644 --- a/src/asahi/compiler/test/test-shared-byte-offsets.cpp +++ b/src/asahi/compiler/test/test-shared-byte-offsets.cpp @@ -1483,13 +1483,11 @@ TEST(SharedByteOffsets, SinkEpilogueDefsPastHighPressureLoop) for (unsigned i = 0; i < 52; i++) live[i] = nir_iadd_imm(&b, n, i + 1); + nir_def *zero = nir_imm_int(&b, 0); nir_loop *loop = nir_push_loop(&b); nir_block *preheader = nir_loop_predecessor_block(loop); nir_phi_instr *idx_phi = create_scalar_phi(b.shader); - nir_phi_instr_add_src(idx_phi, preheader, nir_imm_int(&b, 0)); - nir_instr_insert(nir_before_block(nir_loop_first_block(loop)), - &idx_phi->instr); - b.cursor = nir_after_phis(nir_loop_first_block(loop)); + nir_phi_instr_add_src(idx_phi, preheader, zero); nir_def *acc = &idx_phi->def; for (unsigned i = 0; i < 52; i++) @@ -1498,7 +1496,9 @@ TEST(SharedByteOffsets, SinkEpilogueDefsPastHighPressureLoop) nir_push_if(&b, nir_uge(&b, next, n)); nir_jump(&b, nir_jump_break); nir_pop_if(&b, NULL); - nir_phi_instr_add_src(idx_phi, nir_cursor_current_block(b.cursor), next); + nir_phi_instr_add_src(idx_phi, nir_loop_last_block(loop), next); + nir_instr_insert(nir_before_block(nir_loop_first_block(loop)), + &idx_phi->instr); nir_pop_loop(&b, loop); nir_block *after = nir_cursor_current_block(b.cursor); @@ -1534,13 +1534,11 @@ TEST(SharedByteOffsets, SinkEpilogueTwoSequentialLoopsRematBounds) for (unsigned i = 0; i < 52; i++) live[i] = nir_iadd_imm(&b, n, i + 1); + nir_def *zero = nir_imm_int(&b, 0); nir_loop *loop1 = nir_push_loop(&b); nir_block *pre1 = nir_loop_predecessor_block(loop1); nir_phi_instr *phi1 = create_scalar_phi(b.shader); - nir_phi_instr_add_src(phi1, pre1, nir_imm_int(&b, 0)); - nir_instr_insert(nir_before_block(nir_loop_first_block(loop1)), - &phi1->instr); - b.cursor = nir_after_phis(nir_loop_first_block(loop1)); + nir_phi_instr_add_src(phi1, pre1, zero); nir_def *acc1 = nir_iadd(&b, &phi1->def, remat); for (unsigned i = 0; i < 52; i++) acc1 = nir_iadd(&b, acc1, live[i]); @@ -1548,7 +1546,9 @@ TEST(SharedByteOffsets, SinkEpilogueTwoSequentialLoopsRematBounds) nir_push_if(&b, nir_uge(&b, next1, n)); nir_jump(&b, nir_jump_break); nir_pop_if(&b, NULL); - nir_phi_instr_add_src(phi1, nir_cursor_current_block(b.cursor), next1); + nir_phi_instr_add_src(phi1, nir_loop_last_block(loop1), next1); + nir_instr_insert(nir_before_block(nir_loop_first_block(loop1)), + &phi1->instr); nir_pop_loop(&b, loop1); nir_def *mid = nir_iadd(&b, acc1, remat); @@ -1556,10 +1556,7 @@ TEST(SharedByteOffsets, SinkEpilogueTwoSequentialLoopsRematBounds) nir_loop *loop2 = nir_push_loop(&b); nir_block *pre2 = nir_loop_predecessor_block(loop2); nir_phi_instr *phi2 = create_scalar_phi(b.shader); - nir_phi_instr_add_src(phi2, pre2, nir_imm_int(&b, 0)); - nir_instr_insert(nir_before_block(nir_loop_first_block(loop2)), - &phi2->instr); - b.cursor = nir_after_phis(nir_loop_first_block(loop2)); + nir_phi_instr_add_src(phi2, pre2, zero); nir_def *acc2 = nir_iadd(&b, &phi2->def, mid); for (unsigned i = 0; i < 52; i++) acc2 = nir_iadd(&b, acc2, live[i]); @@ -1567,7 +1564,9 @@ TEST(SharedByteOffsets, SinkEpilogueTwoSequentialLoopsRematBounds) nir_push_if(&b, nir_uge(&b, next2, n)); nir_jump(&b, nir_jump_break); nir_pop_if(&b, NULL); - nir_phi_instr_add_src(phi2, nir_cursor_current_block(b.cursor), next2); + nir_phi_instr_add_src(phi2, nir_loop_last_block(loop2), next2); + nir_instr_insert(nir_before_block(nir_loop_first_block(loop2)), + &phi2->instr); nir_pop_loop(&b, loop2); nir_store_global(&b, nir_iadd(&b, acc2, remat), nir_imm_int64(&b, 0), From 511da1d5eec9d33ca8cabe899e3da15c7adf6a10 Mon Sep 17 00:00:00 2001 From: Dylan Ironside Date: Wed, 2 Dec 2026 05:20:03 -0600 Subject: [PATCH 5/6] agx/licm: validate intrinsic sources on zero-reg remat leaves check_sink_remat_def() returned true immediately for zero-reg remat leaves including nir_intrinsic_load_push_constant and nir_intrinsic_load_kernel_input, both of which take an offset operand (src[0]), while clone_sink_remat_def() recursively clones every intrinsic source into the post-loop block. Call nir_foreach_src(instr, check_sink_remat_src, ctx) inside the is_zero_reg_remat_leaf() branch so dynamic non-rematerializable offsets (e.g. load_global, load_shared, phis, atomics, trapping integer div, or over-budget ALU trees) are rejected cleanly. Add a regression test in test-shared-byte-offsets.cpp covering a load_global offset feeding load_push_constant across a high-pressure loop. Signed-off-by: Dylan Ironside --- src/asahi/compiler/agx_nir_opt_licm.c | 2 + .../test/test-shared-byte-offsets.cpp | 67 +++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/src/asahi/compiler/agx_nir_opt_licm.c b/src/asahi/compiler/agx_nir_opt_licm.c index 081c4dcaabb7..43e784fa186a 100644 --- a/src/asahi/compiler/agx_nir_opt_licm.c +++ b/src/asahi/compiler/agx_nir_opt_licm.c @@ -1766,6 +1766,8 @@ check_sink_remat_def(nir_def *def, struct sink_remat_ctx *ctx) ctx->ok = false; return false; } + nir_foreach_src(instr, check_sink_remat_src, ctx); + return ctx->ok; } return true; } diff --git a/src/asahi/compiler/test/test-shared-byte-offsets.cpp b/src/asahi/compiler/test/test-shared-byte-offsets.cpp index 3a0217d5c903..6b4e25824d55 100644 --- a/src/asahi/compiler/test/test-shared-byte-offsets.cpp +++ b/src/asahi/compiler/test/test-shared-byte-offsets.cpp @@ -1580,6 +1580,73 @@ TEST(SharedByteOffsets, SinkEpilogueTwoSequentialLoopsRematBounds) ralloc_free(b.shader); } +/* Pass B must validate intrinsic sources on zero-reg remat leaves: a + * load_push_constant whose offset comes from a non-rematerializable load_global + * must not be cloned past a high-pressure loop. */ +TEST(SharedByteOffsets, SinkEpilogueRejectsDynamicPushConstantOffset) +{ + nir_builder b = workgroup_shader("sink-dyn-push-const"); + nir_def *n = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .range = 4); + nir_def *dyn_off = + nir_load_global(&b, 1, 32, nir_imm_int64(&b, 0x1000), .align_mul = 4); + nir_def *pc = nir_load_push_constant(&b, 1, 32, dyn_off, .range = 64); + nir_def *remat = nir_imul_imm(&b, pc, 3); + + nir_def *live[52]; + for (unsigned i = 0; i < 52; i++) + live[i] = nir_iadd_imm(&b, n, i + 1); + + nir_def *zero = nir_imm_int(&b, 0); + nir_loop *loop = nir_push_loop(&b); + nir_block *pre = nir_loop_predecessor_block(loop); + nir_phi_instr *phi = create_scalar_phi(b.shader); + nir_phi_instr_add_src(phi, pre, zero); + nir_def *acc = nir_iadd(&b, &phi->def, remat); + for (unsigned i = 0; i < 52; i++) + acc = nir_iadd(&b, acc, live[i]); + nir_def *next = nir_iadd_imm(&b, &phi->def, 1); + nir_push_if(&b, nir_uge(&b, next, n)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_phi_instr_add_src(phi, nir_loop_last_block(loop), next); + nir_instr_insert(nir_before_block(nir_loop_first_block(loop)), &phi->instr); + nir_pop_loop(&b, loop); + + nir_block *after = nir_cf_node_as_block(nir_cf_node_next(&loop->cf_node)); + nir_store_global(&b, nir_iadd(&b, acc, remat), nir_imm_int64(&b, 0), + .align_mul = 4); + + agx_nir_opt_sink_past_loops(b.shader); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "sink-dyn-push-const result"); + + unsigned global_loads = 0; + nir_foreach_block(block, b.impl) { + nir_foreach_instr(instr, block) { + if (instr->type == nir_instr_type_intrinsic && + nir_instr_as_intrinsic(instr)->intrinsic == + nir_intrinsic_load_global) + global_loads++; + } + } + EXPECT_EQ(global_loads, 1u); + + bool cloned_into_after = false; + nir_foreach_instr(instr, after) { + if (instr->type == nir_instr_type_alu && + nir_instr_as_alu(instr)->op == nir_op_imul) + cloned_into_after = true; + if (instr->type == nir_instr_type_intrinsic && + (nir_instr_as_intrinsic(instr)->intrinsic == + nir_intrinsic_load_push_constant || + nir_instr_as_intrinsic(instr)->intrinsic == + nir_intrinsic_load_global)) + cloned_into_after = true; + } + EXPECT_FALSE(cloned_into_after); + ralloc_free(b.shader); +} + /* Over-budget (> 12 terms) imadshl_agx tree with mergeable slices must never * drop its shifted right operand when the collector fills its 12-term buffer. */ TEST(SharedByteOffsets, BitfieldSlicesOverBudgetImadshlPreservesValue) From c9663bad4ef9f005b327d222a0972e46174ba474 Mon Sep 17 00:00:00 2001 From: Dylan Ironside Date: Wed, 2 Dec 2026 07:38:04 -0600 Subject: [PATCH 6/6] agx: gate agx_nir_opt_sink_past_loops to AGX3B compute shaders On AGX3C (e.g. J775c M5 Max), sinking epilogue definitions past an already-spilling high-pressure Q4_0 matmul loop can reduce carriers without crossing an occupancy tier while increasing spill/fill traffic and instructions, regressing Vulkan prefill throughput. Gate agx_nir_opt_sink_past_loops() in agx_compile_shader_nir_internal() to is_agx3b compute shaders while keeping agx_nir_opt_bitfield_slices() enabled across all AGX3 targets. Add an end-to-end compile test (SharedByteOffsets.SinkEpilogueGatedToAgx3b) verifying that AGX3B sinks an epilogue-only imul past a high-pressure compute loop while AGX3C leaves it before the loop. Signed-off-by: Dylan Ironside --- src/asahi/compiler/agx_compile.c | 5 +- .../test/test-shared-byte-offsets.cpp | 96 +++++++++++++++++++ 2 files changed, 100 insertions(+), 1 deletion(-) diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index 6c985c4ac10d..9c0a43f9ae91 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -21411,7 +21411,10 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, if (is_agx3) { NIR_PASS(post_opt_progress, nir, agx_nir_reassociate_loop_invariant_eq); - if (mesa_shader_stage_is_compute(nir->info.stage)) { + /* Gate loop sinking to AGX3B compute shaders: on AGX3C + * already-spilling matmul loops it can increase spill/fill traffic + * without improving occupancy. */ + if (is_agx3b && mesa_shader_stage_is_compute(nir->info.stage)) { bool sunk = false; NIR_PASS(sunk, nir, agx_nir_opt_sink_past_loops); if (sunk) { diff --git a/src/asahi/compiler/test/test-shared-byte-offsets.cpp b/src/asahi/compiler/test/test-shared-byte-offsets.cpp index 5cae796d9bb0..8848e3f16901 100644 --- a/src/asahi/compiler/test/test-shared-byte-offsets.cpp +++ b/src/asahi/compiler/test/test-shared-byte-offsets.cpp @@ -4,6 +4,7 @@ #include "agx_test.h" #include "compiler/nir/nir_builder.h" extern "C" { +#include "agx_compile.h" #include "agx_nir.h" #include "agx_nir_match_gemm.h" } @@ -1921,3 +1922,98 @@ TEST(SharedByteOffsets, BitfieldSlicesOverBudgetImadshlPreservesValue) EXPECT_EQ(actual, expected); ralloc_free(b.shader); } + +/* End-to-end compile gating: agx_nir_opt_sink_past_loops runs on AGX3B compute + * shaders and is disabled on AGX3C. */ +TEST(SharedByteOffsets, SinkEpilogueGatedToAgx3b) +{ + auto build_shader = []() { + nir_builder b = workgroup_shader("sink-past-loops-agx3b-only"); + nir_def *base = agx_test_load_preamble(&b, 1, 64, 0); + nir_def *n = agx_test_load_preamble(&b, 1, 32, 4); + nir_def *lid3 = nir_load_local_invocation_id(&b); + nir_def *tid = + nir_iadd(&b, nir_channel(&b, lid3, 0), + nir_ishl_imm(&b, nir_channel(&b, lid3, 1), 3)); + nir_def *byte_off = nir_u2u64(&b, nir_ishl_imm(&b, tid, 2)); + nir_def *a = + nir_load_global(&b, 1, 32, nir_iadd(&b, base, byte_off), .align_mul = 4); + nir_def *c = nir_load_global( + &b, 1, 32, nir_iadd_imm(&b, nir_iadd(&b, base, byte_off), 256), + .align_mul = 4); + nir_def *ep_val = nir_imul(&b, a, c); + + nir_def *live[52]; + for (unsigned i = 0; i < 52; i++) { + nir_def *addr = nir_iadd_imm( + &b, nir_iadd(&b, base, byte_off), (i + 2) * 256); + live[i] = nir_load_global(&b, 1, 32, addr, .align_mul = 4); + } + + nir_def *zero = nir_imm_int(&b, 0); + nir_loop *loop = nir_push_loop(&b); + nir_block *pre = nir_loop_predecessor_block(loop); + nir_phi_instr *idx_phi = create_scalar_phi(b.shader); + nir_phi_instr_add_src(idx_phi, pre, zero); + nir_phi_instr *acc_phi = create_scalar_phi(b.shader); + nir_phi_instr_add_src(acc_phi, pre, zero); + + nir_def *acc = &acc_phi->def; + for (unsigned i = 0; i < 52; i++) + acc = nir_iadd(&b, acc, nir_ixor(&b, &idx_phi->def, live[i])); + nir_def *next = nir_iadd_imm(&b, &idx_phi->def, 1); + nir_push_if(&b, nir_uge(&b, next, n)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_phi_instr_add_src(idx_phi, nir_loop_last_block(loop), next); + nir_phi_instr_add_src(acc_phi, nir_loop_last_block(loop), acc); + nir_instr_insert(nir_before_block(nir_loop_first_block(loop)), + &idx_phi->instr); + nir_instr_insert(nir_before_block(nir_loop_first_block(loop)), + &acc_phi->instr); + nir_pop_loop(&b, loop); + + nir_store_global(&b, nir_ixor(&b, acc, ep_val), + nir_iadd(&b, base, byte_off), .align_mul = 4); + return b.shader; + }; + + auto block_has_imul = [](nir_block *block) { + nir_foreach_instr(instr, block) { + if (instr->type == nir_instr_type_alu && + nir_instr_as_alu(instr)->op == nir_op_imul) + return true; + } + return false; + }; + + nir_shader *s_3b = build_shader(); + agx_preprocess_nir_native(s_3b, AGX_CHIP_G16G); + struct agx_shader_key k_3b = {}; + k_3b.dev.chip = AGX_CHIP_G16G; + k_3b.dev.encoding = AGX_ISA_ENCODING_AGX3B; + k_3b.reserved_preamble = 16; + k_3b.no_preamble = true; + struct agx_shader_part out_3b = {}; + ASSERT_TRUE(agx_compile_shader_nir(s_3b, &k_3b, &out_3b)); + nir_function_impl *impl_3b = nir_shader_get_entrypoint(s_3b); + EXPECT_FALSE(block_has_imul(nir_start_block(impl_3b))); + EXPECT_TRUE(block_has_imul(nir_impl_last_block(impl_3b))); + free(out_3b.binary); + ralloc_free(s_3b); + + nir_shader *s_3c = build_shader(); + agx_preprocess_nir_m5_chip(s_3c, AGX_CHIP_G17C); + struct agx_shader_key k_3c = {}; + k_3c.dev.chip = AGX_CHIP_G17C; + k_3c.dev.encoding = AGX_ISA_ENCODING_AGX3C; + k_3c.reserved_preamble = 16; + k_3c.no_preamble = true; + struct agx_shader_part out_3c = {}; + ASSERT_TRUE(agx_compile_shader_nir(s_3c, &k_3c, &out_3c)); + nir_function_impl *impl_3c = nir_shader_get_entrypoint(s_3c); + EXPECT_TRUE(block_has_imul(nir_start_block(impl_3c))); + EXPECT_FALSE(block_has_imul(nir_impl_last_block(impl_3c))); + free(out_3c.binary); + ralloc_free(s_3c); +}