diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index d426a303d187..cc543ed27858 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -10399,6 +10399,74 @@ agx_nir_lower_g18_subgroups(nir_shader *nir) return progress; } +static void +agx_optimize_nir_late_tail(nir_shader *nir, bool g17p, bool g18_scans, + bool agx3_compute_opts) +{ + bool progress; + + /* Do remaining lowering late, since this inserts &s for shifts so we want to + * do it after fusing constant shifts. Constant folding will clean up. + */ + /* Must precede agx_nir_lower_algebraic_late, which rewrites extract_u16 + * into u2u32(unpack_32_2x16_split_y) (the pass also matches that form). */ + NIR_PASS(_, nir, agx_nir_fold_extract16_bfe); + NIR_PASS(_, nir, agx_nir_lower_algebraic_late); + if (g18_scans) + NIR_PASS(_, nir, agx_nir_avoid_square_overflow); + NIR_PASS(_, nir, agx_nir_fold_pixel_coord); + if (agx3_compute_opts) { + bool fused_selects = false; + for (unsigned iter = 0; iter < 4; ++iter) { + bool p = false; + NIR_PASS(p, nir, agx_nir_fuse_selects); + fused_selects |= p; + if (!p) + break; + NIR_PASS(_, nir, nir_opt_dce); + } + NIR_PASS(_, nir, agx_nir_fold_const_select_alu); + if (fused_selects) + NIR_PASS(_, nir, nir_opt_remove_phis); + } else { + NIR_PASS(_, nir, agx_nir_fuse_selects); + } + NIR_PASS(_, nir, nir_opt_constant_folding); + NIR_PASS(_, nir, nir_opt_combine_barriers, NULL, NULL); + NIR_PASS(_, nir, nir_opt_copy_prop); + NIR_PASS(_, nir, nir_opt_dce); + NIR_PASS(_, nir, nir_opt_cse); + NIR_PASS(_, nir, nir_lower_alu_to_scalar, NULL, NULL); + NIR_PASS(_, nir, nir_lower_load_const_to_scalar); + + /* Cleanup optimizations */ + nir_move_options move_all = nir_move_const_undef | nir_move_load_ubo | + nir_move_load_input | nir_move_load_frag_coord | + nir_move_comparisons | nir_move_copies | + nir_move_load_ssbo | nir_move_alu; + if (agx_has_derivative_in_control_flow(nir)) + move_all &= ~(nir_move_load_input | nir_move_load_frag_coord | + nir_move_alu); + + /* Sinking a G17P buffer load into the arm that reads it saves the load when + * the arm is skipped. Sink leaves it at the top of that block; moving it on + * to its use would make each load wait alone instead of overlapping. + */ + NIR_PASS(_, nir, nir_opt_sink, + g17p ? move_all : move_all & ~nir_move_load_ssbo); + NIR_PASS(_, nir, nir_opt_move, move_all & ~nir_move_load_ssbo); + NIR_PASS(progress, nir, nir_lower_all_phis_to_scalar); + + /* After lowering phis to scalar, we must copy prop/DCE for correctness. RA + * can't deal with dead phis. + */ + do { + NIR_PASS(progress, nir, nir_opt_copy_prop); + NIR_PASS(progress, nir, nir_opt_dce); + progress = false; + } while (progress); +} + static void agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, bool byte_indices, bool discard_word, bool g17p, bool m5, @@ -10518,16 +10586,24 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, NIR_PASS(_, nir, nir_opt_peephole_select, &peephole_select_options); /* Small uniform ifs whose arms load from memory, which peephole select - * keeps: on M5 an if costs five control-flow instructions and a wait for - * every load in flight. Flattening one can expose another around it. - * Not on G18G, which compiles as AGX3C with emit_agx3d (g18_scans). */ - if (m5 && !g18_scans) { + * keeps: on AGX3 (AGX3B and AGX3C) an if costs control-flow instructions + * and a wait for every load in flight. Flattening one can expose another + * around it. Not on G18G, which compiles as AGX3C with emit_agx3d + * (g18_scans). */ + if (agx3_compute_opts) { + /* Use a single encoding-uniform select limit across AGX3B and AGX3C so + * G15G/G16G/G17P/G17S flatten identically inside the load-flatten loop. */ + nir_opt_peephole_select_options flatten_select_options = { + .limit = 64, + .expensive_alu_ok = true, + .expensive_limit = 0, + }; bool flattened; do { flattened = false; NIR_PASS(flattened, nir, agx_nir_opt_flatten_loads, 64, 4); NIR_PASS(flattened, nir, nir_opt_peephole_select, - &peephole_select_options); + &flatten_select_options); } while (flattened); NIR_PASS(_, nir, nir_opt_algebraic); NIR_PASS(_, nir, nir_opt_cse); @@ -10845,66 +10921,7 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, nir_index_ssa_defs(impl); } - /* Do remaining lowering late, since this inserts &s for shifts so we want to - * do it after fusing constant shifts. Constant folding will clean up. - */ - /* Must precede agx_nir_lower_algebraic_late, which rewrites extract_u16 - * into u2u32(unpack_32_2x16_split_y) (the pass also matches that form). */ - NIR_PASS(_, nir, agx_nir_fold_extract16_bfe); - NIR_PASS(_, nir, agx_nir_lower_algebraic_late); - if (g18_scans) - NIR_PASS(_, nir, agx_nir_avoid_square_overflow); - NIR_PASS(_, nir, agx_nir_fold_pixel_coord); - if (agx3_compute_opts) { - bool fused_selects = false; - for (unsigned iter = 0; iter < 4; ++iter) { - bool p = false; - NIR_PASS(p, nir, agx_nir_fuse_selects); - fused_selects |= p; - if (!p) - break; - NIR_PASS(_, nir, nir_opt_dce); - } - NIR_PASS(_, nir, agx_nir_fold_const_select_alu); - if (fused_selects) - NIR_PASS(_, nir, nir_opt_remove_phis); - } else { - NIR_PASS(_, nir, agx_nir_fuse_selects); - } - NIR_PASS(_, nir, nir_opt_constant_folding); - NIR_PASS(_, nir, nir_opt_combine_barriers, NULL, NULL); - NIR_PASS(_, nir, nir_opt_copy_prop); - NIR_PASS(_, nir, nir_opt_dce); - NIR_PASS(_, nir, nir_opt_cse); - NIR_PASS(_, nir, nir_lower_alu_to_scalar, NULL, NULL); - NIR_PASS(_, nir, nir_lower_load_const_to_scalar); - - /* Cleanup optimizations */ - nir_move_options move_all = nir_move_const_undef | nir_move_load_ubo | - nir_move_load_input | nir_move_load_frag_coord | - nir_move_comparisons | nir_move_copies | - nir_move_load_ssbo | nir_move_alu; - if (agx_has_derivative_in_control_flow(nir)) - move_all &= ~(nir_move_load_input | nir_move_load_frag_coord | - nir_move_alu); - - /* Sinking a G17P buffer load into the arm that reads it saves the load when - * the arm is skipped. Sink leaves it at the top of that block; moving it on - * to its use would make each load wait alone instead of overlapping. - */ - NIR_PASS(_, nir, nir_opt_sink, - g17p ? move_all : move_all & ~nir_move_load_ssbo); - NIR_PASS(_, nir, nir_opt_move, move_all & ~nir_move_load_ssbo); - NIR_PASS(progress, nir, nir_lower_all_phis_to_scalar); - - /* After lowering phis to scalar, we must copy prop/DCE for correctness. RA - * can't deal with dead phis. - */ - do { - NIR_PASS(progress, nir, nir_opt_copy_prop); - NIR_PASS(progress, nir, nir_opt_dce); - progress = false; - } while (progress); + agx_optimize_nir_late_tail(nir, g17p, g18_scans, agx3_compute_opts); } /* @@ -16559,14 +16576,36 @@ agx_compile_shader_nir_once(nir_shader *nir, struct agx_shader_key *key, if (is_agx3 && source_imul64) NIR_PASS(_, nir, agx_nir_lower_imul64, m5_wide_product); + /* AGX_G17P_UNIFORM_DMA: only when no preamble is formed. Turning UBO loads + * inside short-circuit branches into load_preamble makes those branches + * trivial; fold them to selects just as the form_preamble path does. */ + if (is_agx3 && key->g17p_uniform_dma && !form_preamble && + agx3_nir_lower_uniform_dma(nir, key, info)) { + nir_opt_peephole_select_options peephole_select_options = { + .limit = 64, + .expensive_alu_ok = true, + .expensive_limit = 0, + }; + bool dma_folded = false; + NIR_PASS(dma_folded, nir, nir_opt_peephole_select, + &peephole_select_options); + if (dma_folded) { + if (key->dev.encoding == AGX_ISA_ENCODING_AGX3B) + NIR_PASS(_, nir, agx_nir_scalarize_int64); + NIR_PASS(_, nir, nir_lower_int64); + const bool post_dma_agx3_opts = + (key->dev.encoding == AGX_ISA_ENCODING_AGX3B || + key->dev.encoding == AGX_ISA_ENCODING_AGX3C) && + !key->dev.emit_agx3d; + agx_optimize_nir_late_tail(nir, key->dev.chip == AGX_CHIP_G17P, + key->dev.emit_agx3d, post_dma_agx3_opts); + nir_divergence_analysis(nir); + } + } + if (is_agx3) nir->options = original_options; - /* AGX_G17P_UNIFORM_DMA: only when no preamble is formed. */ - if (is_agx3 && key->g17p_uniform_dma && !form_preamble && - agx3_nir_lower_uniform_dma(nir, key, info)) - NIR_PASS(_, nir, nir_opt_dce); - /* Late NIR cleanup can remove main-program uses of values exported by * preamble extraction. Preserve their SSA uses inside the CProg, while * dropping writes to general uniform slots nobody reads anymore. diff --git a/src/asahi/compiler/agx_nir_opt_flatten_loads.c b/src/asahi/compiler/agx_nir_opt_flatten_loads.c index bbba2ea95d64..5e7989a9fd21 100644 --- a/src/asahi/compiler/agx_nir_opt_flatten_loads.c +++ b/src/asahi/compiler/agx_nir_opt_flatten_loads.c @@ -9,6 +9,8 @@ #include "nir.h" #include "nir_intrinsics.h" #include "nir_intrinsics_indices.h" +#include "util/hash_table.h" +#include "util/set.h" /* * Flatten small uniform ifs whose arms load from memory. @@ -47,10 +49,15 @@ * condition), so the result is unchanged; what the untaken arm's loads return * is discarded by the selects. * - * Only ifs with a uniform condition whose arms are single blocks of at most - * `limit` counted instructions and `max_loads` memory reads, both arms - * together, are flattened: the untaken arm's work is executed too, and a - * large arm costs more than the branch saves. + * Flattening handles two cases: + * - Uniform ifs whose arms are single blocks of at most `limit` counted + * instructions and `max_loads` memory reads, both arms together: the + * untaken arm's work is executed too, so a large arm costs more than the + * branch saves. + * - Bursts of at least 4 sibling single-load divergent ifs in the same CF + * list (each with one empty arm, one non-constant-buffer data load, and at + * most MIN2(limit, 24) counted ops), where flattening replaces >= 4 serial + * control-flow load-wait barriers with back-to-back overlapping loads. */ struct flatten_options { @@ -312,7 +319,8 @@ reads_memory(nir_intrinsic_instr *intr) } struct arm_cost { - unsigned count, loads, redirects; + unsigned count, loads, redirects, data_loads; + bool has_const_global; }; /* Whether every instruction of `block` may run with its if's condition false @@ -337,8 +345,14 @@ arm_is_flattenable(nir_shader *shader, nir_block *block, struct arm_cost *cost) (nir_intrinsic_access(intr) & (ACCESS_VOLATILE | ACCESS_ATOMIC))) return false; + if (is_redirectable_load(intr) && + intr->intrinsic != nir_intrinsic_load_global_constant) + cost->data_loads++; + if (load_needs_redirect(shader, intr)) { cost->redirects++; + if (intr->intrinsic == nir_intrinsic_load_global_constant) + cost->has_const_global = true; } else if (!(is_redirectable_load(intr) && (nir_intrinsic_access(intr) & ACCESS_CAN_SPECULATE)) && !nir_instr_can_speculate(instr)) { @@ -394,9 +408,539 @@ redirect_loads(nir_builder *b, nir_block *block, nir_def *taken) } } +static bool +def_outside_if_arms(nir_def *def, nir_block *then_block, nir_block *else_block) +{ + nir_block *blk = nir_def_instr(def)->block; + return blk != then_block && blk != else_block; +} + +static bool +alu_op_is_commutative_int(nir_op op) +{ + switch (op) { + case nir_op_iadd: + case nir_op_imul: + case nir_op_amul: + case nir_op_iand: + case nir_op_ior: + case nir_op_ixor: + case nir_op_imin: + case nir_op_imax: + case nir_op_umin: + case nir_op_umax: + return true; + default: + return false; + } +} + +static bool +same_pure_expr(nir_def *a, nir_def *b, nir_block *then_block, + nir_block *else_block, unsigned depth, unsigned *budget) +{ + if (*budget == 0) + return false; + (*budget)--; + + if (a == b) + return def_outside_if_arms(a, then_block, else_block); + + if (depth == 0 || a->bit_size != b->bit_size || + a->num_components != b->num_components) + return false; + + nir_instr *ia = nir_def_instr(a); + nir_instr *ib = nir_def_instr(b); + if (ia->type != ib->type) + return false; + + if (ia->type == nir_instr_type_load_const) { + nir_load_const_instr *ca = nir_instr_as_load_const(ia); + nir_load_const_instr *cb = nir_instr_as_load_const(ib); + for (unsigned i = 0; i < a->num_components; ++i) { + if (nir_const_value_as_uint(ca->value[i], a->bit_size) != + nir_const_value_as_uint(cb->value[i], b->bit_size)) + return false; + } + return true; + } + + if (ia->type != nir_instr_type_alu) + return false; + + nir_alu_instr *aa = nir_instr_as_alu(ia); + nir_alu_instr *ab = nir_instr_as_alu(ib); + if (aa->op != ab->op || aa->fp_math_ctrl != ab->fp_math_ctrl || + aa->no_signed_wrap != ab->no_signed_wrap || + aa->no_unsigned_wrap != ab->no_unsigned_wrap) + return false; + + const unsigned n = nir_op_infos[aa->op].num_inputs; + bool direct = true; + for (unsigned i = 0; i < n; ++i) { + unsigned comps = nir_ssa_alu_instr_src_components(aa, i); + if (memcmp(aa->src[i].swizzle, ab->src[i].swizzle, comps) != 0 || + !same_pure_expr(aa->src[i].src.ssa, ab->src[i].src.ssa, then_block, + else_block, depth - 1, budget)) { + direct = false; + break; + } + } + if (direct) + return true; + + if (n == 2 && alu_op_is_commutative_int(aa->op)) { + unsigned c0 = nir_ssa_alu_instr_src_components(aa, 0); + unsigned c1 = nir_ssa_alu_instr_src_components(aa, 1); + if (c0 == c1 && + memcmp(aa->src[0].swizzle, ab->src[1].swizzle, c0) == 0 && + memcmp(aa->src[1].swizzle, ab->src[0].swizzle, c1) == 0 && + same_pure_expr(aa->src[0].src.ssa, ab->src[1].src.ssa, then_block, + else_block, depth - 1, budget) && + same_pure_expr(aa->src[1].src.ssa, ab->src[0].src.ssa, then_block, + else_block, depth - 1, budget)) + return true; + } + + return false; +} + +static nir_def * +clone_pure_expr(nir_builder *b, nir_def *def, nir_block *then_block, + nir_block *else_block, struct hash_table *remap) +{ + if (def_outside_if_arms(def, then_block, else_block)) + return def; + + struct hash_entry *he = _mesa_hash_table_search(remap, def); + if (he) + return he->data; + + nir_instr *instr = nir_def_instr(def); + if (instr->type == nir_instr_type_alu) { + nir_alu_instr *alu = nir_instr_as_alu(instr); + for (unsigned i = 0; i < nir_op_infos[alu->op].num_inputs; ++i) + clone_pure_expr(b, alu->src[i].src.ssa, then_block, else_block, remap); + } + + nir_instr *clone = nir_instr_clone_deep(b->shader, instr, remap); + nir_builder_instr_insert(b, clone); + nir_def *res = nir_instr_def(clone); + _mesa_hash_table_insert(remap, def, res); + return res; +} + +static void +dce_pure_arm(nir_block *block) +{ + nir_foreach_instr_reverse_safe(instr, block) { + if (instr->type != nir_instr_type_alu && + instr->type != nir_instr_type_load_const && + instr->type != nir_instr_type_undef) + continue; + nir_def *def = nir_instr_def(instr); + if (def && list_is_empty(&def->uses)) + nir_instr_remove(instr); + } +} + +/* Sink matching terminal store_shared instructions out of a single-block + * if/else diamond into one store_shared(phi(v_then, v_else), saddr) after the + * if. This removes duplicate shared-address ALU and leaves the if with only + * its load arm, allowing burst flattening or peephole-select to remove the CF. + */ +static bool +sink_common_store_shared(nir_builder *b, nir_block *block) +{ + if (nir_cf_node_is_first(&block->cf_node)) + return false; + + nir_cf_node *prev_node = nir_cf_node_prev(&block->cf_node); + if (prev_node->type != nir_cf_node_if) + return false; + + nir_block *prev_block = nir_cf_node_as_block(nir_cf_node_prev(prev_node)); + if (nir_block_ends_in_jump(prev_block)) + return false; + + nir_if *nif = nir_cf_node_as_if(prev_node); + nir_block *then_block = nir_if_first_then_block(nif); + nir_block *else_block = nir_if_first_else_block(nif); + if (nir_if_last_then_block(nif) != then_block || + nir_if_last_else_block(nif) != else_block || + nir_block_ends_in_jump(then_block) || + nir_block_ends_in_jump(else_block)) + return false; + + nir_instr *then_last = nir_block_last_instr(then_block); + nir_instr *else_last = nir_block_last_instr(else_block); + if (!then_last || !else_last || + then_last->type != nir_instr_type_intrinsic || + else_last->type != nir_instr_type_intrinsic) + return false; + + nir_intrinsic_instr *ts = nir_instr_as_intrinsic(then_last); + nir_intrinsic_instr *es = nir_instr_as_intrinsic(else_last); + if (ts->intrinsic != nir_intrinsic_store_shared || + es->intrinsic != nir_intrinsic_store_shared) + return false; + + if ((nir_intrinsic_access(ts) | nir_intrinsic_access(es)) & + (ACCESS_VOLATILE | ACCESS_ATOMIC)) + return false; + + if (nir_intrinsic_base(ts) != nir_intrinsic_base(es) || + nir_intrinsic_write_mask(ts) != nir_intrinsic_write_mask(es) || + nir_intrinsic_align_mul(ts) != nir_intrinsic_align_mul(es) || + nir_intrinsic_align_offset(ts) != nir_intrinsic_align_offset(es) || + ts->src[0].ssa->bit_size != es->src[0].ssa->bit_size || + ts->src[0].ssa->num_components != es->src[0].ssa->num_components || + ts->src[1].ssa->bit_size != es->src[1].ssa->bit_size || + ts->src[1].ssa->num_components != es->src[1].ssa->num_components) + return false; + + unsigned expr_budget = 64; + if (!same_pure_expr(ts->src[1].ssa, es->src[1].ssa, then_block, else_block, + 8, &expr_budget)) + return false; + + b->cursor = nir_before_cf_node(&nif->cf_node); + struct hash_table *remap = _mesa_pointer_hash_table_create(NULL); + nir_def *hoisted_addr = + clone_pure_expr(b, ts->src[1].ssa, then_block, else_block, remap); + _mesa_hash_table_destroy(remap, NULL); + + nir_phi_instr *phi = nir_phi_instr_create(b->shader); + nir_def_init(&phi->instr, &phi->def, ts->src[0].ssa->num_components, + ts->src[0].ssa->bit_size); + nir_phi_instr_add_src(phi, then_block, ts->src[0].ssa); + nir_phi_instr_add_src(phi, else_block, es->src[0].ssa); + b->cursor = nir_before_block(block); + nir_builder_instr_insert(b, &phi->instr); + + b->cursor = nir_after_phis(block); + nir_store_shared(b, &phi->def, hoisted_addr, + .base = nir_intrinsic_base(ts), + .write_mask = nir_intrinsic_write_mask(ts), + .align_mul = nir_intrinsic_align_mul(ts), + .align_offset = nir_intrinsic_align_offset(ts), + .access = nir_intrinsic_access(ts) & + nir_intrinsic_access(es)); + + nir_instr_remove(&ts->instr); + nir_instr_remove(&es->instr); + dce_pure_arm(then_block); + dce_pure_arm(else_block); + return true; +} + +/* Divergent small single-load guarded if eligible as part of a sibling + * tile-load burst (>= 4 in one CF list). Excludes load_global_constant so UBO + * reads remain intact for agx3_nir_lower_uniform_dma. */ +static bool +is_divergent_burst_if(nir_shader *shader, nir_if *nif, + const struct flatten_options *options) +{ + if (nif->control == nir_selection_control_dont_flatten || + !nir_src_is_divergent(&nif->condition)) + return false; + + nir_block *prev_block = nir_cf_node_as_block(nir_cf_node_prev(&nif->cf_node)); + if (nir_block_ends_in_jump(prev_block)) + return false; + + nir_block *then_block = nir_if_first_then_block(nif); + nir_block *else_block = nir_if_first_else_block(nif); + if (nir_if_last_then_block(nif) != then_block || + nir_if_last_else_block(nif) != else_block) + return false; + + struct arm_cost tcost = {0}, ecost = {0}; + if (!arm_is_flattenable(shader, then_block, &tcost) || + !arm_is_flattenable(shader, else_block, &ecost)) + return false; + + unsigned total_loads = tcost.loads + ecost.loads; + unsigned total_data_loads = tcost.data_loads + ecost.data_loads; + unsigned total_count = tcost.count + ecost.count; + bool has_const_global = tcost.has_const_global || ecost.has_const_global; + + /* One data load (plus at most one speculatable descriptor load). Cap the + * arm at 24 counted ops (3/8 of the 64-op uniform limit): enough for a + * 2D/3D index + byte offset + bounds/descriptor setup (~8-16 ops) while + * bounding speculative untaken ALU across a multi-if burst. */ + return total_data_loads == 1 && total_loads <= 2 && + total_loads <= options->max_loads && + total_count <= MIN2(options->limit, 24u) && !has_const_global && + (tcost.count == 0 || ecost.count == 0); +} + +static bool +block_breaks_burst_run(nir_block *block) +{ + nir_foreach_instr(instr, block) { + switch (instr->type) { + case nir_instr_type_alu: + case nir_instr_type_load_const: + case nir_instr_type_undef: + case nir_instr_type_phi: + break; + case nir_instr_type_intrinsic: { + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + if (intr->intrinsic == nir_intrinsic_store_shared) { + if (nir_intrinsic_access(intr) & ACCESS_VOLATILE) + return true; + break; + } + if (nir_intrinsic_can_reorder(intr)) + break; + return true; + } + default: + return true; + } + } + return false; +} + +static void +flush_burst_run(struct set *burst_ifs, nir_if **run, unsigned *run_len) +{ + /* Require a contiguous run of >= 4 guarded loads (separated only by pure + * ALU or non-volatile store_shared, with no barriers or other CF nodes) + * before speculatively flattening divergent ifs: isolated 1-3 loads rarely + * amortize zero-page redirection on cold lanes, whereas >= 4 consecutive + * tile loads remove >= 4 serial load-wait barriers so global latencies + * overlap back-to-back and common tile-address ALU can hoist. */ + if (*run_len >= 4) { + for (unsigned i = 0; i < *run_len; ++i) + _mesa_set_add(burst_ifs, run[i]); + } + *run_len = 0; +} + +static void +collect_burst_ifs(nir_shader *shader, struct exec_list *cf_list, + const struct flatten_options *options, struct set *burst_ifs) +{ + nir_if *run[64]; + unsigned run_len = 0; + + foreach_list_typed(nir_cf_node, node, node, cf_list) { + if (node->type == nir_cf_node_block) { + if (block_breaks_burst_run(nir_cf_node_as_block(node))) + flush_burst_run(burst_ifs, run, &run_len); + } else if (node->type == nir_cf_node_if) { + nir_if *nif = nir_cf_node_as_if(node); + if (is_divergent_burst_if(shader, nif, options)) { + if (run_len < ARRAY_SIZE(run)) { + run[run_len++] = nif; + } else { + _mesa_set_add(burst_ifs, nif); + } + } else { + flush_burst_run(burst_ifs, run, &run_len); + } + collect_burst_ifs(shader, &nif->then_list, options, burst_ifs); + collect_burst_ifs(shader, &nif->else_list, options, burst_ifs); + } else if (node->type == nir_cf_node_loop) { + flush_burst_run(burst_ifs, run, &run_len); + collect_burst_ifs(shader, &nir_cf_node_as_loop(node)->body, options, + burst_ifs); + } + } + flush_burst_run(burst_ifs, run, &run_len); +} + +/* Match val == base + delta via 1..4 chained constant-offset iadd ops. */ +static bool +match_iv_step(nir_def *val, nir_def *base, int64_t *delta_out) +{ + int64_t total = 0; + nir_def *cur = val; + for (unsigned depth = 0; depth < 4 && cur != base; ++depth) { + nir_instr *instr = nir_def_instr(cur); + if (instr->type != nir_instr_type_alu) + return false; + nir_alu_instr *alu = nir_instr_as_alu(instr); + if (alu->op != nir_op_iadd) + return false; + 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]); + if (nir_scalar_is_const(s1)) { + total += nir_scalar_as_int(s1); + cur = alu->src[0].src.ssa; + } else if (nir_scalar_is_const(s0)) { + total += nir_scalar_as_int(s0); + cur = alu->src[1].src.ssa; + } else { + return false; + } + } + if (cur != base || total == 0) + return false; + *delta_out = total; + return true; +} + +static bool +cond_compares_iv(nir_def *cond, nir_def *iv, unsigned depth) +{ + nir_instr *ci = nir_def_instr(cond); + if (ci->type != nir_instr_type_alu) + return false; + nir_alu_instr *alu = nir_instr_as_alu(ci); + switch (alu->op) { + case nir_op_ilt: + case nir_op_ult: + case nir_op_ige: + case nir_op_uge: + case nir_op_ieq: + case nir_op_ine: + return alu->src[0].src.ssa == iv || alu->src[1].src.ssa == iv; + case nir_op_ior: + case nir_op_iand: + return depth > 0 && + (cond_compares_iv(alu->src[0].src.ssa, iv, depth - 1) || + cond_compares_iv(alu->src[1].src.ssa, iv, depth - 1)); + case nir_op_inot: + return depth > 0 && cond_compares_iv(alu->src[0].src.ssa, iv, depth - 1); + default: + return false; + } +} + +static bool +is_uniform_single_then_if(nir_if *nif) +{ + if (nir_src_is_divergent(&nif->condition)) + return false; + nir_block *tb = nir_if_first_then_block(nif); + nir_block *eb = nir_if_first_else_block(nif); + if (nir_if_last_then_block(nif) != tb || nir_if_last_else_block(nif) != eb) + return false; + return exec_list_is_empty(&eb->instr_list); +} + +static bool +match_tail_iv_step_if(nir_if *nif, nir_def *expected_iv, + nir_def **iv_out_out, int64_t *delta_out) +{ + if (!is_uniform_single_then_if(nif)) + return false; + + nir_block *tb = nir_if_first_then_block(nif); + nir_block *eb = nir_if_first_else_block(nif); + nir_block *merge = nir_cf_node_as_block(nir_cf_node_next(&nif->cf_node)); + nir_foreach_phi(phi, merge) { + if (phi->def.num_components != 1 || phi->def.bit_size != 32) + continue; + nir_phi_src *ts = nir_phi_get_src_from_block(phi, tb); + nir_phi_src *es = nir_phi_get_src_from_block(phi, eb); + if (!ts || !es) + continue; + nir_def *vin = es->src.ssa; + if (expected_iv && vin != expected_iv) + continue; + if (!cond_compares_iv(nif->condition.ssa, vin, 2)) + continue; + int64_t delta = 0; + if (!match_iv_step(ts->src.ssa, vin, &delta)) + continue; + int64_t ad = delta < 0 ? -delta : delta; + if (ad == 4 || ad == 2 || ad == 1) { + *iv_out_out = &phi->def; + *delta_out = delta; + return true; + } + } + return false; +} + +/* Binary-tail cascades emitted by agx_nir_unroll_runtime_loops consist of + * >= 2 sequential single-arm uniform ifs comparing a live induction variable + * and stepping it by halving power-of-2 deltas (+/-4 -> +/-2 -> +/-1, with + * the final 1-chunk allowed to drop the dead IV phi). Skip them locally inside + * load flattening without marking nir_selection_control_dont_flatten, so + * nir_opt_peephole_select stays free to fold pure-ALU / speculatable tails. */ +static void +collect_binary_tail_ifs(struct exec_list *cf_list, struct set *skip_ifs) +{ + struct { + nir_if *ifs[4]; + unsigned nifs; + nir_def *iv_out; + int64_t last_delta; + } chains[8]; + unsigned nchains = 0; + + foreach_list_typed(nir_cf_node, node, node, cf_list) { + if (node->type == nir_cf_node_if) { + nir_if *nif = nir_cf_node_as_if(node); + collect_binary_tail_ifs(&nif->then_list, skip_ifs); + collect_binary_tail_ifs(&nif->else_list, skip_ifs); + + bool extended = false; + for (unsigned c = 0; c < nchains; ++c) { + if (!chains[c].iv_out || chains[c].nifs >= ARRAY_SIZE(chains[c].ifs)) + continue; + int64_t abs_prev = chains[c].last_delta < 0 ? -chains[c].last_delta + : chains[c].last_delta; + if (abs_prev != 4 && abs_prev != 2) + continue; + nir_def *vout = NULL; + int64_t delta = 0; + if (match_tail_iv_step_if(nif, chains[c].iv_out, &vout, &delta) && + delta * 2 == chains[c].last_delta) { + chains[c].ifs[chains[c].nifs++] = nif; + chains[c].iv_out = vout; + chains[c].last_delta = delta; + extended = true; + break; + } + if (abs_prev == 2 && is_uniform_single_then_if(nif) && + cond_compares_iv(nif->condition.ssa, chains[c].iv_out, 2)) { + chains[c].ifs[chains[c].nifs++] = nif; + chains[c].iv_out = NULL; + chains[c].last_delta = chains[c].last_delta / 2; + extended = true; + break; + } + } + if (!extended && nchains < ARRAY_SIZE(chains)) { + nir_def *vout = NULL; + int64_t delta = 0; + if (match_tail_iv_step_if(nif, NULL, &vout, &delta)) { + int64_t ad = delta < 0 ? -delta : delta; + if (ad == 4 || ad == 2) { + chains[nchains].ifs[0] = nif; + chains[nchains].nifs = 1; + chains[nchains].iv_out = vout; + chains[nchains].last_delta = delta; + nchains++; + } + } + } + } else if (node->type == nir_cf_node_loop) { + collect_binary_tail_ifs(&nir_cf_node_as_loop(node)->body, skip_ifs); + } + } + + for (unsigned c = 0; c < nchains; ++c) { + if (chains[c].nifs < 2) + continue; + for (unsigned i = 0; i < chains[c].nifs; ++i) + _mesa_set_add(skip_ifs, chains[c].ifs[i]); + } +} + static bool flatten_block(nir_builder *b, nir_block *block, - const struct flatten_options *options) + const struct flatten_options *options, + const struct set *burst_ifs, const struct set *skip_ifs) { if (nir_cf_node_is_first(&block->cf_node)) return false; @@ -409,12 +953,16 @@ flatten_block(nir_builder *b, nir_block *block, if (nir_block_ends_in_jump(prev_block)) return false; - /* Only branches every lane takes the same way: a divergent if may run - * neither arm or one arm for a whole subgroup, and flattening it would run - * both every time. */ + /* Flatten branches every lane takes the same way, plus bursts of >= 4 + * sibling small single-load guarded ifs (such as tile-loading loops) where + * per-load control-flow barriers serialize memory latency. */ nir_if *nif = nir_cf_node_as_if(prev_node); if (nif->control == nir_selection_control_dont_flatten || - nir_src_is_divergent(&nif->condition)) + _mesa_set_search(skip_ifs, nif) != NULL) + return false; + + const bool in_burst = _mesa_set_search(burst_ifs, nif) != NULL; + if (nir_src_is_divergent(&nif->condition) && !in_burst) return false; nir_block *then_block = nir_if_first_then_block(nif); @@ -428,8 +976,10 @@ flatten_block(nir_builder *b, nir_block *block, !arm_is_flattenable(b->shader, else_block, &cost)) return false; - /* Ifs without loads to redirect are peephole select's. */ - if (cost.redirects == 0 || cost.loads > options->max_loads || + /* Uniform ifs without loads to redirect are peephole select's; burst ifs + * may hold speculatable data loads that peephole select skips when + * indirect_load_ok is false. */ + if ((!in_burst && cost.redirects == 0) || cost.loads > options->max_loads || cost.count > options->limit) return false; @@ -476,14 +1026,26 @@ agx_nir_opt_flatten_loads(nir_shader *shader, unsigned limit, bool progress = false; nir_foreach_function_impl(impl, shader) { - nir_metadata_require(impl, nir_metadata_divergence); nir_builder b = nir_builder_create(impl); - bool impl_progress = false; + bool sunk = false; + nir_foreach_block_safe(block, impl) + sunk |= sink_common_store_shared(&b, block); + if (sunk) + nir_progress(true, impl, nir_metadata_control_flow); + + nir_metadata_require(impl, nir_metadata_divergence); + struct set *burst_ifs = _mesa_pointer_set_create(NULL); + struct set *skip_ifs = _mesa_pointer_set_create(NULL); + collect_burst_ifs(shader, &impl->body, &options, burst_ifs); + collect_binary_tail_ifs(&impl->body, skip_ifs); + bool flattened = false; nir_foreach_block_safe(block, impl) - impl_progress |= flatten_block(&b, block, &options); + flattened |= flatten_block(&b, block, &options, burst_ifs, skip_ifs); - progress |= nir_progress(impl_progress, impl, nir_metadata_none); + _mesa_set_destroy(skip_ifs, NULL); + _mesa_set_destroy(burst_ifs, NULL); + progress |= nir_progress(sunk || flattened, impl, nir_metadata_none); } return progress; diff --git a/src/asahi/compiler/test/test-agx3-vision-opts.cpp b/src/asahi/compiler/test/test-agx3-vision-opts.cpp index b5dcfbd1dee4..3ad7dde71181 100644 --- a/src/asahi/compiler/test/test-agx3-vision-opts.cpp +++ b/src/asahi/compiler/test/test-agx3-vision-opts.cpp @@ -3357,3 +3357,164 @@ TEST(AGX3VisionOpts, ExactTailConstInitOmitsDeadFallback) ralloc_free(opt); } } + +TEST(AGX3VisionOpts, UniformDmaNoPreambleFoldsShortCircuitIf) +{ + /* When !form_preamble (AGX3B compute) lowers a uniform-DMA load inside a + * short-circuit branch into load_preamble, post-DMA peephole select must + * fold the now-trivial branch into a select rather than leaving control + * flow around load_preamble. */ + auto compile_once = [](enum agx_chip chip, bool dont_flatten) { + nir_builder b = make_compute_shader("uniform_dma_peephole"); + nir_def *gid = nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0); + nir_def *root = nir_load_preamble(&b, 1, 64, .base = 0); + nir_def *out = nir_load_preamble(&b, 1, 64, .base = 4); + + nir_if *nif = nir_push_if(&b, nir_ige_imm(&b, gid, 0)); + if (dont_flatten) + nif->control = nir_selection_control_dont_flatten; + nir_def *limit = nir_load_global_constant( + &b, 1, 32, nir_iadd_imm(&b, root, 8), .align_mul = 4); + nir_def *oob = nir_ige(&b, gid, limit); + nir_push_else(&b, nif); + nir_def *t = nir_imm_true(&b); + nir_pop_if(&b, nif); + + nir_def *res = nir_b2i32(&b, nir_if_phi(&b, oob, t)); + nir_store_global(&b, res, + nir_iadd(&b, out, nir_imul_imm(&b, nir_u2u64(&b, gid), 4)), + .align_mul = 4); + agx_preprocess_nir(b.shader); + + struct agx_shader_key key = {}; + key.dev.encoding = AGX_ISA_ENCODING_AGX3B; + key.dev.chip = chip; + key.reserved_preamble = 8; + key.no_preamble = true; + key.g17p_uniform_dma = true; + key.g17p_dma_root = 0; + struct agx_shader_part part = {}; + EXPECT_TRUE(agx_compile_shader_nir(b.shader, &key, &part)); + EXPECT_GT(part.info.agx3_uniform_dma_count, 0u); + std::vector bin; + if (part.binary) + bin.assign((const uint8_t *)part.binary, + (const uint8_t *)part.binary + part.info.binary_size); + free(part.binary); + ralloc_free(b.shader); + return bin; + }; + + for (enum agx_chip chip : {AGX_CHIP_G15G, AGX_CHIP_G17P}) { + const std::vector folded = compile_once(chip, false); + const std::vector kept = compile_once(chip, true); + EXPECT_FALSE(folded.empty()); + EXPECT_FALSE(kept.empty()); + EXPECT_NE(folded, kept); + EXPECT_LT(folded.size(), kept.size()); + } +} + +TEST(AGX3VisionOpts, UniformDmaNoPreamblePreservesScalarizedVecStore) +{ + /* Post-uniform-DMA peephole select and constant folding can introduce vector + * bcsel or re-fold vec4 load_const values after agx_optimize_nir's final + * scalarization pass. Ensure the !form_preamble uniform-DMA path re-runs + * scalarization so vector SSBO/global stores never hit missing allocated_vec + * entries in agx_recollect_vector. */ + nir_builder b = make_compute_shader("uniform_dma_vec4_store"); + nir_def *gid = nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0); + nir_def *root = nir_load_preamble(&b, 1, 64, .base = 0); + nir_def *out = nir_load_preamble(&b, 1, 64, .base = 4); + + nir_if *nif = nir_push_if(&b, nir_ige_imm(&b, gid, 0)); + nir_def *limit = nir_load_global_constant( + &b, 1, 32, nir_iadd_imm(&b, root, 8), .align_mul = 4); + nir_def *v_then = nir_vec4(&b, limit, nir_imm_int(&b, 2), + nir_imm_int(&b, 3), nir_imm_int(&b, 4)); + nir_push_else(&b, nif); + nir_def *v_else = nir_imm_ivec4(&b, 10, 20, 30, 40); + nir_pop_if(&b, nif); + + nir_def *sel = nir_if_phi(&b, v_then, v_else); + nir_def *cvec = nir_imm_ivec4(&b, 1, 2, 3, 4); + nir_def *addr0 = nir_iadd(&b, out, nir_imul_imm(&b, nir_u2u64(&b, gid), 32)); + nir_def *addr1 = nir_iadd_imm(&b, addr0, 16); + nir_store_global(&b, sel, addr0, .align_mul = 16); + nir_store_global(&b, cvec, addr1, .align_mul = 16); + agx_preprocess_nir(b.shader); + + struct agx_shader_key key = {}; + key.dev.encoding = AGX_ISA_ENCODING_AGX3B; + key.dev.chip = AGX_CHIP_G17P; + key.reserved_preamble = 8; + key.no_preamble = true; + key.g17p_uniform_dma = true; + key.g17p_dma_root = 0; + struct agx_shader_part part = {}; + EXPECT_TRUE(agx_compile_shader_nir(b.shader, &key, &part)); + EXPECT_GT(part.info.agx3_uniform_dma_count, 0u); + EXPECT_GT(part.info.binary_size, 0u); + free(part.binary); + ralloc_free(b.shader); +} + +TEST(AGX3VisionOpts, BinaryTailChunksSkippedLocallyWithoutDontFlatten) +{ + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "binary_tail_local_skip"); + b.shader->info.workgroup_size[0] = 8; + b.shader->info.workgroup_size[1] = 1; + b.shader->info.workgroup_size[2] = 1; + + nir_def *gid = nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0); + nir_def *n = push_u32(&b, 0); + nir_def *src_addr = nir_pack_64_2x32_split(&b, push_u32(&b, 4), push_u32(&b, 8)); + nir_def *dst_addr = nir_pack_64_2x32_split(&b, push_u32(&b, 12), push_u32(&b, 16)); + + nir_variable *iv = nir_local_variable_create(b.impl, glsl_int_type(), "i"); + nir_variable *acc = nir_local_variable_create(b.impl, glsl_float_type(), "acc"); + nir_store_var(&b, iv, nir_imm_int(&b, 0), 1); + nir_store_var(&b, acc, nir_imm_float(&b, 0.0f), 1); + + nir_loop *loop = nir_push_loop(&b); + { + nir_def *i = nir_load_var(&b, iv); + nir_if *brk = nir_push_if(&b, nir_ige(&b, i, n)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, brk); + + nir_def *off = nir_u2u64(&b, nir_imul_imm(&b, nir_iadd(&b, gid, i), 4)); + nir_def *v = nir_load_global(&b, 1, 32, nir_iadd(&b, src_addr, off), .align_mul = 4); + nir_store_var(&b, acc, nir_fadd(&b, nir_load_var(&b, acc), v), 1); + nir_store_var(&b, iv, nir_iadd_imm(&b, i, 1), 1); + } + nir_pop_loop(&b, loop); + + nir_def *out_off = nir_u2u64(&b, nir_imul_imm(&b, gid, 4)); + nir_store_global(&b, nir_load_var(&b, acc), nir_iadd(&b, dst_addr, out_off), .align_mul = 4); + + nir_lower_vars_to_ssa(b.shader); + nir_opt_constant_folding(b.shader); + nir_opt_copy_prop(b.shader); + nir_opt_dce(b.shader); + + ASSERT_TRUE(agx_nir_unroll_runtime_loops(b.shader, 8, 320, NULL)); + nir_validate_shader(b.shader, "after unroll"); + + unsigned tail_ifs = 0; + unsigned dont_flatten_ifs = 0; + foreach_list_typed(nir_cf_node, node, node, &b.impl->body) { + if (node->type == nir_cf_node_if) { + nir_if *nif = nir_cf_node_as_if(node); + tail_ifs++; + if (nif->control == nir_selection_control_dont_flatten) + dont_flatten_ifs++; + } + } + EXPECT_GE(tail_ifs, 3u); + EXPECT_EQ(dont_flatten_ifs, 0u); + EXPECT_FALSE(agx_nir_opt_flatten_loads(b.shader, 48, 4)); + + ralloc_free(b.shader); +} diff --git a/src/asahi/compiler/test/test-flatten-loads.cpp b/src/asahi/compiler/test/test-flatten-loads.cpp index f6c46809c27e..db332fe58af3 100644 --- a/src/asahi/compiler/test/test-flatten-loads.cpp +++ b/src/asahi/compiler/test/test-flatten-loads.cpp @@ -641,11 +641,13 @@ INSTANTIATE_TEST_SUITE_P( (std::get<2>(info.param) == ARM_THEN ? "Then" : "Else"); }); -/* The pass is M5's: G18G compiles as AGX3C with emit_agx3d and keeps the if. - * A guarded load compiles to a different program with and without - * dont_flatten on M5, to the same one on G18G. */ +/* The pass runs on AGX3B and AGX3C (not G18G, which compiles as AGX3C with + * emit_agx3d and keeps the if). A guarded load compiles to a different program + * with and without dont_flatten on AGX3B and AGX3C, and to the same one on + * G18G. */ static std::vector -compile_guarded_load(bool emit_agx3d, bool dont_flatten) +compile_guarded_load(enum agx_isa_encoding encoding, enum agx_chip chip, + bool emit_agx3d, bool dont_flatten) { nir_builder b = nir_builder_init_simple_shader( MESA_SHADER_COMPUTE, &agx_nir_options, "guarded load"); @@ -666,8 +668,8 @@ compile_guarded_load(bool emit_agx3d, bool dont_flatten) agx_preprocess_nir(b.shader); agx_shader_key key = {}; - key.dev.encoding = AGX_ISA_ENCODING_AGX3C; - key.dev.chip = emit_agx3d ? AGX_CHIP_G17G : AGX_CHIP_G17C; + key.dev.encoding = encoding; + key.dev.chip = chip; key.dev.emit_agx3d = emit_agx3d; key.reserved_preamble = 10; key.no_preamble = true; @@ -683,13 +685,232 @@ compile_guarded_load(bool emit_agx3d, bool dont_flatten) return binary; } -TEST_F(FlattenLoadsKeeps, G18GKeepsTheIf) +TEST_F(FlattenLoadsKeeps, AGX3BAndM5FlattenWhileG18GKeepsTheIf) { - const std::vector m5 = compile_guarded_load(false, false); + const std::vector g15g = compile_guarded_load( + AGX_ISA_ENCODING_AGX3B, AGX_CHIP_G15G, false, false); + EXPECT_FALSE(g15g.empty()); + EXPECT_NE(g15g, compile_guarded_load(AGX_ISA_ENCODING_AGX3B, AGX_CHIP_G15G, + false, true)); + + const std::vector agx3b = compile_guarded_load( + AGX_ISA_ENCODING_AGX3B, AGX_CHIP_G17P, false, false); + EXPECT_FALSE(agx3b.empty()); + EXPECT_NE(agx3b, compile_guarded_load(AGX_ISA_ENCODING_AGX3B, AGX_CHIP_G17P, + false, true)); + + const std::vector m5 = compile_guarded_load( + AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C, false, false); EXPECT_FALSE(m5.empty()); - EXPECT_NE(m5, compile_guarded_load(false, true)); + EXPECT_NE(m5, compile_guarded_load(AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17C, + false, true)); - const std::vector g18g = compile_guarded_load(true, false); + const std::vector g18g = compile_guarded_load( + AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17G, true, false); EXPECT_FALSE(g18g.empty()); - EXPECT_EQ(g18g, compile_guarded_load(true, true)); + EXPECT_EQ(g18g, compile_guarded_load(AGX_ISA_ENCODING_AGX3C, AGX_CHIP_G17G, + true, true)); +} + +TEST_F(FlattenLoadsKeeps, SinkCommonStoreSharedAndFlattenBurst) +{ + /* Four sibling divergent if/else diamonds each loading one dword from + * global memory or zero and storing to the exact same shared-memory + * expression (as in tiled GEMM edge loaders) must sink all four + * store_shared instructions and flatten all four ifs. */ + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "sink_and_burst"); + b.shader->info.shared_size = 256; + b.shader->info.shared_element_index_agx = true; + + nir_def *gid = nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0); + nir_def *lid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *base = nir_load_preamble(&b, 1, 64, .base = SLOT_BASE); + nir_def *limit = nir_load_preamble(&b, 1, 32, .base = SLOT_I); + + for (unsigned k = 0; k < 4; ++k) { + nir_def *cond = nir_ilt(&b, nir_iadd_imm(&b, gid, k), limit); + nir_if *nif = nir_push_if(&b, cond); + { + nir_def *saddr_t = nir_u2u16(&b, nir_iadd_imm(&b, lid, (k + 1) * 16)); + nir_def *gaddr = nir_iadd( + &b, base, nir_imul_imm(&b, nir_u2u64(&b, nir_iadd_imm(&b, gid, k)), 4)); + nir_def *v = nir_load_global(&b, 1, 32, gaddr, .align_mul = 4); + nir_store_shared(&b, v, saddr_t, .base = 0, .write_mask = 1, + .align_mul = 4); + } + nir_push_else(&b, nif); + { + /* Commuted add operand order to verify structural matching. */ + nir_def *saddr_e = nir_u2u16(&b, nir_iadd(&b, nir_imm_int(&b, (k + 1) * 16), lid)); + nir_store_shared(&b, nir_imm_int(&b, 0), saddr_e, .base = 0, + .write_mask = 1, .align_mul = 4); + } + nir_pop_if(&b, nif); + } + + ASSERT_TRUE(agx_nir_opt_flatten_loads(b.shader, 64, 4)); + nir_validate_shader(b.shader, "sink_and_burst"); + EXPECT_EQ(count_ifs(b.shader), 0u); + + unsigned stores = 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_store_shared) + stores++; + } + } + EXPECT_EQ(stores, 4u); + ralloc_free(b.shader); +} + +TEST_F(FlattenLoadsKeeps, StoreSharedMismatchedOrVolatileNotSunk) +{ + for (unsigned mode = 0; mode < 2; ++mode) { + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "no_sink_shared"); + b.shader->info.shared_size = 256; + b.shader->info.shared_element_index_agx = true; + + nir_def *gid = nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0); + nir_def *lid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *base = nir_load_preamble(&b, 1, 64, .base = SLOT_BASE); + + nir_if *nif = nir_push_if(&b, nir_ilt_imm(&b, gid, 16)); + nir_def *v = nir_load_global(&b, 1, 32, base, .align_mul = 4); + const gl_access_qualifier access = mode == 1 ? ACCESS_VOLATILE : + (gl_access_qualifier)0; + nir_store_shared(&b, v, nir_u2u16(&b, lid), .base = 0, .access = access, + .write_mask = 1, .align_mul = 4); + nir_push_else(&b, nif); + nir_def *e_addr = + mode == 0 ? nir_u2u16(&b, nir_iadd_imm(&b, lid, 1)) : nir_u2u16(&b, lid); + nir_store_shared(&b, nir_imm_int(&b, 0), e_addr, .base = 0, + .access = access, .write_mask = 1, .align_mul = 4); + nir_pop_if(&b, nif); + + EXPECT_FALSE(agx_nir_opt_flatten_loads(b.shader, 64, 4)); + EXPECT_EQ(count_ifs(b.shader), 1u); + ralloc_free(b.shader); + } +} + +TEST_F(FlattenLoadsKeeps, DivergentBurstThresholdAndConstGlobalExclusion) +{ + auto run_burst = [](unsigned count, bool const_global) { + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "burst_threshold"); + nir_def *gid = nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0); + nir_def *base = nir_load_preamble(&b, 1, 64, .base = SLOT_BASE); + nir_def *out = nir_load_preamble(&b, 1, 64, .base = SLOT_J); + nir_def *acc = nir_imm_int(&b, 0); + + for (unsigned k = 0; k < count; ++k) { + nir_if *nif = nir_push_if(&b, nir_ilt_imm(&b, gid, 16 + k)); + nir_def *addr = nir_iadd_imm(&b, base, k * 4); + nir_def *v = + const_global + ? nir_load_global_constant(&b, 1, 32, addr, .align_mul = 4) + : nir_load_global(&b, 1, 32, addr, .align_mul = 4); + nir_push_else(&b, nif); + nir_def *z = nir_imm_int(&b, 0); + nir_pop_if(&b, nif); + acc = nir_iadd(&b, acc, nir_if_phi(&b, v, z)); + } + nir_store_global(&b, acc, out, .align_mul = 4); + bool changed = agx_nir_opt_flatten_loads(b.shader, 64, 4); + unsigned rem = count_ifs(b.shader); + nir_validate_shader(b.shader, "burst_threshold"); + ralloc_free(b.shader); + return std::pair{changed, rem}; + }; + + /* 3 sibling divergent ifs stay unflattened; 4 flatten completely. */ + auto r3 = run_burst(3, false); + EXPECT_FALSE(r3.first); + EXPECT_EQ(r3.second, 3u); + + auto r4 = run_burst(4, false); + EXPECT_TRUE(r4.first); + EXPECT_EQ(r4.second, 0u); + + /* 4 sibling load_global_constant ifs stay unflattened for uniform DMA. */ + auto rc = run_burst(4, true); + EXPECT_FALSE(rc.first); + EXPECT_EQ(rc.second, 4u); +} + +TEST_F(FlattenLoadsKeeps, SkipsBinaryTailCascade) +{ + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "binary_tail_skip"); + nir_def *iv = nir_load_preamble(&b, 1, 32, .base = 0); + nir_def *n = nir_load_preamble(&b, 1, 32, .base = 2); + nir_def *buf = nir_load_preamble(&b, 1, 64, .base = 4); + nir_def *out = nir_load_preamble(&b, 1, 64, .base = 8); + + nir_def *acc = nir_imm_int(&b, 0); + for (unsigned step : {4u, 2u, 1u}) { + nir_def *lim = step > 1 ? nir_iadd_imm(&b, n, -(int)(step - 1)) : n; + nir_if *nif = nir_push_if(&b, nir_ilt(&b, iv, lim)); + nir_def *v = nir_load_global( + &b, 1, 32, nir_iadd(&b, buf, nir_u2u64(&b, nir_ishl_imm(&b, iv, 2))), + .align_mul = 4); + nir_def *next_acc = nir_iadd(&b, acc, v); + nir_def *next_iv = nir_iadd_imm(&b, iv, step); + nir_pop_if(&b, nif); + acc = nir_if_phi(&b, next_acc, acc); + if (step > 1) + iv = nir_if_phi(&b, next_iv, iv); + } + nir_store_global(&b, acc, out, .align_mul = 4); + + EXPECT_FALSE(agx_nir_opt_flatten_loads(b.shader, 64, 4)); + unsigned ifs = 0; + nir_foreach_function_impl(impl, b.shader) { + foreach_list_typed(nir_cf_node, node, node, &impl->body) { + if (node->type == nir_cf_node_if) { + EXPECT_EQ(nir_cf_node_as_if(node)->control, + nir_selection_control_none); + ifs++; + } + } + } + EXPECT_EQ(ifs, 3u); + nir_validate_shader(b.shader, "binary_tail_skip"); + ralloc_free(b.shader); +} + +TEST_F(FlattenLoadsKeeps, BurstRequiresContiguousRun) +{ + /* 2 + 2 matching divergent ifs separated by a barrier must not flatten. */ + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "burst_noncontiguous"); + nir_def *gid = nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0); + nir_def *buf = nir_load_preamble(&b, 1, 64, .base = 0); + nir_def *out = nir_load_preamble(&b, 1, 64, .base = 4); + + nir_def *acc = nir_imm_int(&b, 0); + for (unsigned i = 0; i < 4; ++i) { + if (i == 2) { + nir_barrier(&b, .execution_scope = SCOPE_WORKGROUP, + .memory_scope = SCOPE_WORKGROUP, + .memory_semantics = NIR_MEMORY_ACQ_REL, + .memory_modes = nir_var_mem_shared); + } + nir_if *nif = nir_push_if(&b, nir_ult_imm(&b, gid, 64 + i)); + nir_def *addr = nir_iadd(&b, buf, nir_u2u64(&b, nir_ishl_imm(&b, gid, 2))); + nir_def *v = nir_load_global(&b, 1, 32, addr, .align_mul = 4); + nir_push_else(&b, nif); + nir_def *z = nir_imm_int(&b, 0); + nir_pop_if(&b, nif); + acc = nir_iadd(&b, acc, nir_if_phi(&b, v, z)); + } + nir_store_global(&b, acc, out, .align_mul = 4); + + EXPECT_FALSE(agx_nir_opt_flatten_loads(b.shader, 64, 4)); + nir_validate_shader(b.shader, "burst_noncontiguous"); + ralloc_free(b.shader); }