diff --git a/src/asahi/vulkan/hk_cmd_dispatch.c b/src/asahi/vulkan/hk_cmd_dispatch.c index 3112600e9767..3c1ee1e49eb1 100644 --- a/src/asahi/vulkan/hk_cmd_dispatch.c +++ b/src/asahi/vulkan/hk_cmd_dispatch.c @@ -3180,7 +3180,14 @@ hk_record_compute_pair(struct hk_cmd_buffer *cmd, struct hk_cs *cs, record.root_va = desc->uploaded_root.gpu; memcpy(record.root_sets, desc->root.sets, sizeof(record.root_sets)); memcpy(record.push, desc->root.push, sizeof(record.push)); - record.is_depthwise_vec4 = (selected == api->depthwise_vec4); + if (selected == api->depthwise_vec4) + record.alt_kind = HK_COMPUTE_PAIR_ALT_DEPTHWISE_VEC4; + else if (selected == api->gemm_cmat32) + record.alt_kind = HK_COMPUTE_PAIR_ALT_GEMM_CMAT32; + else if (selected == api->gemm_cmat64) + record.alt_kind = HK_COMPUTE_PAIR_ALT_GEMM_CMAT64; + else + record.alt_kind = HK_COMPUTE_PAIR_ALT_NONE; cs->compute_pair = malloc(sizeof(record)); if (!cs->compute_pair) @@ -3806,7 +3813,7 @@ hk_select_depthwise_vec4(struct hk_cmd_buffer *cmd, struct hk_api_shader *api, return normal; if (!hk_g17p_compute_shader_supported(dev->dev.chip, alt, alt->only_linked, 1u << 16) || alt->b.info.workgroup_size[0] == 0 || alt->b.info.workgroup_size[1] == 0 || - alt->b.info.workgroup_size[2] != 1) + alt->b.info.workgroup_size[2] == 0) return normal; const struct hk_nir_depthwise_output *dw = &api->compute_pair->depthwise; @@ -3891,11 +3898,153 @@ hk_select_depthwise_vec4(struct hk_cmd_buffer *cmd, struct hk_api_shader *api, return normal; const uint64_t out_pairs = DIV_ROUND_UP((uint64_t)(uint32_t)ow, 2); - const uint64_t out_x4 = out_pairs * ((uint32_t)ch / 4); - if (out_x4 > UINT32_MAX) + if (out_pairs > UINT32_MAX) + return normal; + const uint32_t gx = DIV_ROUND_UP((uint32_t)ch / 4, alt->b.info.workgroup_size[0]); + const uint32_t gy = DIV_ROUND_UP((uint32_t)out_pairs, alt->b.info.workgroup_size[1]); + const uint32_t gz = DIV_ROUND_UP((uint32_t)oh, alt->b.info.workgroup_size[2]); + if (gx > 65535 || gy > 65535 || gz > 65535) + return normal; + grid->count[0] = gx; + grid->count[1] = gy; + grid->count[2] = gz; + return alt; +} + +static struct hk_shader * +hk_select_gemm_cmat(struct hk_cmd_buffer *cmd, struct hk_api_shader *api, + struct hk_shader *normal, struct agx_grid *grid) +{ + const struct hk_descriptor_state *desc = &cmd->state.cs.descriptors; + struct hk_device *dev = hk_cmd_buffer_device(cmd); + if ((!api->gemm_cmat32 && !api->gemm_cmat64) || !api->compute_pair || + api->compute_pair->role != HK_COMPUTE_PAIR_GEMM) + return normal; + if (!agx_chip_native_or_m5(dev->dev.chip) || + !agx_chip_cooperative_matrix_supported(dev->dev.chip) || + cmd->in_meta || cmd->vk.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) + return normal; + if (grid->mode != AGX_CDM_MODE_DIRECT || desc->root.cs.base_group[0] || + desc->root.cs.base_group[1] || desc->root.cs.base_group[2] || + grid->count[2] != 1) + return normal; + + const struct hk_nir_gemm_output *gemm = &api->compute_pair->gemm; + if (!gemm->cmat_valid || gemm->push_bytes > HK_COMPUTE_OPT_PUSH_BYTES || + gemm->local_size[0] != normal->b.info.workgroup_size[0] || + gemm->local_size[1] != normal->b.info.workgroup_size[1] || + gemm->local_size[2] != normal->b.info.workgroup_size[2]) + return normal; + + int32_t m_i = 0, n_i = 0, k_i = 0, bias_mode = 2; + if (!hk_read_push_i32(desc, gemm->n_offset_B, &n_i) || + !hk_read_push_i32(desc, gemm->k_offset_B, &k_i)) + return normal; + if (n_i <= 0 || k_i <= 0) + return normal; + + if (gemm->has_bias_mode) { + if (!hk_read_push_i32(desc, gemm->bias_mode_offset_B, &bias_mode)) + return normal; + if (bias_mode < 0 || bias_mode > 2 || + !(gemm->bias_mode_mask & (1u << bias_mode))) + return normal; + } else if (gemm->has_bias_buffer) { + if (gemm->bias_mode_mask == (1u << 0)) + bias_mode = 0; + else if (gemm->bias_mode_mask == (1u << 1)) + bias_mode = 1; + else + return normal; + } + + uint64_t m_u = 0; + if (gemm->is_guarded) { + if (!hk_read_push_i32(desc, gemm->m_offset_B, &m_i) || m_i <= 0) + return normal; + m_u = (uint32_t)m_i; + } else { + m_u = (uint64_t)grid->count[1] * 32; + } + if (!hk_gemm_cmat_dispatch_dims_ok(gemm->is_guarded, m_u, (uint32_t)n_i, + (uint32_t)k_i, grid->count)) + return normal; + + struct hk_shader *alt = NULL; + uint32_t tile_n = 0; + if (!gemm->is_guarded) { + if (((uint32_t)n_i % 64) == 0 && api->gemm_cmat64) { + alt = api->gemm_cmat64; + tile_n = 64; + } else if (api->gemm_cmat32) { + alt = api->gemm_cmat32; + tile_n = 32; + } + } else { + if ((uint32_t)n_i > 32 && api->gemm_cmat64) { + alt = api->gemm_cmat64; + tile_n = 64; + } else if (api->gemm_cmat32) { + alt = api->gemm_cmat32; + tile_n = 32; + } + } + if (!alt || + !hk_g17p_compute_shader_supported(dev->dev.chip, alt, alt->only_linked, 1u << 16)) + return normal; + + const uint64_t n_u = (uint32_t)n_i; + const uint64_t k_u = (uint32_t)k_i; + uint64_t a_elems = 0, b_elems = 0, c_elems = 0; + if (__builtin_mul_overflow(m_u, k_u, &a_elems) || + __builtin_mul_overflow(k_u, n_u, &b_elems) || + __builtin_mul_overflow(m_u, n_u, &c_elems)) + return normal; + const uint64_t a_bytes = a_elems * sizeof(uint32_t); + const uint64_t b_bytes = b_elems * sizeof(uint32_t); + const uint64_t c_bytes = c_elems * sizeof(uint32_t); + const uint64_t bias_bytes = + (bias_mode == 0) ? m_u * sizeof(uint32_t) : + (bias_mode == 1) ? n_u * sizeof(uint32_t) : 0; + if (a_bytes > (uint64_t)INT32_MAX + 1 || + b_bytes > (uint64_t)INT32_MAX + 1 || + c_bytes > (uint64_t)INT32_MAX + 1 || + bias_bytes > (uint64_t)INT32_MAX + 1) return normal; - grid->count[0] = DIV_ROUND_UP((uint32_t)out_x4, alt->b.info.workgroup_size[0]); - grid->count[1] = DIV_ROUND_UP((uint32_t)oh, alt->b.info.workgroup_size[1]); + + const uint32_t a_align = gemm->is_guarded ? 4 : 16; + if ((gemm->reads[0].offset_B % a_align) || (gemm->reads[1].offset_B % 4) || + (bias_bytes && (gemm->reads[2].offset_B % 4)) || (gemm->output.offset_B % 4)) + return normal; + + struct hk_storage_backing a_b, b_b, bs_b, c_b; + if (!hk_check_storage_backing(desc, gemm->reads[0].set, gemm->reads[0].binding, + gemm->reads[0].offset_B, a_bytes, a_align, &a_b) || + !hk_check_storage_backing(desc, gemm->reads[1].set, gemm->reads[1].binding, + gemm->reads[1].offset_B, b_bytes, 4, &b_b) || + !hk_check_storage_backing(desc, gemm->output.set, gemm->output.binding, + gemm->output.offset_B, c_bytes, 4, &c_b)) + return normal; + if (bias_bytes && + !hk_check_storage_backing(desc, gemm->reads[2].set, gemm->reads[2].binding, + gemm->reads[2].offset_B, bias_bytes, 4, &bs_b)) + return normal; + + if (!hk_intervals_disjoint(&a_b, gemm->reads[0].offset_B, a_bytes, + &c_b, gemm->output.offset_B, c_bytes) || + !hk_intervals_disjoint(&b_b, gemm->reads[1].offset_B, b_bytes, + &c_b, gemm->output.offset_B, c_bytes) || + (bias_bytes && + !hk_intervals_disjoint(&bs_b, gemm->reads[2].offset_B, bias_bytes, + &c_b, gemm->output.offset_B, c_bytes))) + return normal; + + const uint64_t gx = DIV_ROUND_UP(n_u, tile_n); + const uint64_t gy = DIV_ROUND_UP(m_u, 64); + if (gx > 65535 || gy > 65535) + return normal; + grid->count[0] = (uint32_t)gx; + grid->count[1] = (uint32_t)gy; grid->count[2] = 1; return alt; } @@ -3969,6 +4118,13 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, local_size = agx_workgroup(selected->b.info.workgroup_size[0], selected->b.info.workgroup_size[1], selected->b.info.workgroup_size[2]); + } else if (api && (api->gemm_cmat32 || api->gemm_cmat64) && api->compute_pair && + api->compute_pair->role == HK_COMPUTE_PAIR_GEMM && + !in_threads && !invocation_stat) { + selected = hk_select_gemm_cmat(cmd, api, s, &grid); + local_size = agx_workgroup(selected->b.info.workgroup_size[0], + selected->b.info.workgroup_size[1], + selected->b.info.workgroup_size[2]); } if (!agx_is_indirect(grid) && !in_threads) { @@ -4036,7 +4192,8 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, } hk_dispatch_with_local_size(cmd, cs, selected, grid, local_size); if (!in_threads && !invocation_stat && api && api->compute_pair && - (selected == s || selected == api->depthwise_vec4)) + (selected == s || selected == api->depthwise_vec4 || + selected == api->gemm_cmat32 || selected == api->gemm_cmat64)) hk_record_compute_pair(cmd, cs, api, selected, orig_groups, grid); cs->uses_global_atomics |= selected->b.info.uses_global_atomics; cs->pack_loops |= selected->b.info.has_loops; diff --git a/src/asahi/vulkan/hk_compute_pair.h b/src/asahi/vulkan/hk_compute_pair.h index 90ffeb7026f1..5f4ab22f59ce 100644 --- a/src/asahi/vulkan/hk_compute_pair.h +++ b/src/asahi/vulkan/hk_compute_pair.h @@ -17,11 +17,18 @@ struct hk_shader; struct nir_shader; struct vk_descriptor_set_layout; -#define HK_COMPUTE_PAIR_MAX_VARIANTS 8u +#define HK_COMPUTE_PAIR_MAX_VARIANTS 16u + +enum hk_compute_pair_alt_kind { + HK_COMPUTE_PAIR_ALT_NONE = 0, + HK_COMPUTE_PAIR_ALT_DEPTHWISE_VEC4 = 1, + HK_COMPUTE_PAIR_ALT_GEMM_CMAT32 = 2, + HK_COMPUTE_PAIR_ALT_GEMM_CMAT64 = 3, +}; struct hk_compute_pair_variant { struct hk_nir_clamp_epilogue epilogue; - bool use_depthwise_vec4; + enum hk_compute_pair_alt_kind alt_kind; struct hk_shader *shader; }; @@ -67,7 +74,7 @@ struct hk_shader * hk_compute_pair_get_or_compile_fused(struct hk_device *dev, struct hk_compute_pair_producer *prod, const struct hk_nir_clamp_epilogue *epilogue, - bool use_depthwise_vec4); + enum hk_compute_pair_alt_kind alt_kind); void hk_compute_pair_info_serialize(struct blob *blob, const struct hk_compute_pair_info *info); @@ -88,7 +95,7 @@ struct hk_compute_pair_dispatch { uint64_t root_va; uint64_t root_sets[HK_MAX_SETS]; uint8_t push[HK_MAX_PUSH_SIZE]; - bool is_depthwise_vec4; + enum hk_compute_pair_alt_kind alt_kind; struct hk_compute_pair_producer *producer; }; diff --git a/src/asahi/vulkan/hk_nir_match_pointwise_clamp.c b/src/asahi/vulkan/hk_nir_match_pointwise_clamp.c index 79890604fc5e..b70cac8bb268 100644 --- a/src/asahi/vulkan/hk_nir_match_pointwise_clamp.c +++ b/src/asahi/vulkan/hk_nir_match_pointwise_clamp.c @@ -1988,48 +1988,57 @@ match_gemm_c_index(nir_scalar idx, const uint16_t ls[3], return false; } +/* Extract the two predicates of an `a && b` branch condition (either `iand` + * or a short-circuit phi after `if (a) { b }`). */ +static bool +match_guard_cond_pair(nir_if *branch, const uint16_t ls[3], + nir_scalar *p0_out, nir_scalar *p1_out) +{ + nir_scalar cond = source(branch->condition); + if (scalar_op(cond, nir_op_iand)) { + *p0_out = nir_scalar_chase_alu_src(cond, 0); + *p1_out = nir_scalar_chase_alu_src(cond, 1); + return true; + } + if (!nir_def_is_phi(cond.def)) + return false; + const nir_phi_instr *phi = nir_def_as_phi(cond.def); + if (nir_cf_node_next(&phi->instr.block->cf_node) != &branch->cf_node) + return false; + nir_cf_node *prev = nir_cf_node_prev(&phi->instr.block->cf_node); + if (!prev || prev->type != nir_cf_node_if) + return false; + nir_if *test = nir_cf_node_as_if(prev); + nir_scalar first = source(test->condition); + nir_scalar p1 = {0}; + bool saw_false = false, saw_second = false; + nir_foreach_phi_src(src, phi) { + nir_scalar val = source(src->src); + if (src->pred == nir_if_last_else_block(test) && + (same_with_local(val, first, ls) || constant(val, 0))) { + saw_false = true; + } else if (src->pred == nir_if_last_then_block(test)) { + p1 = val; + saw_second = true; + } else { + return false; + } + } + if (!saw_false || !saw_second) + return false; + *p0_out = first; + *p1_out = p1; + return true; +} + /* Match row < m && col < n guard (iand or short-circuit phi). */ static bool match_gemm_store_guard(nir_if *branch, const uint16_t ls[3], uint32_t expected_r, uint32_t expected_j, uint32_t expected_n_off, uint32_t *m_offset_B) { - nir_scalar cond = source(branch->condition); nir_scalar p0 = {0}, p1 = {0}; - bool have_pair = false; - - if (scalar_op(cond, nir_op_iand)) { - p0 = nir_scalar_chase_alu_src(cond, 0); - p1 = nir_scalar_chase_alu_src(cond, 1); - have_pair = true; - } else if (nir_def_is_phi(cond.def)) { - const nir_phi_instr *phi = nir_def_as_phi(cond.def); - if (nir_cf_node_next(&phi->instr.block->cf_node) != &branch->cf_node) - return false; - nir_cf_node *prev = nir_cf_node_prev(&phi->instr.block->cf_node); - if (!prev || prev->type != nir_cf_node_if) - return false; - nir_if *test = nir_cf_node_as_if(prev); - nir_scalar first = source(test->condition); - bool saw_false = false, saw_second = false; - nir_foreach_phi_src(src, phi) { - nir_scalar val = source(src->src); - if (src->pred == nir_if_last_else_block(test) && - (same_with_local(val, first, ls) || constant(val, 0))) { - saw_false = true; - } else if (src->pred == nir_if_last_then_block(test)) { - p1 = val; - saw_second = true; - } else { - return false; - } - } - if (saw_false && saw_second) { - p0 = first; - have_pair = true; - } - } - if (!have_pair) + if (!match_guard_cond_pair(branch, ls, &p0, &p1)) return false; if ((!scalar_op(p0, nir_op_ilt) && !scalar_op(p0, nir_op_ult)) || (!scalar_op(p1, nir_op_ilt) && !scalar_op(p1, nir_op_ult))) @@ -2059,6 +2068,30 @@ match_gemm_store_guard(nir_if *branch, const uint16_t ls[3], return true; } +static bool +match_bias_mode_if(const nir_if *branch, uint32_t *bias_mode_off, + uint32_t *mode_out) +{ + nir_scalar cond = source(branch->condition); + if (!scalar_op(cond, nir_op_ieq)) + return false; + nir_scalar a = nir_scalar_chase_alu_src(cond, 0); + nir_scalar b = nir_scalar_chase_alu_src(cond, 1); + uint32_t off, mode; + if (push_count(a, &off) && nir_scalar_is_const(b)) { + mode = nir_scalar_as_uint(b); + } else if (push_count(b, &off) && nir_scalar_is_const(a)) { + mode = nir_scalar_as_uint(a); + } else { + return false; + } + if (mode > 2) + return false; + *bias_mode_off = off; + *mode_out = mode; + return true; +} + /* Find the dominating `if (push[bias_mode_off] == mode)` whose then-arm holds * `node`. Returns false if `node` is not inside such a bias_mode arm. */ static bool @@ -2070,50 +2103,1569 @@ find_bias_mode_arm(nir_cf_node *node, uint32_t *bias_mode_off, uint32_t *mode_ou nir_if *branch = nir_cf_node_as_if(cur->parent); if (!in_then(cur, branch)) continue; - nir_scalar cond = source(branch->condition); - if (!scalar_op(cond, nir_op_ieq)) - continue; - nir_scalar a = nir_scalar_chase_alu_src(cond, 0); - nir_scalar b = nir_scalar_chase_alu_src(cond, 1); - uint32_t off, mode; - if (push_count(a, &off) && nir_scalar_is_const(b)) { - mode = nir_scalar_as_uint(b); - } else if (push_count(b, &off) && nir_scalar_is_const(a)) { - mode = nir_scalar_as_uint(a); + if (match_bias_mode_if(branch, bias_mode_off, mode_out)) + return true; + } + return false; +} + +/* Extract push-constant stride from a linear SSBO index `(... * stride) + ...`. */ +static bool +find_linear_stride_push_rec(nir_scalar idx, uint32_t *stride_off, unsigned depth) +{ + idx = nir_scalar_chase_movs(idx); + if (scalar_op(idx, nir_op_imul)) { + if (push_count(nir_scalar_chase_alu_src(idx, 1), stride_off)) + return true; + if (push_count(nir_scalar_chase_alu_src(idx, 0), stride_off)) + return true; + return false; + } + if (!depth || !scalar_op(idx, nir_op_iadd)) + return false; + return find_linear_stride_push_rec(nir_scalar_chase_alu_src(idx, 0), stride_off, depth - 1) || + find_linear_stride_push_rec(nir_scalar_chase_alu_src(idx, 1), stride_off, depth - 1); +} + +static bool +find_linear_stride_push(nir_scalar idx, uint32_t *stride_off) +{ + return find_linear_stride_push_rec(idx, stride_off, 4); +} + +static bool +is_local_id_axis(nir_scalar s, const uint16_t ls[3], unsigned axis) +{ + unsigned a = 0; + return sysval_id_axis(s, SYSTEM_VALUE_LOCAL_INVOCATION_ID, ls, &a) && a == axis; +} + +static bool +is_const_u32(nir_scalar s, uint32_t expected) +{ + s = nir_scalar_chase_movs(s); + return nir_scalar_is_const(s) && s.def->bit_size == 32 && + nir_scalar_as_uint(s) == expected; +} + +static bool +is_lid_y_mul8(nir_scalar s, const uint16_t ls[3]) +{ + s = nir_scalar_chase_movs(s); + if (scalar_op(s, nir_op_imul)) { + nir_scalar a = nir_scalar_chase_alu_src(s, 0); + nir_scalar b = nir_scalar_chase_alu_src(s, 1); + return (is_local_id_axis(a, ls, 1) && is_const_u32(b, 8)) || + (is_local_id_axis(b, ls, 1) && is_const_u32(a, 8)); + } + if (scalar_op(s, nir_op_ishl)) { + return is_local_id_axis(nir_scalar_chase_alu_src(s, 0), ls, 1) && + is_const_u32(nir_scalar_chase_alu_src(s, 1), 3); + } + return false; +} + +static bool +match_lid_row8(nir_scalar s, const uint16_t ls[3], uint32_t *j_out) +{ + s = nir_scalar_chase_movs(s); + if (is_lid_y_mul8(s, ls)) { + *j_out = 0; + return true; + } + if (scalar_op(s, nir_op_iadd)) { + nir_scalar a = nir_scalar_chase_alu_src(s, 0); + nir_scalar b = nir_scalar_chase_alu_src(s, 1); + if (is_lid_y_mul8(a, ls) && nir_scalar_is_const(b) && + b.def->bit_size == 32 && nir_scalar_as_uint(b) < 8) { + *j_out = (uint32_t)nir_scalar_as_uint(b); + return true; + } + if (is_lid_y_mul8(b, ls) && nir_scalar_is_const(a) && + a.def->bit_size == 32 && nir_scalar_as_uint(a) < 8) { + *j_out = (uint32_t)nir_scalar_as_uint(a); + return true; + } + } + return false; +} + +static bool +match_mul32(nir_scalar s, nir_scalar *base_out) +{ + s = nir_scalar_chase_movs(s); + if (scalar_op(s, nir_op_imul)) { + nir_scalar a = nir_scalar_chase_alu_src(s, 0); + nir_scalar b = nir_scalar_chase_alu_src(s, 1); + if (is_const_u32(b, 32)) { + *base_out = a; + return true; + } + if (is_const_u32(a, 32)) { + *base_out = b; + return true; + } + } else if (scalar_op(s, nir_op_ishl)) { + if (is_const_u32(nir_scalar_chase_alu_src(s, 1), 5)) { + *base_out = nir_scalar_chase_alu_src(s, 0); + return true; + } + } + return false; +} + +static bool +is_phi_scalar(nir_scalar s, const nir_phi_instr *phi) +{ + s = nir_scalar_chase_movs(s); + return phi && s.def == &phi->def && s.comp == 0; +} + +static bool +is_tile_k_base(nir_scalar s, const nir_phi_instr *tile_phi, + const nir_phi_instr *k_idx_phi) +{ + s = nir_scalar_chase_movs(s); + if (k_idx_phi && is_phi_scalar(s, k_idx_phi)) + return true; + nir_scalar base; + if (tile_phi && match_mul32(s, &base) && is_phi_scalar(base, tile_phi)) + return true; + return false; +} + +static bool +flatten_iadd_terms(nir_scalar s, nir_scalar *terms, unsigned *count, + unsigned max_terms, unsigned depth) +{ + s = nir_scalar_chase_movs(s); + if (depth > 0 && scalar_op(s, nir_op_iadd)) { + return flatten_iadd_terms(nir_scalar_chase_alu_src(s, 0), terms, count, + max_terms, depth - 1) && + flatten_iadd_terms(nir_scalar_chase_alu_src(s, 1), terms, count, + max_terms, depth - 1); + } + if (*count >= max_terms) + return false; + terms[(*count)++] = s; + return true; +} + +static bool +match_k_plus_31(nir_scalar s, uint32_t k_off) +{ + s = nir_scalar_chase_movs(s); + uint32_t off; + if (scalar_op(s, nir_op_isub)) { + nir_scalar a = nir_scalar_chase_alu_src(s, 0); + nir_scalar b = nir_scalar_chase_alu_src(s, 1); + if (is_const_u32(b, 1) && scalar_op(a, nir_op_iadd)) { + nir_scalar a0 = nir_scalar_chase_alu_src(a, 0); + nir_scalar a1 = nir_scalar_chase_alu_src(a, 1); + if ((push_count(a0, &off) && off == k_off && is_const_u32(a1, 32)) || + (push_count(a1, &off) && off == k_off && is_const_u32(a0, 32))) + return true; + } + return false; + } + nir_scalar terms[4]; + unsigned n = 0; + if (!flatten_iadd_terms(s, terms, &n, 4, 3)) + return false; + bool got_k = false; + int64_t csum = 0; + for (unsigned i = 0; i < n; ++i) { + if (!got_k && push_count(terms[i], &off) && off == k_off) { + got_k = true; + } else if (nir_scalar_is_const(terms[i]) && terms[i].def->bit_size == 32) { + csum += (int32_t)nir_scalar_as_uint(terms[i]); } else { - continue; + return false; + } + } + return got_k && csum == 31; +} + +static bool +match_ceil_div_32(nir_scalar s, uint32_t k_off) +{ + s = nir_scalar_chase_movs(s); + if (scalar_op(s, nir_op_idiv) || scalar_op(s, nir_op_udiv)) { + return is_const_u32(nir_scalar_chase_alu_src(s, 1), 32) && + match_k_plus_31(nir_scalar_chase_alu_src(s, 0), k_off); + } + if (scalar_op(s, nir_op_ishr) || scalar_op(s, nir_op_ushr)) { + if (!is_const_u32(nir_scalar_chase_alu_src(s, 1), 5)) + return false; + nir_scalar x = nir_scalar_chase_alu_src(s, 0); + if (match_k_plus_31(x, k_off)) + return true; + /* Lowered signed idiv by 32: (x + ((x >> 31) & 31)) >> 5. */ + if (scalar_op(x, nir_op_iadd)) { + nir_scalar a = nir_scalar_chase_alu_src(x, 0); + nir_scalar b = nir_scalar_chase_alu_src(x, 1); + for (unsigned flip = 0; flip < 2; ++flip) { + nir_scalar xv = flip ? b : a; + nir_scalar bias = flip ? a : b; + if (!match_k_plus_31(xv, k_off)) + continue; + if (scalar_op(bias, nir_op_iand)) { + nir_scalar b0 = nir_scalar_chase_alu_src(bias, 0); + nir_scalar b1 = nir_scalar_chase_alu_src(bias, 1); + nir_scalar sh = is_const_u32(b1, 31) ? b0 : (is_const_u32(b0, 31) ? b1 : (nir_scalar){0}); + if (sh.def && (scalar_op(sh, nir_op_ishr) || scalar_op(sh, nir_op_ushr)) && + is_const_u32(nir_scalar_chase_alu_src(sh, 1), 31) && + match_k_plus_31(nir_scalar_chase_alu_src(sh, 0), k_off)) + return true; + } else if (scalar_op(bias, nir_op_ushr)) { + nir_scalar b0 = nir_scalar_chase_alu_src(bias, 0); + nir_scalar b1 = nir_scalar_chase_alu_src(bias, 1); + if (is_const_u32(b1, 27) && scalar_op(b0, nir_op_ishr) && + is_const_u32(nir_scalar_chase_alu_src(b0, 1), 31) && + match_k_plus_31(nir_scalar_chase_alu_src(b0, 0), k_off)) + return true; + } + } + } + } + /* Lowered signed idiv by 32 via isign(x) * (iabs(x) >> 5), where isign(x) + * may be lowered to imin(imax(x, -1), 1) or imax(imin(x, 1), -1). */ + if (scalar_op(s, nir_op_imul)) { + nir_scalar a = nir_scalar_chase_alu_src(s, 0); + nir_scalar b = nir_scalar_chase_alu_src(s, 1); + for (unsigned flip = 0; flip < 2; ++flip) { + nir_scalar sgn = flip ? b : a; + nir_scalar mag = flip ? a : b; + if (!scalar_op(mag, nir_op_ushr) || + !is_const_u32(nir_scalar_chase_alu_src(mag, 1), 5)) + continue; + nir_scalar abs_x = nir_scalar_chase_alu_src(mag, 0); + if (!scalar_op(abs_x, nir_op_iabs)) + continue; + nir_scalar x = nir_scalar_chase_alu_src(abs_x, 0); + if (!match_k_plus_31(x, k_off)) + continue; + bool sgn_ok = false; + if (scalar_op(sgn, nir_op_isign)) { + sgn_ok = match_k_plus_31(nir_scalar_chase_alu_src(sgn, 0), k_off); + } else if (scalar_op(sgn, nir_op_imin)) { + nir_scalar m0 = nir_scalar_chase_alu_src(sgn, 0); + nir_scalar m1 = nir_scalar_chase_alu_src(sgn, 1); + nir_scalar inner = is_const_u32(m1, 1) ? m0 : (is_const_u32(m0, 1) ? m1 : (nir_scalar){0}); + if (inner.def && scalar_op(inner, nir_op_imax)) { + nir_scalar n0 = nir_scalar_chase_alu_src(inner, 0); + nir_scalar n1 = nir_scalar_chase_alu_src(inner, 1); + nir_scalar xv = is_const_u32(n1, UINT32_MAX) ? n0 : + (is_const_u32(n0, UINT32_MAX) ? n1 : (nir_scalar){0}); + sgn_ok = xv.def && match_k_plus_31(xv, k_off); + } + } else if (scalar_op(sgn, nir_op_imax)) { + nir_scalar m0 = nir_scalar_chase_alu_src(sgn, 0); + nir_scalar m1 = nir_scalar_chase_alu_src(sgn, 1); + nir_scalar inner = is_const_u32(m1, UINT32_MAX) ? m0 : (is_const_u32(m0, UINT32_MAX) ? m1 : (nir_scalar){0}); + if (inner.def && scalar_op(inner, nir_op_imin)) { + nir_scalar n0 = nir_scalar_chase_alu_src(inner, 0); + nir_scalar n1 = nir_scalar_chase_alu_src(inner, 1); + nir_scalar xv = is_const_u32(n1, 1) ? n0 : + (is_const_u32(n0, 1) ? n1 : (nir_scalar){0}); + sgn_ok = xv.def && match_k_plus_31(xv, k_off); + } + } + if (sgn_ok) + return true; + } + } + if (scalar_op(s, nir_op_bcsel)) { + /* bcsel(x < 0, (x + 31) >> 5, x >> 5) */ + nir_scalar c = nir_scalar_chase_alu_src(s, 0); + nir_scalar t = nir_scalar_chase_alu_src(s, 1); + nir_scalar f = nir_scalar_chase_alu_src(s, 2); + if (scalar_op(c, nir_op_ilt) && + is_const_u32(nir_scalar_chase_alu_src(c, 1), 0) && + match_k_plus_31(nir_scalar_chase_alu_src(c, 0), k_off) && + scalar_op(f, nir_op_ishr) && + is_const_u32(nir_scalar_chase_alu_src(f, 1), 5) && + match_k_plus_31(nir_scalar_chase_alu_src(f, 0), k_off) && + scalar_op(t, nir_op_ishr) && + is_const_u32(nir_scalar_chase_alu_src(t, 1), 5)) + return true; + } + return false; +} + +struct shared_access_idx { + const nir_variable *var; + bool is_2d; + nir_scalar linear; + nir_scalar row2d; + nir_scalar col2d; +}; + +static bool +match_shared_array_access(const nir_deref_instr *d, struct shared_access_idx *out) +{ + if (!d || !nir_deref_mode_is(d, nir_var_mem_shared) || + d->deref_type != nir_deref_type_array) + return false; + const nir_deref_instr *parent = nir_deref_instr_parent(d); + if (!parent) + return false; + if (parent->deref_type == nir_deref_type_var && parent->var) { + const nir_variable *var = parent->var; + if (!glsl_type_is_array(var->type) || + glsl_get_array_element(var->type) != glsl_float_type() || + glsl_get_length(var->type) < 1024) + return false; + *out = (struct shared_access_idx){ + .var = var, .is_2d = false, .linear = source(d->arr.index), + }; + return true; + } + if (parent->deref_type == nir_deref_type_array) { + const nir_deref_instr *gp = nir_deref_instr_parent(parent); + if (!gp || gp->deref_type != nir_deref_type_var || !gp->var) + return false; + const nir_variable *var = gp->var; + if (!glsl_type_is_array(var->type) || glsl_get_length(var->type) < 32) + return false; + const struct glsl_type *inner = glsl_get_array_element(var->type); + if (!glsl_type_is_array(inner) || + glsl_get_array_element(inner) != glsl_float_type() || + glsl_get_length(inner) != 32) + return false; + *out = (struct shared_access_idx){ + .var = var, .is_2d = true, + .row2d = source(parent->arr.index), + .col2d = source(d->arr.index), + }; + return true; + } + return false; +} + +static bool +is_lid_y_mul256(nir_scalar s, const uint16_t ls[3]) +{ + s = nir_scalar_chase_movs(s); + if (scalar_op(s, nir_op_ishl)) { + return is_local_id_axis(nir_scalar_chase_alu_src(s, 0), ls, 1) && + is_const_u32(nir_scalar_chase_alu_src(s, 1), 8); + } + if (scalar_op(s, nir_op_imul)) { + nir_scalar a = nir_scalar_chase_alu_src(s, 0); + nir_scalar b = nir_scalar_chase_alu_src(s, 1); + return (is_local_id_axis(a, ls, 1) && is_const_u32(b, 256)) || + (is_local_id_axis(b, ls, 1) && is_const_u32(a, 256)); + } + return false; +} + +static bool +match_shared_tile_idx(const struct shared_access_idx *acc, const uint16_t ls[3], + uint32_t *j_out) +{ + if (acc->is_2d) { + return is_local_id_axis(acc->col2d, ls, 0) && + match_lid_row8(acc->row2d, ls, j_out); + } + nir_scalar terms[6]; + unsigned n = 0; + if (!flatten_iadd_terms(acc->linear, terms, &n, 6, 4)) + return false; + bool got_lx = false, got_row_mul32 = false, got_ly256 = false; + uint32_t row_j = 0; + int64_t csum = 0; + for (unsigned i = 0; i < n; ++i) { + nir_scalar row; + if (!got_lx && is_local_id_axis(terms[i], ls, 0)) { + got_lx = true; + } else if (!got_row_mul32 && !got_ly256 && + match_mul32(terms[i], &row) && match_lid_row8(row, ls, &row_j)) { + got_row_mul32 = true; + } else if (!got_row_mul32 && !got_ly256 && is_lid_y_mul256(terms[i], ls)) { + got_ly256 = true; + } else if (nir_scalar_is_const(terms[i]) && terms[i].def->bit_size == 32) { + csum += (int32_t)nir_scalar_as_uint(terms[i]); + } else { + return false; + } + } + if (!got_lx) + return false; + if (got_row_mul32) { + if (csum != 0) + return false; + *j_out = row_j; + return true; + } + if (got_ly256) { + if (csum < 0 || csum >= 256 || (csum % 32) != 0) + return false; + *j_out = (uint32_t)(csum / 32); + return true; + } + return false; +} + +static bool +match_tile_k_plus_lid_row(nir_scalar s, const uint16_t ls[3], + const nir_phi_instr *tile_phi, + const nir_phi_instr *k_idx_phi, uint32_t expected_j) +{ + nir_scalar terms[6]; + unsigned n = 0; + if (!flatten_iadd_terms(s, terms, &n, 6, 4)) + return false; + bool got_k = false, got_lid_y = false; + int64_t csum = 0; + for (unsigned i = 0; i < n; ++i) { + if (!got_k && is_tile_k_base(terms[i], tile_phi, k_idx_phi)) { + got_k = true; + } else if (!got_lid_y && is_lid_y_mul8(terms[i], ls)) { + got_lid_y = true; + } else if (nir_scalar_is_const(terms[i]) && terms[i].def->bit_size == 32) { + csum += (int32_t)nir_scalar_as_uint(terms[i]); + } else { + return false; + } + } + return got_k && got_lid_y && csum == (int64_t)expected_j; +} + +static bool +match_a_ssbo_idx(nir_scalar idx, const uint16_t ls[3], uint32_t k_off, + const nir_phi_instr *tile_phi, const nir_phi_instr *k_idx_phi, + uint32_t j) +{ + nir_scalar terms[6]; + unsigned n = 0; + if (!flatten_iadd_terms(idx, terms, &n, 6, 4)) + return false; + bool got_row_k = false, got_tile_k = false, got_lid_x = false; + for (unsigned i = 0; i < n; ++i) { + if (is_const_u32(terms[i], 0)) + continue; + if (!got_tile_k && is_tile_k_base(terms[i], tile_phi, k_idx_phi)) { + got_tile_k = true; + } else if (!got_lid_x && is_local_id_axis(terms[i], ls, 0)) { + got_lid_x = true; + } else if (!got_row_k && scalar_op(terms[i], nir_op_imul)) { + nir_scalar a = nir_scalar_chase_alu_src(terms[i], 0); + nir_scalar b = nir_scalar_chase_alu_src(terms[i], 1); + uint32_t r, rj, off; + if ((match_gemm_row(a, ls, &r, &rj) && r == 8 && rj == j && + push_count(b, &off) && off == k_off) || + (match_gemm_row(b, ls, &r, &rj) && r == 8 && rj == j && + push_count(a, &off) && off == k_off)) + got_row_k = true; + else + return false; + } else { + return false; + } + } + return got_row_k && got_tile_k && got_lid_x; +} + +static bool +match_b_ssbo_idx(nir_scalar idx, const uint16_t ls[3], uint32_t n_off, + const nir_phi_instr *tile_phi, const nir_phi_instr *k_idx_phi, + uint32_t j) +{ + nir_scalar terms[4]; + unsigned n = 0; + if (!flatten_iadd_terms(idx, terms, &n, 4, 3)) + return false; + bool got_row_n = false, got_col = false; + for (unsigned i = 0; i < n; ++i) { + if (is_const_u32(terms[i], 0)) + continue; + if (!got_col && is_global_id(terms[i], ls, 0)) { + got_col = true; + } else if (!got_row_n && scalar_op(terms[i], nir_op_imul)) { + nir_scalar a = nir_scalar_chase_alu_src(terms[i], 0); + nir_scalar b = nir_scalar_chase_alu_src(terms[i], 1); + uint32_t off; + if ((match_tile_k_plus_lid_row(a, ls, tile_phi, k_idx_phi, j) && + push_count(b, &off) && off == n_off) || + (match_tile_k_plus_lid_row(b, ls, tile_phi, k_idx_phi, j) && + push_count(a, &off) && off == n_off)) + got_row_n = true; + else + return false; + } else { + return false; + } + } + return got_row_n && got_col; +} + +static bool +match_gemm_shared_guard(nir_if *branch, bool is_a, const uint16_t ls[3], + uint32_t m_off, uint32_t n_off, uint32_t k_off, + const nir_phi_instr *tile_phi, + const nir_phi_instr *k_idx_phi, uint32_t j) +{ + nir_scalar p0 = {0}, p1 = {0}; + if (!match_guard_cond_pair(branch, ls, &p0, &p1)) + return false; + if ((!scalar_op(p0, nir_op_ilt) && !scalar_op(p0, nir_op_ult)) || + (!scalar_op(p1, nir_op_ilt) && !scalar_op(p1, nir_op_ult))) + return false; + + nir_scalar pairs[2][2] = { + { nir_scalar_chase_alu_src(p0, 0), nir_scalar_chase_alu_src(p0, 1) }, + { nir_scalar_chase_alu_src(p1, 0), nir_scalar_chase_alu_src(p1, 1) }, + }; + bool got0 = false, got1 = false; + for (unsigned i = 0; i < 2; ++i) { + uint32_t off, r, rj; + if (is_a) { + if (match_gemm_row(pairs[i][0], ls, &r, &rj) && r == 8 && rj == j && + push_count(pairs[i][1], &off) && off == m_off) { + got0 = true; + } else if (push_count(pairs[i][1], &off) && off == k_off) { + nir_scalar t[4]; + unsigned tn = 0; + bool tk = false, lx = false; + if (flatten_iadd_terms(pairs[i][0], t, &tn, 4, 3)) { + bool ok = true; + for (unsigned ti = 0; ti < tn; ++ti) { + if (is_const_u32(t[ti], 0)) + continue; + else if (!tk && is_tile_k_base(t[ti], tile_phi, k_idx_phi)) + tk = true; + else if (!lx && is_local_id_axis(t[ti], ls, 0)) + lx = true; + else + ok = false; + } + if (ok && tk && lx) + got1 = true; + } + } + } else { + if (is_global_id(pairs[i][0], ls, 0) && + push_count(pairs[i][1], &off) && off == n_off) { + got0 = true; + } else if (match_tile_k_plus_lid_row(pairs[i][0], ls, tile_phi, k_idx_phi, j) && + push_count(pairs[i][1], &off) && off == k_off) { + got1 = true; + } + } + } + return got0 && got1; +} + +static bool +match_dot_step(nir_scalar acc_in, nir_scalar acc_prev, + const nir_variable *s_a, const nir_variable *s_b, + const uint16_t ls[3], uint32_t j, + const nir_phi_instr *l_phi, uint32_t *kk_out) +{ + acc_in = nir_scalar_chase_movs(acc_in); + nir_scalar op_a = {0}, op_b = {0}; + if (scalar_op(acc_in, nir_op_ffma)) { + const nir_alu_instr *alu = nir_def_as_alu(acc_in.def); + if (alu->fp_math_ctrl != 0) + return false; + nir_scalar s2 = nir_scalar_chase_alu_src(acc_in, 2); + if (s2.def != acc_prev.def || s2.comp != acc_prev.comp) + return false; + op_a = nir_scalar_chase_alu_src(acc_in, 0); + op_b = nir_scalar_chase_alu_src(acc_in, 1); + } else if (scalar_op(acc_in, nir_op_fadd)) { + const nir_alu_instr *alu = nir_def_as_alu(acc_in.def); + if (alu->fp_math_ctrl != 0) + return false; + nir_scalar s0 = nir_scalar_chase_alu_src(acc_in, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(acc_in, 1); + nir_scalar prod = {0}; + if (s0.def == acc_prev.def && s0.comp == acc_prev.comp) + prod = s1; + else if (s1.def == acc_prev.def && s1.comp == acc_prev.comp) + prod = s0; + else + return false; + if (!scalar_op(prod, nir_op_fmul) || nir_def_as_alu(prod.def)->fp_math_ctrl != 0) + return false; + op_a = nir_scalar_chase_alu_src(prod, 0); + op_b = nir_scalar_chase_alu_src(prod, 1); + } else { + return false; + } + + const nir_intrinsic_instr *ld0 = intrinsic(op_a.def, nir_intrinsic_load_deref); + const nir_intrinsic_instr *ld1 = intrinsic(op_b.def, nir_intrinsic_load_deref); + if (!ld0 || !ld1 || !nir_def_is_deref(ld0->src[0].ssa) || + !nir_def_is_deref(ld1->src[0].ssa)) + return false; + struct shared_access_idx acc0 = {0}, acc1 = {0}; + if (!match_shared_array_access(nir_def_as_deref(ld0->src[0].ssa), &acc0) || + !match_shared_array_access(nir_def_as_deref(ld1->src[0].ssa), &acc1)) + return false; + const struct shared_access_idx *a_acc = NULL, *b_acc = NULL; + if (acc0.var == s_a && acc1.var == s_b) { + a_acc = &acc0; + b_acc = &acc1; + } else if (acc0.var == s_b && acc1.var == s_a) { + a_acc = &acc1; + b_acc = &acc0; + } else { + return false; + } + + /* Match A: s_a[lid_y * 8 + j, kk] */ + bool a_has_const_k = false; + uint32_t a_k_const = 0; + if (a_acc->is_2d) { + uint32_t aj = 0; + if (!match_lid_row8(a_acc->row2d, ls, &aj) || aj != j) + return false; + if (l_phi) { + if (!is_phi_scalar(a_acc->col2d, l_phi)) + return false; + } else { + nir_scalar ck = nir_scalar_chase_movs(a_acc->col2d); + if (!nir_scalar_is_const(ck) || ck.def->bit_size != 32) + return false; + a_k_const = (uint32_t)nir_scalar_as_uint(ck); + a_has_const_k = true; + } + } else { + nir_scalar terms[6]; + unsigned n = 0; + if (!flatten_iadd_terms(a_acc->linear, terms, &n, 6, 4)) + return false; + bool got_row_mul32 = false, got_ly256 = false, got_l = false; + int64_t csum = 0; + for (unsigned i = 0; i < n; ++i) { + nir_scalar row; + uint32_t aj = 0; + if (l_phi && !got_l && is_phi_scalar(terms[i], l_phi)) { + got_l = true; + } else if (!got_row_mul32 && !got_ly256 && + match_mul32(terms[i], &row) && + match_lid_row8(row, ls, &aj) && aj == j) { + got_row_mul32 = true; + } else if (!got_row_mul32 && !got_ly256 && is_lid_y_mul256(terms[i], ls)) { + got_ly256 = true; + } else if (nir_scalar_is_const(terms[i]) && terms[i].def->bit_size == 32) { + csum += (int32_t)nir_scalar_as_uint(terms[i]); + } else { + return false; + } + } + if (!got_row_mul32 && !got_ly256) + return false; + if (l_phi) { + if (!got_l) + return false; + if (got_row_mul32 && csum != 0) + return false; + if (got_ly256 && csum != (int64_t)j * 32) + return false; + } else { + int64_t k_val = got_row_mul32 ? csum : (csum - (int64_t)j * 32); + if (k_val < 0 || k_val >= 32) + return false; + a_k_const = (uint32_t)k_val; + a_has_const_k = true; + } + } + + /* Match B: s_b[kk, lid_x] */ + uint32_t b_k_const = 0; + if (b_acc->is_2d) { + if (!is_local_id_axis(b_acc->col2d, ls, 0)) + return false; + if (l_phi) { + if (!is_phi_scalar(b_acc->row2d, l_phi)) + return false; + return true; + } + nir_scalar ck = nir_scalar_chase_movs(b_acc->row2d); + if (!nir_scalar_is_const(ck) || ck.def->bit_size != 32) + return false; + b_k_const = (uint32_t)nir_scalar_as_uint(ck); + } else { + nir_scalar terms[4]; + unsigned n = 0; + if (!flatten_iadd_terms(b_acc->linear, terms, &n, 4, 3)) + return false; + bool got_lx = false, got_l32 = false; + int64_t csum = 0; + for (unsigned i = 0; i < n; ++i) { + nir_scalar kk; + if (!got_lx && is_local_id_axis(terms[i], ls, 0)) { + got_lx = true; + } else if (l_phi && !got_l32 && match_mul32(terms[i], &kk) && + is_phi_scalar(kk, l_phi)) { + got_l32 = true; + } else if (nir_scalar_is_const(terms[i]) && terms[i].def->bit_size == 32) { + csum += (int32_t)nir_scalar_as_uint(terms[i]); + } else { + return false; + } + } + if (!got_lx) + return false; + if (l_phi) + return got_l32 && csum == 0; + if (csum < 0 || (csum % 32) != 0 || (csum / 32) >= 32) + return false; + b_k_const = (uint32_t)(csum / 32); + } + + if (!a_has_const_k || a_k_const != b_k_const || a_k_const >= 32) + return false; + if (kk_out) + *kk_out = a_k_const; + return true; +} + +static unsigned +count_cf_loops(const struct exec_list *list) +{ + unsigned n = 0; + foreach_list_typed(nir_cf_node, node, node, list) { + if (node->type == nir_cf_node_loop) { + n += 1 + count_cf_loops(&nir_cf_node_as_loop(node)->body); + } else if (node->type == nir_cf_node_if) { + nir_if *nif = nir_cf_node_as_if(node); + n += count_cf_loops(&nif->then_list); + n += count_cf_loops(&nif->else_list); + } + } + return n; +} + +static bool +match_loop_iv_less_than(nir_loop *loop, const nir_phi_instr *iv, + bool match_const_bound, uint32_t const_bound, + bool match_ceil32_k, uint32_t k_off, + bool match_raw_k, + const nir_instr **exit_break_out) +{ + nir_block *hdr = nir_loop_first_block(loop); + nir_cf_node *next = nir_cf_node_next(&hdr->cf_node); + if (!next || next->type != nir_cf_node_if) + return false; + nir_if *br = nir_cf_node_as_if(next); + nir_block *tb = nir_if_first_then_block(br); + nir_block *eb = nir_if_first_else_block(br); + bool then_break = + exec_list_is_singular(&br->then_list) && + !exec_list_is_empty(&tb->instr_list) && + nir_block_last_instr(tb)->type == nir_instr_type_jump && + nir_instr_as_jump(nir_block_last_instr(tb))->type == nir_jump_break; + bool else_break = + exec_list_is_singular(&br->else_list) && + !exec_list_is_empty(&eb->instr_list) && + nir_block_last_instr(eb)->type == nir_instr_type_jump && + nir_instr_as_jump(nir_block_last_instr(eb))->type == nir_jump_break; + if (then_break == else_break) + return false; + + const nir_instr *break_instr = + then_break ? nir_block_last_instr(tb) : nir_block_last_instr(eb); + + nir_scalar cond = source(br->condition); + if (then_break && scalar_op(cond, nir_op_inot)) { + cond = nir_scalar_chase_alu_src(cond, 0); + then_break = false; + else_break = true; + } + + nir_scalar lhs = {0}, rhs = {0}; + if (else_break) { + if (!scalar_op(cond, nir_op_ilt) && !scalar_op(cond, nir_op_ult)) + return false; + lhs = nir_scalar_chase_alu_src(cond, 0); + rhs = nir_scalar_chase_alu_src(cond, 1); + } else { + if (!scalar_op(cond, nir_op_ige) && !scalar_op(cond, nir_op_uge)) + return false; + lhs = nir_scalar_chase_alu_src(cond, 0); + rhs = nir_scalar_chase_alu_src(cond, 1); + } + if (!is_phi_scalar(lhs, iv)) + return false; + bool bound_ok = false; + if (match_const_bound) + bound_ok = is_const_u32(rhs, const_bound); + else if (match_ceil32_k) + bound_ok = match_ceil_div_32(rhs, k_off); + else if (match_raw_k) { + uint32_t off; + bound_ok = push_count(rhs, &off) && off == k_off; + } + if (!bound_ok) + return false; + if (exit_break_out) + *exit_break_out = break_instr; + return true; +} + +static bool +is_wg_shared_barrier(const nir_instr *instr) +{ + if (instr->type != nir_instr_type_intrinsic) + return false; + const nir_intrinsic_instr *op = nir_instr_as_intrinsic(instr); + return op->intrinsic == nir_intrinsic_barrier && + nir_intrinsic_execution_scope(op) == SCOPE_WORKGROUP && + (nir_intrinsic_memory_modes(op) & nir_var_mem_shared); +} + +/* Match a leaf C-store value against one of: + * bias_kind == 0: acc_phi[j] + bias[row_j] + * bias_kind == 1: acc_phi[j] + bias[col] + * bias_kind == 2: acc_phi[j] (no bias) + */ +static const nir_phi_instr * +match_c_store_bias_leaf(nir_scalar sv, const nir_block *k_hdr, + const uint16_t ls[3], uint32_t j, + bool has_bias_buffer, + struct hk_nir_clamp_buffer bias_binding, + unsigned desc_comps, int *bias_kind_out) +{ + sv = nir_scalar_chase_movs(sv); + if (nir_def_is_phi(sv.def) && nir_def_instr(sv.def)->block == k_hdr) { + *bias_kind_out = 2; + return nir_def_as_phi(sv.def); + } + if (scalar_op(sv, nir_op_fadd) && + nir_def_as_alu(sv.def)->fp_math_ctrl == 0 && has_bias_buffer) { + for (unsigned s = 0; s < 2; ++s) { + nir_scalar op0 = nir_scalar_chase_alu_src(sv, s); + nir_scalar op1 = nir_scalar_chase_alu_src(sv, 1 - s); + if (!nir_def_is_phi(op0.def) || nir_def_instr(op0.def)->block != k_hdr) + continue; + const nir_intrinsic_instr *bld = + intrinsic(op1.def, nir_intrinsic_load_deref); + struct buffer_access bacc; + if (!bld || !storage_read(bld, desc_comps, &bacc) || + !same_binding(bacc.binding, bias_binding)) + continue; + uint32_t br = 0, bj = 0; + if (is_global_id(bacc.element, ls, 0)) { + *bias_kind_out = 1; + return nir_def_as_phi(op0.def); + } + if (match_gemm_row(bacc.element, ls, &br, &bj) && br == 8 && bj == j) { + *bias_kind_out = 0; + return nir_def_as_phi(op0.def); + } + } + } + return NULL; +} + +/* Recursively verify a non-split C-store value that merges bias_mode arms via + * phis: every then-arm of `bias_mode == m` must produce the exact matching + * bias kind (0=row, 1=col, 2=none), and every fallthrough else-leaf must be + * plain acc_phi (kind 2). */ +static const nir_phi_instr * +extract_dyn_bias_phi(nir_scalar sv, const nir_block *src_block, + const nir_block *k_hdr, const uint16_t ls[3], uint32_t j, + bool has_bias_buffer, + struct hk_nir_clamp_buffer bias_binding, + uint32_t bias_mode_off, unsigned desc_comps, + uint8_t *seen_modes, unsigned depth) +{ + sv = nir_scalar_chase_movs(sv); + if (depth > 4) + return NULL; + if (nir_def_is_phi(sv.def) && nir_def_instr(sv.def)->block != k_hdr) { + nir_phi_instr *p = nir_def_as_phi(sv.def); + nir_cf_node *prev = nir_cf_node_prev(&p->instr.block->cf_node); + uint32_t if_off = 0, if_mode = 0; + if (!prev || prev->type != nir_cf_node_if || + !match_bias_mode_if(nir_cf_node_as_if(prev), &if_off, &if_mode) || + if_off != bias_mode_off) + return NULL; + + const nir_phi_instr *common = NULL; + nir_foreach_phi_src(src, p) { + const nir_phi_instr *sub = extract_dyn_bias_phi( + source(src->src), src->pred, k_hdr, ls, j, has_bias_buffer, + bias_binding, bias_mode_off, desc_comps, seen_modes, depth + 1); + if (!sub || (common && common != sub)) + return NULL; + common = sub; + } + return common; + } + + int kind = -1; + const nir_phi_instr *acc = match_c_store_bias_leaf( + sv, k_hdr, ls, j, has_bias_buffer, bias_binding, desc_comps, &kind); + if (!acc) + return NULL; + + uint32_t arm_off = 0, arm_mode = 0; + if (find_bias_mode_arm(&((nir_block *)src_block)->cf_node, &arm_off, + &arm_mode)) { + if (arm_off != bias_mode_off || kind != (int)arm_mode) + return NULL; + *seen_modes |= (uint8_t)(1u << arm_mode); + } else { + /* Fallthrough else arm corresponds to no-bias (mode 2). */ + if (kind != 2) + return NULL; + *seen_modes |= (uint8_t)(1u << 2); + } + return acc; +} + +static bool +is_shared_load(const nir_intrinsic_instr *op) +{ + return op->intrinsic == nir_intrinsic_load_deref && + nir_def_is_deref(op->src[0].ssa) && + nir_deref_mode_is(nir_def_as_deref(op->src[0].ssa), + nir_var_mem_shared); +} + +/* True if a shared-memory load lies outside the CF subtree `node`. */ +static bool +has_shared_load_outside(const nir_function_impl *impl, const nir_cf_node *node) +{ + nir_foreach_block(blk, (nir_function_impl *)impl) { + const nir_cf_node *cur = &blk->cf_node; + while (cur && cur != node) + cur = cur->parent; + if (cur) + continue; + nir_foreach_instr(instr, blk) { + if (instr->type == nir_instr_type_intrinsic && + is_shared_load(nir_instr_as_intrinsic(instr))) + return true; + } + } + return false; +} + +/* The cmat alternate writes every in-bounds C element exactly once per + * dispatch, so a certified C store may only be predicated by what the + * alternate reproduces: the per-element `row < M && col < N` guard (guarded + * form: the store's immediate parent, then-arm) and, for stores split per + * bias_mode arm, the `bias_mode == mode` dispatch chain (the then-arm of + * exactly one `bias_mode == mode` if, plus the else-arms of `bias_mode == m` + * ifs with m != mode). Any other enclosing if or loop, at any depth up to + * the function body, can skip or repeat the store in the original. */ +static bool +c_store_cf_accounted(const nir_intrinsic_instr *store, const uint16_t ls[3], + uint32_t j, uint32_t n_off, bool is_guarded, + uint32_t m_off, bool stores_split_by_bias_mode, + uint32_t bias_mode_off, uint32_t mode) +{ + nir_cf_node *store_block = &store->instr.block->cf_node; + bool seen_guard = false, seen_arm = false; + + for (nir_cf_node *cur = store_block; + cur->parent && cur->parent->type != nir_cf_node_function; + cur = cur->parent) { + if (cur->parent->type != nir_cf_node_if) + return false; + nir_if *branch = nir_cf_node_as_if(cur->parent); + const bool then_arm = in_then(cur, branch); + + uint32_t guard_m_off = UINT32_MAX; + if (is_guarded && cur == store_block && then_arm && + match_gemm_store_guard(branch, ls, 8, j, n_off, &guard_m_off) && + guard_m_off == m_off) { + seen_guard = true; + continue; + } + + uint32_t if_off = 0, if_mode = 0; + if (stores_split_by_bias_mode && + match_bias_mode_if(branch, &if_off, &if_mode) && + if_off == bias_mode_off) { + if (then_arm && !seen_arm && if_mode == mode) { + seen_arm = true; + continue; + } + if (!then_arm && if_mode != mode) + continue; + } + return false; + } + + return seen_guard == is_guarded && seen_arm == stores_split_by_bias_mode; +} + +/* Certify that a matched 32x4x1, 8-row/thread GEMM producer actually executes + * a standard 32x32 shared-memory tiled row-major FP32 GEMM K-loop + * `C[row, col] = sum_{k=0..K-1} A[row*K + k] * B[k*N + col] (+ bias)` with + * default FP32 math controls. + * + * Floating-point exactness requirement: the certified original executes a + * sequential FP32 ffma (or fmul+fadd) chain per output element under default + * Vulkan math controls, which permit FMA contraction but NOT reassociation or + * reordering of the summation. Replacement by AGX `f32matmad8x8` therefore + * relies on hardware `f32matmad8x8` being bit-exact with that sequential FP32 + * FMA accumulation order (including NaN/Inf propagation, overflow, and + * denormals). */ +static bool +certify_gemm_row_major_k_loop(const nir_function_impl *impl, + const uint16_t ls[3], + const nir_intrinsic_instr *const *c_stores, + const struct buffer_access *c_access, + unsigned num_c_stores, + struct hk_nir_clamp_buffer a_binding, + struct hk_nir_clamp_buffer b_binding, + bool has_bias_buffer, + struct hk_nir_clamp_buffer bias_binding, + bool stores_split_by_bias_mode, + bool has_bias_mode, uint32_t bias_mode_off, + uint8_t bias_mode_mask, + bool is_guarded, + uint32_t m_off, uint32_t n_off, uint32_t k_off, + unsigned desc_comps) +{ + /* 1. Require exactly one top-level K-tile loop in the entrypoint body. */ + nir_loop *k_loop = NULL; + foreach_list_typed(nir_cf_node, node, node, &impl->body) { + if (node->type == nir_cf_node_loop) { + if (k_loop) + return false; + k_loop = nir_cf_node_as_loop(node); + } + } + if (!k_loop) + return false; + + nir_block *k_pre = nir_cf_node_as_block(nir_cf_node_prev(&k_loop->cf_node)); + nir_block *k_hdr = nir_loop_first_block(k_loop); + nir_block *k_back = nir_loop_last_block(k_loop); + + /* 2. Map every C store (rows j = 0..7) back to its outer-loop acc_phi[j] + * and enforce the exact bias convention (0=row, 1=col, 2=none) on both + * split-store and non-split paths. */ + const nir_phi_instr *acc_phi[8] = {0}; + for (unsigned i = 0; i < num_c_stores; ++i) { + uint32_t r = 0, j = 0, store_n_off = 0; + if (!match_gemm_c_index(c_access[i].element, ls, &r, &j, &store_n_off) || + r != 8 || j >= 8 || store_n_off != n_off) + return false; + + const nir_phi_instr *phi = NULL; + uint32_t arm_mode = 0; + if (stores_split_by_bias_mode) { + uint32_t arm_off = 0; + int kind = -1; + if (!find_bias_mode_arm(&c_stores[i]->instr.block->cf_node, &arm_off, + &arm_mode) || + arm_off != bias_mode_off) + return false; + phi = match_c_store_bias_leaf(source(c_stores[i]->src[1]), k_hdr, ls, j, + has_bias_buffer, bias_binding, desc_comps, + &kind); + if (!phi || kind != (int)arm_mode) + return false; + } else if (!has_bias_mode) { + int want_kind = -1; + if (!has_bias_buffer) + want_kind = 2; + else if (bias_mode_mask == (1u << 0)) + want_kind = 0; + else if (bias_mode_mask == (1u << 1)) + want_kind = 1; + else + return false; + int kind = -1; + phi = match_c_store_bias_leaf(source(c_stores[i]->src[1]), k_hdr, ls, j, + has_bias_buffer, bias_binding, desc_comps, + &kind); + if (!phi || kind != want_kind) + return false; + } else { + uint8_t seen_modes = 0; + phi = extract_dyn_bias_phi(source(c_stores[i]->src[1]), + c_stores[i]->instr.block, k_hdr, ls, j, + has_bias_buffer, bias_binding, bias_mode_off, + desc_comps, &seen_modes, 0); + if (!phi || seen_modes != bias_mode_mask) + return false; + } + + if (!c_store_cf_accounted(c_stores[i], ls, j, n_off, is_guarded, m_off, + stores_split_by_bias_mode, bias_mode_off, + arm_mode)) + return false; + + if (acc_phi[j] && acc_phi[j] != phi) + return false; + acc_phi[j] = phi; + } + + for (unsigned j = 0; j < 8; ++j) { + if (!acc_phi[j]) + return false; + for (unsigned k = 0; k < j; ++k) { + if (acc_phi[k] == acc_phi[j]) + return false; + } + /* Pre-header accumulator must initialize to +0.0f. */ + bool pre_zero = false, got_back = false; + nir_foreach_phi_src(src, acc_phi[j]) { + if (src->pred == k_pre) + pre_zero = is_const_u32(source(src->src), 0x00000000u); + else if (src->pred == k_back) + got_back = true; + else + return false; + } + if (!pre_zero || !got_back) + return false; + } + + /* 3. Classify outer-loop induction variables (tile_phi +1, k_idx_phi +32) + * and verify the K-tile exit bound. */ + const nir_phi_instr *tile_phi = NULL; + const nir_phi_instr *k_idx_phi = NULL; + nir_foreach_phi(phi, k_hdr) { + bool is_acc = false; + for (unsigned j = 0; j < 8; ++j) { + if (acc_phi[j] == phi) + is_acc = true; + } + if (is_acc) + continue; + nir_scalar pre_v = {0}, back_v = {0}; + bool got_pre = false, got_back = false; + nir_foreach_phi_src(src, phi) { + if (src->pred == k_pre) { + pre_v = source(src->src); + got_pre = true; + } else if (src->pred == k_back) { + back_v = source(src->src); + got_back = true; + } else { + return false; + } + } + if (!got_pre || !got_back || !is_const_u32(pre_v, 0) || + !scalar_op(back_v, nir_op_iadd)) + return false; + nir_scalar a = nir_scalar_chase_alu_src(back_v, 0); + nir_scalar b = nir_scalar_chase_alu_src(back_v, 1); + nir_scalar step = {0}; + if (is_phi_scalar(a, phi)) + step = b; + else if (is_phi_scalar(b, phi)) + step = a; + else + return false; + if (is_const_u32(step, 1)) { + if (tile_phi) + return false; + tile_phi = phi; + } else if (is_const_u32(step, 32)) { + if (k_idx_phi) + return false; + k_idx_phi = phi; + } else { + return false; + } + } + if (!tile_phi && !k_idx_phi) + return false; + + const nir_instr *k_exit_break = NULL; + bool exit_ok = false; + if (tile_phi && + match_loop_iv_less_than(k_loop, tile_phi, false, 0, true, k_off, false, + &k_exit_break)) + exit_ok = true; + else if (k_idx_phi && + match_loop_iv_less_than(k_loop, k_idx_phi, false, 0, false, k_off, true, + &k_exit_break)) + exit_ok = true; + if (!exit_ok || !k_exit_break) + return false; + + /* 4. Partition k_loop body into Phase 1 (before first WG barrier), + * Phase 2 (between first and second WG barriers), and tail. */ + unsigned barrier_stage = 0; /* 0 = Phase 1, 1 = Phase 2, 2 = after barrier_2 */ + nir_loop *dot_loop = NULL; + const nir_variable *s_a = NULL, *s_b = NULL; + uint8_t a_load_mask = 0, a_zero_mask = 0; + uint8_t b_load_mask = 0, b_zero_mask = 0; + + foreach_list_typed(nir_cf_node, cf, node, &k_loop->body) { + if (cf->type == nir_cf_node_loop) { + if (barrier_stage != 1 || dot_loop) + return false; + dot_loop = nir_cf_node_as_loop(cf); + continue; + } + + /* Walk every block inside this top-level CF node of k_loop. */ + nir_block *start = (cf->type == nir_cf_node_block) + ? nir_cf_node_as_block(cf) + : nir_cf_node_cf_tree_first(cf); + nir_block *end = (cf->type == nir_cf_node_block) + ? start + : nir_cf_node_cf_tree_last(cf); + + for (nir_block *blk = start; blk; blk = (blk == end) ? NULL : nir_block_cf_tree_next(blk)) { + nir_foreach_instr(instr, blk) { + if (is_wg_shared_barrier(instr)) { + if (cf->type != nir_cf_node_block) + return false; + if (barrier_stage < 2) + barrier_stage++; + else + return false; + continue; + } + if (instr->type != nir_instr_type_intrinsic) + continue; + const nir_intrinsic_instr *op = nir_instr_as_intrinsic(instr); + if (is_shared_load(op)) { + /* Tile reads belong to Phase 2 only. The dot_loop form ties + * its loads to l_phi; the unrolled form uses constant columns + * and would otherwise also accept a read before barrier_1. */ + if (barrier_stage != 1) + return false; + continue; + } + if (op->intrinsic != nir_intrinsic_store_deref) + continue; + if (!nir_def_is_deref(op->src[0].ssa)) + return false; + const nir_deref_instr *dst = nir_def_as_deref(op->src[0].ssa); + /* No SSBO stores allowed inside the K-loop, and shared stores only in Phase 1. */ + if (!nir_deref_mode_is(dst, nir_var_mem_shared) || barrier_stage != 0) + return false; + if (op->num_components != 1 || op->src[1].ssa->bit_size != 32 || + nir_intrinsic_write_mask(op) != 1) + return false; + + struct shared_access_idx sh_acc = {0}; + uint32_t j = 0; + if (!match_shared_array_access(dst, &sh_acc) || + !match_shared_tile_idx(&sh_acc, ls, &j) || j >= 8) + return false; + const nir_variable *var = sh_acc.var; + + nir_scalar val = source(op->src[1]); + const nir_intrinsic_instr *ld = intrinsic(val.def, nir_intrinsic_load_deref); + bool is_zero = is_const_u32(val, 0x00000000u); + + if (!is_guarded) { + if (cf->type != nir_cf_node_block || !ld) + return false; + struct buffer_access acc; + if (!storage_read(ld, desc_comps, &acc)) + return false; + if (same_binding(acc.binding, a_binding) && + match_a_ssbo_idx(acc.element, ls, k_off, tile_phi, k_idx_phi, j)) { + if (s_a && s_a != var) + return false; + s_a = var; + if (a_load_mask & (1u << j)) + return false; + a_load_mask |= (uint8_t)(1u << j); + } else if (same_binding(acc.binding, b_binding) && + match_b_ssbo_idx(acc.element, ls, n_off, tile_phi, k_idx_phi, j)) { + if (s_b && s_b != var) + return false; + s_b = var; + if (b_load_mask & (1u << j)) + return false; + b_load_mask |= (uint8_t)(1u << j); + } else { + return false; + } + } else { + /* Guarded: either direct if/else stores, or phi(load, 0.0f) store. */ + if (cf->type == nir_cf_node_if) { + nir_if *br = nir_cf_node_as_if(cf); + /* The store must sit directly in an arm of the guard `br`. + * A store inside a nested `if` in either arm carries a + * predicate that match_gemm_shared_guard() never sees. + * Nested control flow next to a direct store cannot skip + * it: the only jumps allowed are the loop header breaks + * (checked below). */ + if (blk->cf_node.parent != &br->cf_node) + return false; + bool in_t = in_then(&blk->cf_node, br); + if (in_t && ld) { + struct buffer_access acc; + if (!storage_read(ld, desc_comps, &acc)) + return false; + if (same_binding(acc.binding, a_binding) && + match_a_ssbo_idx(acc.element, ls, k_off, tile_phi, k_idx_phi, j) && + match_gemm_shared_guard(br, true, ls, m_off, n_off, k_off, + tile_phi, k_idx_phi, j)) { + if (s_a && s_a != var) + return false; + s_a = var; + if (a_load_mask & (1u << j)) + return false; + a_load_mask |= (uint8_t)(1u << j); + } else if (same_binding(acc.binding, b_binding) && + match_b_ssbo_idx(acc.element, ls, n_off, tile_phi, k_idx_phi, j) && + match_gemm_shared_guard(br, false, ls, m_off, n_off, k_off, + tile_phi, k_idx_phi, j)) { + if (s_b && s_b != var) + return false; + s_b = var; + if (b_load_mask & (1u << j)) + return false; + b_load_mask |= (uint8_t)(1u << j); + } else { + return false; + } + } else if (!in_t && is_zero) { + if (match_gemm_shared_guard(br, true, ls, m_off, n_off, k_off, + tile_phi, k_idx_phi, j)) { + if (s_a && s_a != var) + return false; + s_a = var; + if (a_zero_mask & (1u << j)) + return false; + a_zero_mask |= (uint8_t)(1u << j); + } else if (match_gemm_shared_guard(br, false, ls, m_off, n_off, k_off, + tile_phi, k_idx_phi, j)) { + if (s_b && s_b != var) + return false; + s_b = var; + if (b_zero_mask & (1u << j)) + return false; + b_zero_mask |= (uint8_t)(1u << j); + } else { + return false; + } + } else { + return false; + } + } else if (cf->type == nir_cf_node_block && nir_def_is_phi(val.def)) { + const nir_phi_instr *vphi = nir_def_as_phi(val.def); + nir_cf_node *prev = nir_cf_node_prev(&vphi->instr.block->cf_node); + if (!prev || prev->type != nir_cf_node_if) + return false; + nir_if *br = nir_cf_node_as_if(prev); + nir_scalar tv = {0}, ev = {0}; + bool gt = false, ge = false; + nir_foreach_phi_src(ps, vphi) { + if (ps->pred == nir_if_last_then_block(br)) { + tv = source(ps->src); + gt = true; + } else if (ps->pred == nir_if_last_else_block(br)) { + ev = source(ps->src); + ge = true; + } else { + return false; + } + } + const nir_intrinsic_instr *tld = intrinsic(tv.def, nir_intrinsic_load_deref); + if (!gt || !ge || !tld || !is_const_u32(ev, 0x00000000u)) + return false; + struct buffer_access acc; + if (!storage_read(tld, desc_comps, &acc)) + return false; + if (same_binding(acc.binding, a_binding) && + match_a_ssbo_idx(acc.element, ls, k_off, tile_phi, k_idx_phi, j) && + match_gemm_shared_guard(br, true, ls, m_off, n_off, k_off, + tile_phi, k_idx_phi, j)) { + if (s_a && s_a != var) + return false; + s_a = var; + if ((a_load_mask | a_zero_mask) & (1u << j)) + return false; + a_load_mask |= (uint8_t)(1u << j); + a_zero_mask |= (uint8_t)(1u << j); + } else if (same_binding(acc.binding, b_binding) && + match_b_ssbo_idx(acc.element, ls, n_off, tile_phi, k_idx_phi, j) && + match_gemm_shared_guard(br, false, ls, m_off, n_off, k_off, + tile_phi, k_idx_phi, j)) { + if (s_b && s_b != var) + return false; + s_b = var; + if ((b_load_mask | b_zero_mask) & (1u << j)) + return false; + b_load_mask |= (uint8_t)(1u << j); + b_zero_mask |= (uint8_t)(1u << j); + } else { + return false; + } + } else { + return false; + } + } + } + } + } + + if (barrier_stage != 2 || !s_a || !s_b || s_a == s_b || + a_load_mask != 0xffu || b_load_mask != 0xffu) + return false; + if (has_shared_load_outside(impl, &k_loop->cf_node)) + return false; + if (is_guarded && (a_zero_mask != 0xffu || b_zero_mask != 0xffu)) + return false; + + /* 5. Verify Phase 2 dot-product accumulation for all 8 rows j = 0..7. */ + if (dot_loop) { + nir_block *d_pre = nir_cf_node_as_block(nir_cf_node_prev(&dot_loop->cf_node)); + nir_block *d_hdr = nir_loop_first_block(dot_loop); + nir_block *d_back = nir_loop_last_block(dot_loop); + + /* Reject any stores or barriers inside dot_loop. */ + nir_block *d_end = nir_loop_last_block(dot_loop); + for (nir_block *blk = d_hdr; blk; + blk = (blk == d_end) ? NULL : nir_block_cf_tree_next(blk)) { + nir_foreach_instr(instr, blk) { + if (instr->type == nir_instr_type_intrinsic) { + const nir_intrinsic_instr *op = nir_instr_as_intrinsic(instr); + if (op->intrinsic == nir_intrinsic_store_deref || + op->intrinsic == nir_intrinsic_barrier) + return false; + } + } + } + + /* Map outer acc_phi[j] back-edge -> inner dot_loop phi in_acc[j]. */ + const nir_phi_instr *in_acc[8] = {0}; + for (unsigned j = 0; j < 8; ++j) { + nir_scalar k_next = {0}; + nir_foreach_phi_src(src, acc_phi[j]) { + if (src->pred == k_back) + k_next = source(src->src); + } + if (!k_next.def || !nir_def_is_phi(k_next.def) || + nir_def_instr(k_next.def)->block != d_hdr) + return false; + in_acc[j] = nir_def_as_phi(k_next.def); + } + + /* Find inner index l_phi: 0 .. 31, step +1. */ + const nir_phi_instr *l_phi = NULL; + nir_foreach_phi(phi, d_hdr) { + bool is_acc = false; + for (unsigned j = 0; j < 8; ++j) { + if (in_acc[j] == phi) + is_acc = true; + } + if (is_acc) + continue; + nir_scalar pre_v = {0}, back_v = {0}; + bool gp = false, gb = false; + nir_foreach_phi_src(src, phi) { + if (src->pred == d_pre) { + pre_v = source(src->src); + gp = true; + } else if (src->pred == d_back) { + back_v = source(src->src); + gb = true; + } else { + return false; + } + } + if (!gp || !gb || !is_const_u32(pre_v, 0) || + !scalar_op(back_v, nir_op_iadd)) + return false; + nir_scalar a = nir_scalar_chase_alu_src(back_v, 0); + nir_scalar b = nir_scalar_chase_alu_src(back_v, 1); + if (!((is_phi_scalar(a, phi) && is_const_u32(b, 1)) || + (is_phi_scalar(b, phi) && is_const_u32(a, 1)))) + return false; + if (l_phi) + return false; + l_phi = phi; } - if (mode <= 2) { - *bias_mode_off = off; - *mode_out = mode; - return true; + const nir_instr *dot_exit_break = NULL; + if (!l_phi || + !match_loop_iv_less_than(dot_loop, l_phi, true, 32, false, 0, false, + &dot_exit_break) || + !dot_exit_break) + return false; + + /* Require no extra loops anywhere and no break other than the two loop + * header exits (rejects any early `if (...) break;` in K- or dot-loop). */ + if (count_cf_loops(&impl->body) != 2u) + return false; + nir_foreach_block(blk, (nir_function_impl *)impl) { + nir_foreach_instr(instr, blk) { + if (instr->type == nir_instr_type_jump && + (nir_instr_as_jump(instr)->type != nir_jump_break || + (instr != k_exit_break && instr != dot_exit_break))) + return false; + } + } + + for (unsigned j = 0; j < 8; ++j) { + nir_scalar pre_v = {0}, back_v = {0}; + bool gp = false, gb = false; + nir_foreach_phi_src(src, in_acc[j]) { + if (src->pred == d_pre) { + pre_v = source(src->src); + gp = true; + } else if (src->pred == d_back) { + back_v = source(src->src); + gb = true; + } else { + return false; + } + } + if (!gp || !gb || !is_phi_scalar(pre_v, acc_phi[j])) + return false; + if (!match_dot_step(back_v, nir_get_scalar((nir_def *)&in_acc[j]->def, 0), + s_a, s_b, ls, j, l_phi, NULL)) + return false; } + return true; } - return false; -} -/* Extract push-constant stride from a linear SSBO index `(... * stride) + ...`. */ -static bool -find_linear_stride_push_rec(nir_scalar idx, uint32_t *stride_off, unsigned depth) -{ - idx = nir_scalar_chase_movs(idx); - if (scalar_op(idx, nir_op_imul)) { - if (push_count(nir_scalar_chase_alu_src(idx, 1), stride_off)) - return true; - if (push_count(nir_scalar_chase_alu_src(idx, 0), stride_off)) - return true; + /* Require K-loop is the only loop and its header exit is the only break. */ + if (count_cf_loops(&impl->body) != 1u) return false; + nir_foreach_block(blk, (nir_function_impl *)impl) { + nir_foreach_instr(instr, blk) { + if (instr->type == nir_instr_type_jump && + (nir_instr_as_jump(instr)->type != nir_jump_break || + instr != k_exit_break)) + return false; + } } - if (!depth || !scalar_op(idx, nir_op_iadd)) - return false; - return find_linear_stride_push_rec(nir_scalar_chase_alu_src(idx, 0), stride_off, depth - 1) || - find_linear_stride_push_rec(nir_scalar_chase_alu_src(idx, 1), stride_off, depth - 1); -} -static bool -find_linear_stride_push(nir_scalar idx, uint32_t *stride_off) -{ - return find_linear_stride_push_rec(idx, stride_off, 4); + /* Unrolled 32-step dot-product fallback (no inner loop). */ + for (unsigned j = 0; j < 8; ++j) { + nir_scalar cur = {0}; + nir_foreach_phi_src(src, acc_phi[j]) { + if (src->pred == k_back) + cur = source(src->src); + } + uint32_t seen_kk = 0; + for (unsigned step = 0; step < 32; ++step) { + cur = nir_scalar_chase_movs(cur); + nir_scalar prev = {0}; + if (scalar_op(cur, nir_op_ffma)) { + prev = nir_scalar_chase_alu_src(cur, 2); + } else if (scalar_op(cur, nir_op_fadd)) { + nir_scalar s0 = nir_scalar_chase_alu_src(cur, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(cur, 1); + prev = scalar_op(s1, nir_op_fmul) ? s0 : s1; + } else { + return false; + } + uint32_t kk = 0; + if (!match_dot_step(cur, prev, s_a, s_b, ls, j, NULL, &kk) || + (seen_kk & (1u << kk))) + return false; + seen_kk |= (1u << kk); + cur = prev; + } + if (seen_kk != 0xffffffffu || !is_phi_scalar(cur, acc_phi[j])) + return false; + } + return true; } bool @@ -2144,12 +3696,14 @@ hk_nir_match_gemm_output(const nir_shader *shader, unsigned num_c_stores = 0; struct hk_nir_clamp_buffer read_bindings[4]; + uint32_t read_res_types[4] = {0}; uint32_t read_stride_off[4] = {0}; bool read_has_stride[4] = {0}; bool read_is_row_idx[4] = {0}; bool read_is_col_idx[4] = {0}; uint32_t read_bias_arm_off[4] = { UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX }; uint8_t read_bias_arm_mask[4] = {0}; + bool read_has_unguarded_bias[4] = {0}; bool read_bias_arm_inconsistent[4] = {0}; unsigned num_read_bindings = 0; @@ -2210,7 +3764,10 @@ hk_nir_match_gemm_output(const nir_shader *shader, if (slot == num_read_bindings) { if (num_read_bindings >= ARRAY_SIZE(read_bindings)) return false; - read_bindings[num_read_bindings++] = acc.binding; + read_bindings[num_read_bindings] = acc.binding; + read_res_types[num_read_bindings] = nir_intrinsic_resource_type( + nir_def_as_intrinsic(acc.descriptor->src[0].ssa)); + num_read_bindings++; } uint32_t s_off; if (!read_has_stride[slot] && @@ -2238,8 +3795,8 @@ hk_nir_match_gemm_output(const nir_shader *shader, } else { read_bias_arm_inconsistent[slot] = true; } - } else if (read_bias_arm_mask[slot]) { - read_bias_arm_inconsistent[slot] = true; + } else { + read_has_unguarded_bias[slot] = true; } } } else if (nir_deref_mode_is(ptr, nir_var_mem_push_const)) { @@ -2432,13 +3989,29 @@ hk_nir_match_gemm_output(const nir_shader *shader, if (num_read_bindings == 3 && !has_bias_buffer) return false; + const bool stores_split_by_bias_mode = has_bias_mode; + + /* Enforce bias_mode load consistency unconditionally on both split-store + * and non-split paths. */ + if (has_bias_buffer) { + if (read_bias_arm_inconsistent[bias_slot] || + (read_has_unguarded_bias[bias_slot] && read_bias_arm_mask[bias_slot])) + return false; + if (stores_split_by_bias_mode) { + if (read_has_unguarded_bias[bias_slot]) + return false; + if (read_bias_arm_mask[bias_slot] && + (read_bias_arm_off[bias_slot] != bias_mode_off || + (read_bias_arm_mask[bias_slot] & ~bias_mode_mask) != 0)) + return false; + } + } + /* If there is a bias buffer and stores themselves were not split per * bias_mode arm, either the bias loads are guarded by bias_mode arms * (with a fallthrough no-bias mode 2) or the bias load is unconditional * (indexed exclusively by row -> mode 0, or col -> mode 1). */ if (!has_bias_mode && has_bias_buffer) { - if (read_bias_arm_inconsistent[bias_slot]) - return false; if (read_bias_arm_mask[bias_slot]) { has_bias_mode = true; bias_mode_off = read_bias_arm_off[bias_slot]; @@ -2455,17 +4028,56 @@ hk_nir_match_gemm_output(const nir_shader *shader, if (has_bias_mode && (bias_mode_mask & 0x3u) && !has_bias_buffer) return false; + const uint32_t k_off = read_stride_off[a_slot]; + uint32_t max_push = MAX2(n_off, k_off) + 4; + if (is_guarded) + max_push = MAX2(max_push, m_off + 4); + if (has_bias_mode) + max_push = MAX2(max_push, bias_mode_off + 4); + + const uint32_t out_res_type = nir_intrinsic_resource_type( + nir_def_as_intrinsic(c_access[0].descriptor->src[0].ssa)); + const struct hk_nir_clamp_buffer bias_b = + has_bias_buffer ? read_bindings[bias_slot] : (struct hk_nir_clamp_buffer){0}; + + const bool cmat_ok = + !shader->info.float_controls_execution_mode && + ls[0] == 32 && ls[1] == 4 && ls[2] == 1 && + rows_per_thread == 8 && + desc_comps >= 3 && desc_comps <= 5 && + max_push <= 64 && + (n_off & 3) == 0 && (k_off & 3) == 0 && + (!is_guarded || (m_off & 3) == 0) && + (!has_bias_mode || (bias_mode_off & 3) == 0) && + ((out_binding.offset_B | read_bindings[a_slot].offset_B | + read_bindings[b_slot].offset_B | bias_b.offset_B) & 3) == 0 && + (is_guarded || (read_bindings[a_slot].offset_B & 15) == 0) && + certify_gemm_row_major_k_loop(impl, ls, c_stores, c_access, num_c_stores, + read_bindings[a_slot], read_bindings[b_slot], + has_bias_buffer, bias_b, + stores_split_by_bias_mode, has_bias_mode, + bias_mode_off, bias_mode_mask, is_guarded, + m_off, n_off, k_off, desc_comps); + *match = (struct hk_nir_gemm_output){ .output = out_binding, .reads = { read_bindings[a_slot], read_bindings[b_slot], - has_bias_buffer ? read_bindings[bias_slot] : (struct hk_nir_clamp_buffer){0}, + bias_b, }, .m_offset_B = is_guarded ? m_off : UINT32_MAX, .n_offset_B = n_off, - .k_offset_B = read_stride_off[a_slot], + .k_offset_B = k_off, .bias_mode_offset_B = has_bias_mode ? bias_mode_off : UINT32_MAX, + .push_bytes = max_push, + .out_res_type = out_res_type, + .read_res_type = { + read_res_types[a_slot], + read_res_types[b_slot], + has_bias_buffer ? read_res_types[bias_slot] : 0, + }, + .desc_comps = desc_comps, .local_size = { shader->info.workgroup_size[0], shader->info.workgroup_size[1], @@ -2477,6 +4089,7 @@ hk_nir_match_gemm_output(const nir_shader *shader, .has_bias_mode = has_bias_mode, .has_bias_buffer = has_bias_buffer, .is_guarded = is_guarded, + .cmat_valid = cmat_ok, }; return true; } @@ -2776,6 +4389,8 @@ static nir_def * dw_vec4_addr(nir_builder *b, struct hk_nir_clamp_buffer buf, uint32_t desc_comps, uint32_t res_type, nir_def *idx4, enum gl_access_qualifier access) { + if (buf.offset_B) + idx4 = nir_iadd_imm(b, idx4, buf.offset_B / 16); nir_def *resource = nir_vulkan_resource_index( b, desc_comps, 32, nir_imm_int(b, 0), .desc_type = nir_descriptor_type_storage_buffer, .resource_type = res_type, @@ -2810,6 +4425,142 @@ dw_fma4(nir_builder *b, nir_def *acc, nir_def *in_v, nir_def *wt_v, return sum; } +static void +emit_dw_kx_streamed(nir_builder *b, const struct hk_nir_depthwise_output *info, + nir_def *kw, nir_def *kh, unsigned stride_x, + nir_def *in_base0, nir_def *ch4, nir_def *c4, + nir_def *dy_step4, nir_def *wt_row4, + nir_def *zero_v4, nir_def **a0_out, nir_def **a1_out) +{ + const enum gl_access_qualifier read = ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER; + nir_def *zero_i = nir_imm_int(b, 0); + nir_def *sx_off = (stride_x == 2) ? nir_ishl_imm(b, c4, 1) : NULL; + + nir_loop *ky_lp = nir_push_loop(b); + ky_lp->control = nir_loop_control_dont_unroll; + nir_block *ky_pre = nir_cf_node_as_block(nir_cf_node_prev(&ky_lp->cf_node)); + nir_block *ky_hdr = nir_loop_first_block(ky_lp); + + nir_phi_instr *ky_phi = nir_phi_instr_create(b->shader); + nir_def_init(&ky_phi->instr, &ky_phi->def, 1, 32); + nir_phi_instr_add_src(ky_phi, ky_pre, zero_i); + + nir_phi_instr *r0_phi = nir_phi_instr_create(b->shader); + nir_def_init(&r0_phi->instr, &r0_phi->def, 4, 32); + nir_phi_instr_add_src(r0_phi, ky_pre, zero_v4); + + nir_phi_instr *r1_phi = nir_phi_instr_create(b->shader); + nir_def_init(&r1_phi->instr, &r1_phi->def, 4, 32); + nir_phi_instr_add_src(r1_phi, ky_pre, zero_v4); + + nir_phi_instr *in_phi = nir_phi_instr_create(b->shader); + nir_def_init(&in_phi->instr, &in_phi->def, 1, 32); + nir_phi_instr_add_src(in_phi, ky_pre, in_base0); + + nir_phi_instr *wt_phi = nir_phi_instr_create(b->shader); + nir_def_init(&wt_phi->instr, &wt_phi->def, 1, 32); + nir_phi_instr_add_src(wt_phi, ky_pre, ch4); + + nir_if *ky_done = nir_push_if(b, nir_ige(b, &ky_phi->def, kh)); + nir_jump(b, nir_jump_break); + nir_pop_if(b, ky_done); + + nir_def *iv_init = (stride_x == 1) + ? nir_load_global(b, 4, 32, + dw_vec4_addr(b, info->reads[0], info->desc_comps, info->read_res_type[0], + &in_phi->def, read), + .align_mul = 16, .access = read) + : zero_v4; + + nir_loop *kx_lp = nir_push_loop(b); + kx_lp->control = nir_loop_control_dont_unroll; + nir_block *kx_pre = nir_cf_node_as_block(nir_cf_node_prev(&kx_lp->cf_node)); + nir_block *kx_hdr = nir_loop_first_block(kx_lp); + + nir_phi_instr *kx_phi = nir_phi_instr_create(b->shader); + nir_def_init(&kx_phi->instr, &kx_phi->def, 1, 32); + nir_phi_instr_add_src(kx_phi, kx_pre, zero_i); + + nir_phi_instr *kr0_phi = nir_phi_instr_create(b->shader); + nir_def_init(&kr0_phi->instr, &kr0_phi->def, 4, 32); + nir_phi_instr_add_src(kr0_phi, kx_pre, &r0_phi->def); + + nir_phi_instr *kr1_phi = nir_phi_instr_create(b->shader); + nir_def_init(&kr1_phi->instr, &kr1_phi->def, 4, 32); + nir_phi_instr_add_src(kr1_phi, kx_pre, &r1_phi->def); + + nir_phi_instr *kin_phi = nir_phi_instr_create(b->shader); + nir_def_init(&kin_phi->instr, &kin_phi->def, 1, 32); + nir_phi_instr_add_src(kin_phi, kx_pre, &in_phi->def); + + nir_phi_instr *kwt_phi = nir_phi_instr_create(b->shader); + nir_def_init(&kwt_phi->instr, &kwt_phi->def, 1, 32); + nir_phi_instr_add_src(kwt_phi, kx_pre, &wt_phi->def); + + nir_phi_instr *kiv_phi = NULL; + if (stride_x == 1) { + kiv_phi = nir_phi_instr_create(b->shader); + nir_def_init(&kiv_phi->instr, &kiv_phi->def, 4, 32); + nir_phi_instr_add_src(kiv_phi, kx_pre, iv_init); + } + + nir_if *kx_done = nir_push_if(b, nir_ige(b, &kx_phi->def, kw)); + nir_jump(b, nir_jump_break); + nir_pop_if(b, kx_done); + + nir_def *wv = nir_load_global(b, 4, 32, + dw_vec4_addr(b, info->reads[1], info->desc_comps, info->read_res_type[1], + &kwt_phi->def, read), + .align_mul = 16, .access = read); + nir_def *iv0 = (stride_x == 1) + ? &kiv_phi->def + : nir_load_global(b, 4, 32, + dw_vec4_addr(b, info->reads[0], info->desc_comps, info->read_res_type[0], + &kin_phi->def, read), + .align_mul = 16, .access = read); + nir_def *nr0 = dw_fma4(b, &kr0_phi->def, iv0, wv, info); + nir_def *kin_nxt = nir_iadd(b, &kin_phi->def, c4); + nir_def *p1_in = (stride_x == 1) ? kin_nxt : nir_iadd(b, &kin_phi->def, sx_off); + nir_def *iv1 = nir_load_global(b, 4, 32, + dw_vec4_addr(b, info->reads[0], info->desc_comps, info->read_res_type[0], + p1_in, read), + .align_mul = 16, .access = read); + nir_def *nr1 = dw_fma4(b, &kr1_phi->def, iv1, wv, info); + + nir_block *kx_back = nir_loop_last_block(kx_lp); + nir_phi_instr_add_src(kx_phi, kx_back, nir_iadd_imm(b, &kx_phi->def, 1)); + nir_phi_instr_add_src(kr0_phi, kx_back, nr0); + nir_phi_instr_add_src(kr1_phi, kx_back, nr1); + nir_phi_instr_add_src(kin_phi, kx_back, kin_nxt); + nir_phi_instr_add_src(kwt_phi, kx_back, nir_iadd(b, &kwt_phi->def, c4)); + nir_instr_insert(nir_before_block(kx_hdr), &kx_phi->instr); + nir_instr_insert(nir_before_block(kx_hdr), &kr0_phi->instr); + nir_instr_insert(nir_before_block(kx_hdr), &kr1_phi->instr); + nir_instr_insert(nir_before_block(kx_hdr), &kin_phi->instr); + nir_instr_insert(nir_before_block(kx_hdr), &kwt_phi->instr); + if (stride_x == 1) { + nir_phi_instr_add_src(kiv_phi, kx_back, iv1); + nir_instr_insert(nir_before_block(kx_hdr), &kiv_phi->instr); + } + nir_pop_loop(b, kx_lp); + + nir_block *ky_back = nir_loop_last_block(ky_lp); + nir_phi_instr_add_src(ky_phi, ky_back, nir_iadd_imm(b, &ky_phi->def, 1)); + nir_phi_instr_add_src(r0_phi, ky_back, &kr0_phi->def); + nir_phi_instr_add_src(r1_phi, ky_back, &kr1_phi->def); + nir_phi_instr_add_src(in_phi, ky_back, nir_iadd(b, &in_phi->def, dy_step4)); + nir_phi_instr_add_src(wt_phi, ky_back, nir_iadd(b, &wt_phi->def, wt_row4)); + nir_instr_insert(nir_before_block(ky_hdr), &ky_phi->instr); + nir_instr_insert(nir_before_block(ky_hdr), &r0_phi->instr); + nir_instr_insert(nir_before_block(ky_hdr), &r1_phi->instr); + nir_instr_insert(nir_before_block(ky_hdr), &in_phi->instr); + nir_instr_insert(nir_before_block(ky_hdr), &wt_phi->instr); + nir_pop_loop(b, ky_lp); + + *a0_out = &r0_phi->def; + *a1_out = &r1_phi->def; +} + nir_shader * hk_nir_build_depthwise_vec4(const nir_shader *producer, const struct hk_nir_depthwise_output *info, @@ -2831,12 +4582,15 @@ hk_nir_build_depthwise_vec4(const nir_shader *producer, nir->info.name = ralloc_asprintf(nir, "%s_dw_vec4%s", producer->info.name ? producer->info.name : "cs", epilogue ? "_clamp" : ""); - nir->info.workgroup_size[0] = 32; - nir->info.workgroup_size[1] = 4; - nir->info.workgroup_size[2] = 1; + /* 3D grid (c4, ceil(out_w/2), out_h): 8 contiguous ch4 vec4s (128B full + * cache line) along X x 8 ox_pairs along Y for spatial L1 reuse. */ + nir->info.workgroup_size[0] = 8; + nir->info.workgroup_size[1] = 8; + nir->info.workgroup_size[2] = 2; nir->info.workgroup_size_variable = false; nir->info.num_ssbos = producer->info.num_ssbos; nir->info.float_controls_execution_mode = producer->info.float_controls_execution_mode; + nir->num_uniforms = info->push_bytes; nir_function *fn = nir_function_create(nir, "main"); fn->is_entrypoint = true; @@ -2847,8 +4601,9 @@ hk_nir_build_depthwise_vec4(const nir_shader *producer, const uint32_t pb = info->push_bytes; nir_def *gid = nir_load_global_invocation_id(&b, 32); - nir_def *gx = nir_channel(&b, gid, 0); - nir_def *gy = nir_channel(&b, gid, 1); + nir_def *ch4 = nir_channel(&b, gid, 0); + nir_def *ox_pair = nir_channel(&b, gid, 1); + nir_def *oy = nir_channel(&b, gid, 2); nir_def *in_w = dw_push(&b, info->input_width_offset_B, pb); nir_def *in_h = dw_push(&b, info->input_height_offset_B, pb); @@ -2868,206 +4623,244 @@ hk_nir_build_depthwise_vec4(const nir_shader *producer, ? dw_push(&b, info->has_bias_offset_B, pb) : NULL; - nir_def *c4 = nir_ishr_imm(&b, ch, 2); - nir_def *out_pairs = nir_ishr_imm(&b, nir_iadd_imm(&b, out_w, 1), 1); - nir_def *total_x4 = nir_imul(&b, out_pairs, c4); - nir_def *in_bounds = nir_iand(&b, nir_ilt(&b, gx, total_x4), nir_ilt(&b, gy, out_h)); + nir_def *c4 = nir_ushr_imm(&b, ch, 2); + nir_def *out_pairs = nir_ushr_imm(&b, nir_iadd_imm(&b, out_w, 1), 1); - nir_if *active = nir_push_if(&b, in_bounds); + nir_if *active = nir_push_if(&b, nir_iand(&b, nir_iand(&b, nir_ult(&b, ch4, c4), + nir_ult(&b, ox_pair, out_pairs)), + nir_ult(&b, oy, out_h))); { - nir_def *pair_idx = nir_udiv(&b, gx, c4); - nir_def *ch4 = nir_isub(&b, gx, nir_imul(&b, pair_idx, c4)); - nir_def *ox0 = nir_ishl_imm(&b, pair_idx, 1); - nir_def *ox1 = nir_iadd_imm(&b, ox0, 1); - nir_def *has_p1 = nir_ilt(&b, ox1, out_w); - - nir_def *ix0 = nir_iadd(&b, px, nir_imul(&b, ox0, sx)); - nir_def *ix1 = nir_iadd(&b, ix0, sx); - nir_def *iy0 = nir_iadd(&b, py, nir_imul(&b, gy, sy)); - nir_def *ix_max = nir_iadd(&b, ix1, nir_imul(&b, nir_iadd_imm(&b, kw, -1), dx)); - nir_def *iy_max = nir_iadd(&b, iy0, nir_imul(&b, nir_iadd_imm(&b, kh, -1), dy)); - nir_def *interior = nir_iand(&b, - nir_iand(&b, nir_ige_imm(&b, ix0, 0), nir_ilt(&b, ix_max, in_w)), - nir_iand(&b, nir_ige_imm(&b, iy0, 0), nir_ilt(&b, iy_max, in_h))); - interior = nir_iand(&b, interior, has_p1); - - nir_def *zero_i = nir_imm_int(&b, 0); - nir_def *zero4 = nir_imm_vec4(&b, 0.0f, 0.0f, 0.0f, 0.0f); - nir_def *kw_c4 = nir_imul(&b, kw, c4); - nir_def *iw_c4 = nir_imul(&b, in_w, c4); - nir_def *dx_c4 = nir_imul(&b, dx, c4); - nir_def *sx_c4 = nir_imul(&b, sx, c4); - nir_def *dy_iw_c4 = nir_imul(&b, dy, iw_c4); + nir_def *km1_dx = nir_imul(&b, nir_iadd_imm(&b, kw, -1), dx); + nir_def *km1_dy = nir_imul(&b, nir_iadd_imm(&b, kh, -1), dy); + nir_def *row_stride4 = nir_imul(&b, in_w, c4); + nir_def *wt_row4 = nir_imul(&b, kw, c4); + nir_def *dx_step4 = nir_imul(&b, dx, c4); + nir_def *dy_step4 = nir_imul(&b, dy, row_stride4); + nir_def *sx_step4 = nir_imul(&b, sx, c4); + + nir_def *ox0_chk = nir_ishl_imm(&b, ox_pair, 1); + nir_def *ix0_chk = nir_iadd(&b, nir_imul(&b, ox0_chk, sx), px); + nir_def *iy0_chk = nir_iadd(&b, nir_imul(&b, oy, sy), py); + nir_def *in_y_ok = nir_iand(&b, nir_ige_imm(&b, iy0_chk, 0), + nir_ilt(&b, nir_iadd(&b, iy0_chk, km1_dy), in_h)); + nir_def *in_x_ok = nir_iand(&b, nir_iand(&b, nir_ult(&b, nir_iadd_imm(&b, ox0_chk, 1), out_w), + nir_ige_imm(&b, ix0_chk, 0)), + nir_ilt(&b, nir_iadd(&b, nir_iadd(&b, ix0_chk, sx), km1_dx), in_w)); + nir_def *is_interior2 = nir_iand(&b, in_y_ok, in_x_ok); + + nir_def *zero_f = nir_imm_float(&b, 0.0f); + nir_def *zero_v4 = nir_vec4(&b, zero_f, zero_f, zero_f, zero_f); nir_def *acc0_int = NULL, *acc1_int = NULL; nir_def *acc0_brd = NULL, *acc1_brd = NULL; - - nir_if *int_if = nir_push_if(&b, interior); + nir_if *int_if = nir_push_if(&b, is_interior2); { - nir_def *base_in0 = nir_iadd(&b, - nir_imul(&b, nir_iadd(&b, nir_imul(&b, iy0, in_w), ix0), c4), ch4); - nir_loop *ylp = nir_push_loop(&b); - nir_block *pre_y = nir_cf_node_as_block(nir_cf_node_prev(&ylp->cf_node)); - nir_block *yhdr = nir_loop_first_block(ylp); + nir_def *in_base0 = + nir_iadd(&b, nir_iadd(&b, nir_imul(&b, iy0_chk, row_stride4), + nir_imul(&b, ix0_chk, c4)), ch4); + nir_def *is_s1_d1 = nir_iand(&b, nir_ieq_imm(&b, dx, 1), nir_ieq_imm(&b, sx, 1)); + nir_def *a0_s1 = NULL, *a1_s1 = NULL; + nir_def *a0_g = NULL, *a1_g = NULL; + nir_if *s1_if = nir_push_if(&b, is_s1_d1); + { + emit_dw_kx_streamed(&b, info, kw, kh, 1, in_base0, ch4, c4, dy_step4, wt_row4, + zero_v4, &a0_s1, &a1_s1); + } + nir_push_else(&b, s1_if); + { + nir_def *is_s2_d1 = nir_iand(&b, nir_ieq_imm(&b, dx, 1), nir_ieq_imm(&b, sx, 2)); + nir_def *a0_s2 = NULL, *a1_s2 = NULL; + nir_def *a0_gen = NULL, *a1_gen = NULL; + nir_if *s2_if = nir_push_if(&b, is_s2_d1); + { + emit_dw_kx_streamed(&b, info, kw, kh, 2, in_base0, ch4, c4, dy_step4, wt_row4, + zero_v4, &a0_s2, &a1_s2); + } + nir_push_else(&b, s2_if); + { + nir_def *zero_i = nir_imm_int(&b, 0); + nir_loop *oy_lp = nir_push_loop(&b); + oy_lp->control = nir_loop_control_dont_unroll; + nir_block *oy_pre = nir_cf_node_as_block(nir_cf_node_prev(&oy_lp->cf_node)); + nir_block *oy_hdr = nir_loop_first_block(oy_lp); - nir_phi_instr *ky_phi = nir_phi_instr_create(nir); - nir_def_init(&ky_phi->instr, &ky_phi->def, 1, 32); - nir_phi_instr_add_src(ky_phi, pre_y, zero_i); + nir_phi_instr *ky_phi = nir_phi_instr_create(b.shader); + nir_def_init(&ky_phi->instr, &ky_phi->def, 1, 32); + nir_phi_instr_add_src(ky_phi, oy_pre, zero_i); - nir_phi_instr *in_y_phi = nir_phi_instr_create(nir); - nir_def_init(&in_y_phi->instr, &in_y_phi->def, 1, 32); - nir_phi_instr_add_src(in_y_phi, pre_y, base_in0); + nir_phi_instr *oy_a0_phi = nir_phi_instr_create(b.shader); + nir_def_init(&oy_a0_phi->instr, &oy_a0_phi->def, 4, 32); + nir_phi_instr_add_src(oy_a0_phi, oy_pre, zero_v4); - nir_phi_instr *wt_y_phi = nir_phi_instr_create(nir); - nir_def_init(&wt_y_phi->instr, &wt_y_phi->def, 1, 32); - nir_phi_instr_add_src(wt_y_phi, pre_y, ch4); + nir_phi_instr *oy_a1_phi = nir_phi_instr_create(b.shader); + nir_def_init(&oy_a1_phi->instr, &oy_a1_phi->def, 4, 32); + nir_phi_instr_add_src(oy_a1_phi, oy_pre, zero_v4); - nir_phi_instr *a0_y_phi = nir_phi_instr_create(nir); - nir_def_init(&a0_y_phi->instr, &a0_y_phi->def, 4, 32); - nir_phi_instr_add_src(a0_y_phi, pre_y, zero4); + nir_phi_instr *oy_in_phi = nir_phi_instr_create(b.shader); + nir_def_init(&oy_in_phi->instr, &oy_in_phi->def, 1, 32); + nir_phi_instr_add_src(oy_in_phi, oy_pre, in_base0); - nir_phi_instr *a1_y_phi = nir_phi_instr_create(nir); - nir_def_init(&a1_y_phi->instr, &a1_y_phi->def, 4, 32); - nir_phi_instr_add_src(a1_y_phi, pre_y, zero4); + nir_phi_instr *oy_wt_phi = nir_phi_instr_create(b.shader); + nir_def_init(&oy_wt_phi->instr, &oy_wt_phi->def, 1, 32); + nir_phi_instr_add_src(oy_wt_phi, oy_pre, ch4); - nir_if *ybrk = nir_push_if(&b, nir_ige(&b, &ky_phi->def, kh)); - nir_jump(&b, nir_jump_break); - nir_pop_if(&b, ybrk); + nir_if *oy_done = nir_push_if(&b, nir_ige(&b, &ky_phi->def, kh)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, oy_done); - nir_loop *xlp = nir_push_loop(&b); - nir_block *pre_x = nir_cf_node_as_block(nir_cf_node_prev(&xlp->cf_node)); - nir_block *xhdr = nir_loop_first_block(xlp); + nir_loop *ix_lp = nir_push_loop(&b); + ix_lp->control = nir_loop_control_dont_unroll; + nir_block *ix_pre = nir_cf_node_as_block(nir_cf_node_prev(&ix_lp->cf_node)); + nir_block *ix_hdr = nir_loop_first_block(ix_lp); - nir_phi_instr *kx_phi = nir_phi_instr_create(nir); - nir_def_init(&kx_phi->instr, &kx_phi->def, 1, 32); - nir_phi_instr_add_src(kx_phi, pre_x, zero_i); + nir_phi_instr *kx_phi = nir_phi_instr_create(b.shader); + nir_def_init(&kx_phi->instr, &kx_phi->def, 1, 32); + nir_phi_instr_add_src(kx_phi, ix_pre, zero_i); - nir_phi_instr *in_x_phi = nir_phi_instr_create(nir); - nir_def_init(&in_x_phi->instr, &in_x_phi->def, 1, 32); - nir_phi_instr_add_src(in_x_phi, pre_x, &in_y_phi->def); + nir_phi_instr *ix_a0_phi = nir_phi_instr_create(b.shader); + nir_def_init(&ix_a0_phi->instr, &ix_a0_phi->def, 4, 32); + nir_phi_instr_add_src(ix_a0_phi, ix_pre, &oy_a0_phi->def); - nir_phi_instr *wt_x_phi = nir_phi_instr_create(nir); - nir_def_init(&wt_x_phi->instr, &wt_x_phi->def, 1, 32); - nir_phi_instr_add_src(wt_x_phi, pre_x, &wt_y_phi->def); + nir_phi_instr *ix_a1_phi = nir_phi_instr_create(b.shader); + nir_def_init(&ix_a1_phi->instr, &ix_a1_phi->def, 4, 32); + nir_phi_instr_add_src(ix_a1_phi, ix_pre, &oy_a1_phi->def); - nir_phi_instr *a0_x_phi = nir_phi_instr_create(nir); - nir_def_init(&a0_x_phi->instr, &a0_x_phi->def, 4, 32); - nir_phi_instr_add_src(a0_x_phi, pre_x, &a0_y_phi->def); + nir_phi_instr *ix_in_phi = nir_phi_instr_create(b.shader); + nir_def_init(&ix_in_phi->instr, &ix_in_phi->def, 1, 32); + nir_phi_instr_add_src(ix_in_phi, ix_pre, &oy_in_phi->def); - nir_phi_instr *a1_x_phi = nir_phi_instr_create(nir); - nir_def_init(&a1_x_phi->instr, &a1_x_phi->def, 4, 32); - nir_phi_instr_add_src(a1_x_phi, pre_x, &a1_y_phi->def); + nir_phi_instr *ix_wt_phi = nir_phi_instr_create(b.shader); + nir_def_init(&ix_wt_phi->instr, &ix_wt_phi->def, 1, 32); + nir_phi_instr_add_src(ix_wt_phi, ix_pre, &oy_wt_phi->def); - nir_if *xbrk = nir_push_if(&b, nir_ige(&b, &kx_phi->def, kw)); - nir_jump(&b, nir_jump_break); - nir_pop_if(&b, xbrk); - - nir_def *wa = dw_vec4_addr(&b, info->reads[1], info->desc_comps, - info->read_res_type[1], &wt_x_phi->def, read); - nir_def *wv = nir_load_global(&b, 4, 32, wa, .align_mul = 16, .access = read); - - nir_def *ia0 = dw_vec4_addr(&b, info->reads[0], info->desc_comps, - info->read_res_type[0], &in_x_phi->def, read); - nir_def *iv0 = nir_load_global(&b, 4, 32, ia0, .align_mul = 16, .access = read); - - nir_def *ia1 = dw_vec4_addr(&b, info->reads[0], info->desc_comps, - info->read_res_type[0], - nir_iadd(&b, &in_x_phi->def, sx_c4), read); - nir_def *iv1 = nir_load_global(&b, 4, 32, ia1, .align_mul = 16, .access = read); - - nir_def *na0 = dw_fma4(&b, &a0_x_phi->def, iv0, wv, info); - nir_def *na1 = dw_fma4(&b, &a1_x_phi->def, iv1, wv, info); - - nir_block *xback = nir_loop_last_block(xlp); - nir_phi_instr_add_src(kx_phi, xback, nir_iadd_imm(&b, &kx_phi->def, 1)); - nir_phi_instr_add_src(in_x_phi, xback, nir_iadd(&b, &in_x_phi->def, dx_c4)); - nir_phi_instr_add_src(wt_x_phi, xback, nir_iadd(&b, &wt_x_phi->def, c4)); - nir_phi_instr_add_src(a0_x_phi, xback, na0); - nir_phi_instr_add_src(a1_x_phi, xback, na1); - nir_instr_insert(nir_before_block(xhdr), &kx_phi->instr); - nir_instr_insert(nir_before_block(xhdr), &in_x_phi->instr); - nir_instr_insert(nir_before_block(xhdr), &wt_x_phi->instr); - nir_instr_insert(nir_before_block(xhdr), &a0_x_phi->instr); - nir_instr_insert(nir_before_block(xhdr), &a1_x_phi->instr); - nir_pop_loop(&b, xlp); - - nir_block *yback = nir_loop_last_block(ylp); - nir_phi_instr_add_src(ky_phi, yback, nir_iadd_imm(&b, &ky_phi->def, 1)); - nir_phi_instr_add_src(in_y_phi, yback, nir_iadd(&b, &in_y_phi->def, dy_iw_c4)); - nir_phi_instr_add_src(wt_y_phi, yback, nir_iadd(&b, &wt_y_phi->def, kw_c4)); - nir_phi_instr_add_src(a0_y_phi, yback, &a0_x_phi->def); - nir_phi_instr_add_src(a1_y_phi, yback, &a1_x_phi->def); - nir_instr_insert(nir_before_block(yhdr), &ky_phi->instr); - nir_instr_insert(nir_before_block(yhdr), &in_y_phi->instr); - nir_instr_insert(nir_before_block(yhdr), &wt_y_phi->instr); - nir_instr_insert(nir_before_block(yhdr), &a0_y_phi->instr); - nir_instr_insert(nir_before_block(yhdr), &a1_y_phi->instr); - nir_pop_loop(&b, ylp); - - acc0_int = &a0_y_phi->def; - acc1_int = &a1_y_phi->def; + nir_if *ix_done = nir_push_if(&b, nir_ige(&b, &kx_phi->def, kw)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, ix_done); + + nir_def *wv = nir_load_global(&b, 4, 32, + dw_vec4_addr(&b, info->reads[1], info->desc_comps, info->read_res_type[1], + &ix_wt_phi->def, read), + .align_mul = 16, .access = read); + nir_def *iv0 = nir_load_global(&b, 4, 32, + dw_vec4_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], + &ix_in_phi->def, read), + .align_mul = 16, .access = read); + nir_def *a0_next = dw_fma4(&b, &ix_a0_phi->def, iv0, wv, info); + nir_def *iv1 = nir_load_global(&b, 4, 32, + dw_vec4_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], + nir_iadd(&b, &ix_in_phi->def, sx_step4), read), + .align_mul = 16, .access = read); + nir_def *a1_next = dw_fma4(&b, &ix_a1_phi->def, iv1, wv, info); + + nir_block *ix_back = nir_loop_last_block(ix_lp); + nir_phi_instr_add_src(kx_phi, ix_back, nir_iadd_imm(&b, &kx_phi->def, 1)); + nir_phi_instr_add_src(ix_a0_phi, ix_back, a0_next); + nir_phi_instr_add_src(ix_a1_phi, ix_back, a1_next); + nir_phi_instr_add_src(ix_in_phi, ix_back, nir_iadd(&b, &ix_in_phi->def, dx_step4)); + nir_phi_instr_add_src(ix_wt_phi, ix_back, nir_iadd(&b, &ix_wt_phi->def, c4)); + nir_instr_insert(nir_before_block(ix_hdr), &kx_phi->instr); + nir_instr_insert(nir_before_block(ix_hdr), &ix_a0_phi->instr); + nir_instr_insert(nir_before_block(ix_hdr), &ix_a1_phi->instr); + nir_instr_insert(nir_before_block(ix_hdr), &ix_in_phi->instr); + nir_instr_insert(nir_before_block(ix_hdr), &ix_wt_phi->instr); + nir_pop_loop(&b, ix_lp); + + nir_block *oy_back = nir_loop_last_block(oy_lp); + nir_phi_instr_add_src(ky_phi, oy_back, nir_iadd_imm(&b, &ky_phi->def, 1)); + nir_phi_instr_add_src(oy_a0_phi, oy_back, &ix_a0_phi->def); + nir_phi_instr_add_src(oy_a1_phi, oy_back, &ix_a1_phi->def); + nir_phi_instr_add_src(oy_in_phi, oy_back, nir_iadd(&b, &oy_in_phi->def, dy_step4)); + nir_phi_instr_add_src(oy_wt_phi, oy_back, nir_iadd(&b, &oy_wt_phi->def, wt_row4)); + nir_instr_insert(nir_before_block(oy_hdr), &ky_phi->instr); + nir_instr_insert(nir_before_block(oy_hdr), &oy_a0_phi->instr); + nir_instr_insert(nir_before_block(oy_hdr), &oy_a1_phi->instr); + nir_instr_insert(nir_before_block(oy_hdr), &oy_in_phi->instr); + nir_instr_insert(nir_before_block(oy_hdr), &oy_wt_phi->instr); + nir_pop_loop(&b, oy_lp); + a0_gen = &oy_a0_phi->def; + a1_gen = &oy_a1_phi->def; + } + nir_pop_if(&b, s2_if); + a0_g = nir_if_phi(&b, a0_s2, a0_gen); + a1_g = nir_if_phi(&b, a1_s2, a1_gen); + } + nir_pop_if(&b, s1_if); + acc0_int = nir_if_phi(&b, a0_s1, a0_g); + acc1_int = nir_if_phi(&b, a1_s1, a1_g); } nir_push_else(&b, int_if); { + /* Recompute border coordinates inside the border branch so they are + * not kept live in registers across the hot interior loop. */ + nir_def *ox0_b = nir_ishl_imm(&b, ox_pair, 1); + nir_def *has_p1_b = nir_ult(&b, nir_iadd_imm(&b, ox0_b, 1), out_w); + nir_def *ix0_b = nir_iadd(&b, nir_imul(&b, ox0_b, sx), px); + nir_def *ix1_b = nir_iadd(&b, ix0_b, sx); + nir_def *iy0_b = nir_iadd(&b, nir_imul(&b, oy, sy), py); + + nir_def *zero_i = nir_imm_int(&b, 0); nir_loop *oy_lp = nir_push_loop(&b); - nir_block *pre_oy = nir_cf_node_as_block(nir_cf_node_prev(&oy_lp->cf_node)); + oy_lp->control = nir_loop_control_dont_unroll; + nir_block *oy_pre = nir_cf_node_as_block(nir_cf_node_prev(&oy_lp->cf_node)); nir_block *oy_hdr = nir_loop_first_block(oy_lp); - nir_phi_instr *ky_phi = nir_phi_instr_create(nir); + nir_phi_instr *ky_phi = nir_phi_instr_create(b.shader); nir_def_init(&ky_phi->instr, &ky_phi->def, 1, 32); - nir_phi_instr_add_src(ky_phi, pre_oy, zero_i); + nir_phi_instr_add_src(ky_phi, oy_pre, zero_i); - nir_phi_instr *oy_a0_phi = nir_phi_instr_create(nir); + nir_phi_instr *oy_a0_phi = nir_phi_instr_create(b.shader); nir_def_init(&oy_a0_phi->instr, &oy_a0_phi->def, 4, 32); - nir_phi_instr_add_src(oy_a0_phi, pre_oy, zero4); + nir_phi_instr_add_src(oy_a0_phi, oy_pre, zero_v4); - nir_phi_instr *oy_a1_phi = nir_phi_instr_create(nir); + nir_phi_instr *oy_a1_phi = nir_phi_instr_create(b.shader); nir_def_init(&oy_a1_phi->instr, &oy_a1_phi->def, 4, 32); - nir_phi_instr_add_src(oy_a1_phi, pre_oy, zero4); + nir_phi_instr_add_src(oy_a1_phi, oy_pre, zero_v4); - nir_if *ybrk = nir_push_if(&b, nir_ige(&b, &ky_phi->def, kh)); + nir_if *oy_done = nir_push_if(&b, nir_ige(&b, &ky_phi->def, kh)); nir_jump(&b, nir_jump_break); - nir_pop_if(&b, ybrk); + nir_pop_if(&b, oy_done); - nir_def *iy = nir_iadd(&b, iy0, nir_imul(&b, &ky_phi->def, dy)); - nir_def *iy_ok = nir_ult(&b, iy, in_h); + nir_def *iy = nir_iadd(&b, iy0_b, nir_imul(&b, dy, &ky_phi->def)); nir_def *y_a0 = NULL, *y_a1 = NULL; - nir_if *y_ok = nir_push_if(&b, iy_ok); + nir_if *y_ok = nir_push_if(&b, nir_ult(&b, iy, in_h)); { - nir_def *in_row4 = nir_iadd(&b, nir_imul(&b, iy, iw_c4), ch4); - nir_def *wt_row4 = nir_iadd(&b, nir_imul(&b, &ky_phi->def, kw_c4), ch4); + nir_def *in_row4 = nir_iadd(&b, nir_imul(&b, iy, row_stride4), ch4); + nir_def *wt_y4 = nir_iadd(&b, nir_imul(&b, &ky_phi->def, wt_row4), ch4); + nir_loop *ix_lp = nir_push_loop(&b); - nir_block *pre_ix = nir_cf_node_as_block(nir_cf_node_prev(&ix_lp->cf_node)); + ix_lp->control = nir_loop_control_dont_unroll; + nir_block *ix_pre = nir_cf_node_as_block(nir_cf_node_prev(&ix_lp->cf_node)); nir_block *ix_hdr = nir_loop_first_block(ix_lp); - nir_phi_instr *kx_phi = nir_phi_instr_create(nir); + nir_phi_instr *kx_phi = nir_phi_instr_create(b.shader); nir_def_init(&kx_phi->instr, &kx_phi->def, 1, 32); - nir_phi_instr_add_src(kx_phi, pre_ix, zero_i); + nir_phi_instr_add_src(kx_phi, ix_pre, zero_i); - nir_phi_instr *ix_a0_phi = nir_phi_instr_create(nir); + nir_phi_instr *ix_a0_phi = nir_phi_instr_create(b.shader); nir_def_init(&ix_a0_phi->instr, &ix_a0_phi->def, 4, 32); - nir_phi_instr_add_src(ix_a0_phi, pre_ix, &oy_a0_phi->def); + nir_phi_instr_add_src(ix_a0_phi, ix_pre, &oy_a0_phi->def); - nir_phi_instr *ix_a1_phi = nir_phi_instr_create(nir); + nir_phi_instr *ix_a1_phi = nir_phi_instr_create(b.shader); nir_def_init(&ix_a1_phi->instr, &ix_a1_phi->def, 4, 32); - nir_phi_instr_add_src(ix_a1_phi, pre_ix, &oy_a1_phi->def); + nir_phi_instr_add_src(ix_a1_phi, ix_pre, &oy_a1_phi->def); - nir_if *xbrk = nir_push_if(&b, nir_ige(&b, &kx_phi->def, kw)); + nir_if *ix_done = nir_push_if(&b, nir_ige(&b, &kx_phi->def, kw)); nir_jump(&b, nir_jump_break); - nir_pop_if(&b, xbrk); + nir_pop_if(&b, ix_done); - nir_def *kdx = nir_imul(&b, &kx_phi->def, dx); - nir_def *ix_a = nir_iadd(&b, ix0, kdx); - nir_def *ix_b = nir_iadd(&b, ix1, kdx); + nir_def *kdx = nir_imul(&b, dx, &kx_phi->def); + nir_def *ix_a = nir_iadd(&b, ix0_b, kdx); + nir_def *ix_b = nir_iadd(&b, ix1_b, kdx); nir_def *ok0 = nir_ult(&b, ix_a, in_w); - nir_def *ok1 = nir_iand(&b, has_p1, nir_ult(&b, ix_b, in_w)); + nir_def *ok1 = nir_iand(&b, has_p1_b, nir_ult(&b, ix_b, in_w)); nir_def *any_a0 = NULL, *any_a1 = NULL; nir_if *any_ok = nir_push_if(&b, nir_ior(&b, ok0, ok1)); { - nir_def *wt_idx4 = nir_iadd(&b, wt_row4, nir_imul(&b, &kx_phi->def, c4)); + nir_def *wt_idx4 = nir_iadd(&b, wt_y4, nir_imul(&b, &kx_phi->def, c4)); nir_def *wv = nir_load_global(&b, 4, 32, - dw_vec4_addr(&b, info->reads[1], info->desc_comps, info->read_res_type[1], wt_idx4, read), + dw_vec4_addr(&b, info->reads[1], info->desc_comps, info->read_res_type[1], + wt_idx4, read), .align_mul = 16, .access = read); nir_def *hit0 = NULL; @@ -3075,7 +4868,8 @@ hk_nir_build_depthwise_vec4(const nir_shader *producer, { nir_def *in_idx4 = nir_iadd(&b, in_row4, nir_imul(&b, ix_a, c4)); nir_def *iv0 = nir_load_global(&b, 4, 32, - dw_vec4_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], in_idx4, read), + dw_vec4_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], + in_idx4, read), .align_mul = 16, .access = read); hit0 = dw_fma4(&b, &ix_a0_phi->def, iv0, wv, info); } @@ -3088,7 +4882,8 @@ hk_nir_build_depthwise_vec4(const nir_shader *producer, { nir_def *in_idx4 = nir_iadd(&b, in_row4, nir_imul(&b, ix_b, c4)); nir_def *iv1 = nir_load_global(&b, 4, 32, - dw_vec4_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], in_idx4, read), + dw_vec4_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], + in_idx4, read), .align_mul = 16, .access = read); hit1 = dw_fma4(&b, &ix_a1_phi->def, iv1, wv, info); } @@ -3132,8 +4927,7 @@ hk_nir_build_depthwise_vec4(const nir_shader *producer, nir_def *acc0 = nir_if_phi(&b, acc0_int, acc0_brd); nir_def *acc1 = nir_if_phi(&b, acc1_int, acc1_brd); - nir_def *val0 = acc0; - nir_def *val1 = acc1; + nir_def *val0 = acc0, *val1 = acc1; if (info->has_bias_buffer) { if (has_bias) { nir_def *b_a0 = NULL, *b_a1 = NULL; @@ -3167,8 +4961,10 @@ hk_nir_build_depthwise_vec4(const nir_shader *producer, val1 = apply_clamp_epilogue(&b, val1, epilogue); } + nir_def *ox0 = nir_ishl_imm(&b, ox_pair, 1); + nir_def *has_p1 = nir_ult(&b, nir_iadd_imm(&b, ox0, 1), out_w); nir_def *out_idx0 = - nir_iadd(&b, nir_imul(&b, nir_iadd(&b, nir_imul(&b, gy, out_w), ox0), c4), ch4); + nir_iadd(&b, nir_imul(&b, nir_iadd(&b, nir_imul(&b, oy, out_w), ox0), c4), ch4); nir_def *oa0 = dw_vec4_addr(&b, info->output, info->desc_comps, info->out_res_type, out_idx0, ACCESS_NON_READABLE); nir_store_global(&b, val0, oa0, .align_mul = 16, .write_mask = 0xf, @@ -3190,3 +4986,855 @@ hk_nir_build_depthwise_vec4(const nir_shader *producer, nir_shader_gather_info(nir, impl); return nir; } + +static nir_def * +gemm_f32_addr(nir_builder *b, struct hk_nir_clamp_buffer buf, uint32_t desc_comps, + uint32_t res_type, nir_def *idx, enum gl_access_qualifier access) +{ + if (buf.offset_B) + idx = nir_iadd_imm(b, idx, buf.offset_B / 4); + nir_def *resource = nir_vulkan_resource_index( + b, desc_comps, 32, nir_imm_int(b, 0), + .desc_type = nir_descriptor_type_storage_buffer, .resource_type = res_type, + .desc_set = buf.set, .binding = buf.binding); + nir_def *descriptor = nir_load_vulkan_descriptor( + b, desc_comps, 32, resource, .desc_type = nir_descriptor_type_storage_buffer); + const glsl_type *array_type = glsl_array_type(glsl_float_type(), 0, 4); + nir_deref_instr *array = nir_build_deref_cast_with_alignment( + b, descriptor, nir_var_mem_ssbo, array_type, 0, 4, 0); + nir_deref_instr *element = nir_build_deref_array(b, array, idx); + element->arr.in_bounds = true; + return nir_deref_buffer_address(b, 1, 64, &element->def, .access = access); +} + +static nir_def * +gemm_vec4_addr(nir_builder *b, struct hk_nir_clamp_buffer buf, uint32_t desc_comps, + uint32_t res_type, nir_def *idx4, enum gl_access_qualifier access) +{ + if (buf.offset_B) + idx4 = nir_iadd_imm(b, idx4, buf.offset_B / 16); + nir_def *resource = nir_vulkan_resource_index( + b, desc_comps, 32, nir_imm_int(b, 0), + .desc_type = nir_descriptor_type_storage_buffer, .resource_type = res_type, + .desc_set = buf.set, .binding = buf.binding); + nir_def *descriptor = nir_load_vulkan_descriptor( + b, desc_comps, 32, resource, .desc_type = nir_descriptor_type_storage_buffer); + const glsl_type *array_type = glsl_array_type(glsl_vec4_type(), 0, 16); + nir_deref_instr *array = nir_build_deref_cast_with_alignment( + b, descriptor, nir_var_mem_ssbo, array_type, 0, 16, 0); + nir_deref_instr *element = nir_build_deref_array(b, array, idx4); + element->arr.in_bounds = true; + return nir_deref_buffer_address(b, 1, 64, &element->def, .access = access); +} + +static void +emit_gemm_cmat_store_fast(nir_builder *b, const struct hk_nir_gemm_output *info, + const struct hk_nir_clamp_epilogue *epilogue, + nir_def *n, nir_def *bias_mode, + nir_def *c_row0, nir_def *c_row1, nir_def *c_col0, + nir_def *acc0[4], nir_def *acc1[4]) +{ + const enum gl_access_qualifier read = ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER; + nir_def *c_idx0 = nir_iadd(b, nir_imul(b, c_row0, n), c_col0); + nir_def *c_idx1 = nir_iadd(b, nir_imul(b, c_row1, n), c_col0); + + const bool dyn_row = info->has_bias_buffer && info->has_bias_mode && + (info->bias_mode_mask & (1u << 0)); + const bool dyn_col = info->has_bias_buffer && info->has_bias_mode && + (info->bias_mode_mask & (1u << 1)); + const bool fixed_row = info->has_bias_buffer && !info->has_bias_mode && + info->bias_mode_mask == (1u << 0); + const bool fixed_col = info->has_bias_buffer && !info->has_bias_mode && + info->bias_mode_mask == (1u << 1); + + nir_def *zero_f = nir_imm_float(b, 0.0f); + nir_def *is_row_bias = dyn_row ? nir_ieq_imm(b, bias_mode, 0) : NULL; + nir_def *is_col_bias = dyn_col ? nir_ieq_imm(b, bias_mode, 1) : NULL; + + nir_def *rb0_v2 = NULL, *rb1_v2 = NULL; + if (fixed_row) { + nir_def *rb0 = nir_load_global(b, 1, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, info->read_res_type[2], + c_row0, read), + .align_mul = 4, .access = read); + nir_def *rb1 = nir_load_global(b, 1, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, info->read_res_type[2], + c_row1, read), + .align_mul = 4, .access = read); + rb0_v2 = nir_vec2(b, rb0, rb0); + rb1_v2 = nir_vec2(b, rb1, rb1); + } else if (dyn_row) { + nir_def *rb0 = NULL, *rb1 = NULL; + nir_if *rb_if = nir_push_if(b, is_row_bias); + { + rb0 = nir_load_global(b, 1, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, info->read_res_type[2], + c_row0, read), + .align_mul = 4, .access = read); + rb1 = nir_load_global(b, 1, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, info->read_res_type[2], + c_row1, read), + .align_mul = 4, .access = read); + } + nir_push_else(b, rb_if); + nir_pop_if(b, rb_if); + rb0 = nir_if_phi(b, rb0, zero_f); + rb1 = nir_if_phi(b, rb1, zero_f); + rb0_v2 = nir_vec2(b, rb0, rb0); + rb1_v2 = nir_vec2(b, rb1, rb1); + } + + for (unsigned t = 0; t < 4; ++t) { + nir_def *v0 = acc0[t]; + nir_def *v1 = acc1[t]; + if (fixed_row) { + v0 = nir_fadd(b, v0, rb0_v2); + v1 = nir_fadd(b, v1, rb1_v2); + } else if (fixed_col) { + nir_def *cb = nir_load_global(b, 2, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, info->read_res_type[2], + nir_iadd_imm(b, c_col0, 8 * t), read), + .align_mul = 4, .access = read); + v0 = nir_fadd(b, v0, cb); + v1 = nir_fadd(b, v1, cb); + } else if (dyn_row || dyn_col) { + if (dyn_row) { + nir_def *v0_rb = NULL, *v1_rb = NULL; + nir_def *v0_nc = NULL, *v1_nc = NULL; + nir_if *m0_if = nir_push_if(b, is_row_bias); + { + v0_rb = nir_fadd(b, v0, rb0_v2); + v1_rb = nir_fadd(b, v1, rb1_v2); + } + nir_push_else(b, m0_if); + { + if (dyn_col) { + nir_def *v0_cb = NULL, *v1_cb = NULL; + nir_if *m1_if = nir_push_if(b, is_col_bias); + { + nir_def *cb = nir_load_global(b, 2, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, + info->read_res_type[2], + nir_iadd_imm(b, c_col0, 8 * t), read), + .align_mul = 4, .access = read); + v0_cb = nir_fadd(b, v0, cb); + v1_cb = nir_fadd(b, v1, cb); + } + nir_push_else(b, m1_if); + nir_pop_if(b, m1_if); + v0_nc = nir_if_phi(b, v0_cb, v0); + v1_nc = nir_if_phi(b, v1_cb, v1); + } else { + v0_nc = v0; + v1_nc = v1; + } + } + nir_pop_if(b, m0_if); + v0 = nir_if_phi(b, v0_rb, v0_nc); + v1 = nir_if_phi(b, v1_rb, v1_nc); + } else { + nir_def *v0_cb = NULL, *v1_cb = NULL; + nir_if *m1_if = nir_push_if(b, is_col_bias); + { + nir_def *cb = nir_load_global(b, 2, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, + info->read_res_type[2], + nir_iadd_imm(b, c_col0, 8 * t), read), + .align_mul = 4, .access = read); + v0_cb = nir_fadd(b, v0, cb); + v1_cb = nir_fadd(b, v1, cb); + } + nir_push_else(b, m1_if); + nir_pop_if(b, m1_if); + v0 = nir_if_phi(b, v0_cb, v0); + v1 = nir_if_phi(b, v1_cb, v1); + } + } + + if (epilogue) { + v0 = apply_clamp_epilogue(b, v0, epilogue); + v1 = apply_clamp_epilogue(b, v1, epilogue); + } + + nir_store_global(b, v0, + gemm_f32_addr(b, info->output, info->desc_comps, info->out_res_type, + nir_iadd_imm(b, c_idx0, 8 * t), ACCESS_NON_READABLE), + .align_mul = 4, .write_mask = 3, .access = ACCESS_NON_READABLE); + nir_store_global(b, v1, + gemm_f32_addr(b, info->output, info->desc_comps, info->out_res_type, + nir_iadd_imm(b, c_idx1, 8 * t), ACCESS_NON_READABLE), + .align_mul = 4, .write_mask = 3, .access = ACCESS_NON_READABLE); + } +} + +static void +emit_gemm_cmat_store_guarded_row(nir_builder *b, const struct hk_nir_gemm_output *info, + const struct hk_nir_clamp_epilogue *epilogue, + nir_def *m, nir_def *n, nir_def *bias_mode, + nir_def *c_row, nir_def *c_col0, nir_def *acc[4]) +{ + const enum gl_access_qualifier read = ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER; + const bool dyn_row = info->has_bias_buffer && info->has_bias_mode && + (info->bias_mode_mask & (1u << 0)); + const bool dyn_col = info->has_bias_buffer && info->has_bias_mode && + (info->bias_mode_mask & (1u << 1)); + const bool fixed_row = info->has_bias_buffer && !info->has_bias_mode && + info->bias_mode_mask == (1u << 0); + const bool fixed_col = info->has_bias_buffer && !info->has_bias_mode && + info->bias_mode_mask == (1u << 1); + + nir_if *r_if = nir_push_if(b, nir_ult(b, c_row, m)); + { + nir_def *zero_f = nir_imm_float(b, 0.0f); + nir_def *is_row_bias = dyn_row ? nir_ieq_imm(b, bias_mode, 0) : NULL; + nir_def *is_col_bias = dyn_col ? nir_ieq_imm(b, bias_mode, 1) : NULL; + nir_def *rb = NULL; + if (fixed_row) { + rb = nir_load_global(b, 1, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, info->read_res_type[2], + c_row, read), + .align_mul = 4, .access = read); + } else if (dyn_row) { + nir_if *rb_if = nir_push_if(b, is_row_bias); + { + rb = nir_load_global(b, 1, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, info->read_res_type[2], + c_row, read), + .align_mul = 4, .access = read); + } + nir_push_else(b, rb_if); + nir_pop_if(b, rb_if); + rb = nir_if_phi(b, rb, zero_f); + } + + nir_def *c_idx0 = nir_iadd(b, nir_imul(b, c_row, n), c_col0); + for (unsigned t = 0; t < 4; ++t) { + for (unsigned lc = 0; lc < 2; ++lc) { + unsigned off = 8 * t + lc; + nir_def *col_k = nir_iadd_imm(b, c_col0, off); + nir_if *c_if = nir_push_if(b, nir_ult(b, col_k, n)); + { + nir_def *v = nir_channel(b, acc[t], lc); + if (fixed_row) { + v = nir_fadd(b, v, rb); + } else if (fixed_col) { + nir_def *cb = nir_load_global(b, 1, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, + info->read_res_type[2], col_k, read), + .align_mul = 4, .access = read); + v = nir_fadd(b, v, cb); + } else if (dyn_row || dyn_col) { + if (dyn_row) { + nir_def *v_rb = NULL, *v_nc = NULL; + nir_if *m0_if = nir_push_if(b, is_row_bias); + { + v_rb = nir_fadd(b, v, rb); + } + nir_push_else(b, m0_if); + { + if (dyn_col) { + nir_def *v_cb = NULL; + nir_if *m1_if = nir_push_if(b, is_col_bias); + { + nir_def *cb = nir_load_global(b, 1, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, + info->read_res_type[2], col_k, read), + .align_mul = 4, .access = read); + v_cb = nir_fadd(b, v, cb); + } + nir_push_else(b, m1_if); + nir_pop_if(b, m1_if); + v_nc = nir_if_phi(b, v_cb, v); + } else { + v_nc = v; + } + } + nir_pop_if(b, m0_if); + v = nir_if_phi(b, v_rb, v_nc); + } else { + nir_def *v_cb = NULL; + nir_if *m1_if = nir_push_if(b, is_col_bias); + { + nir_def *cb = nir_load_global(b, 1, 32, + gemm_f32_addr(b, info->reads[2], info->desc_comps, + info->read_res_type[2], col_k, read), + .align_mul = 4, .access = read); + v_cb = nir_fadd(b, v, cb); + } + nir_push_else(b, m1_if); + nir_pop_if(b, m1_if); + v = nir_if_phi(b, v_cb, v); + } + } + if (epilogue) + v = apply_clamp_epilogue(b, v, epilogue); + nir_store_global(b, v, + gemm_f32_addr(b, info->output, info->desc_comps, info->out_res_type, + nir_iadd_imm(b, c_idx0, off), ACCESS_NON_READABLE), + .align_mul = 4, .write_mask = 1, .access = ACCESS_NON_READABLE); + } + nir_pop_if(b, c_if); + } + } + } + nir_pop_if(b, r_if); +} + +nir_shader * +hk_nir_build_gemm_cmat(const nir_shader *producer, + const struct hk_nir_gemm_output *info, + uint32_t tile_n, + const struct hk_nir_clamp_epilogue *epilogue) +{ + if (!producer || !info || !info->cmat_valid || + (tile_n != 32 && tile_n != 64) || + info->desc_comps < 3 || info->desc_comps > 5) + return NULL; + if (epilogue && + (!hk_nir_clamp_epilogue_valid(epilogue) || + producer->info.float_controls_execution_mode != + epilogue->float_controls_execution_mode)) + return NULL; + + nir_shader *nir = nir_shader_create(NULL, MESA_SHADER_COMPUTE, + producer->options); + if (!nir) + return NULL; + nir->info.name = ralloc_asprintf(nir, "%s_gemm_cmat%u%s", + producer->info.name ? producer->info.name : "cs", + tile_n, epilogue ? "_clamp" : ""); + + /* Stage only the 64x16 tile of A (4 KiB) with XOR bank swizzle and load B + * directly from global memory, cutting shared memory in half for higher + * workgroup residency while eliminating B-staging overhead. */ + nir_variable *a_sh_var = nir_variable_create( + nir, nir_var_mem_shared, glsl_array_type(glsl_float_type(), 64 * 16, 4), + "gemm_a_tile"); + + const uint32_t wg_threads = (tile_n == 64) ? 256 : 128; + nir->info.workgroup_size[0] = wg_threads; + nir->info.workgroup_size[1] = 1; + nir->info.workgroup_size[2] = 1; + nir->info.workgroup_size_variable = false; + nir->info.api_subgroup_size = 32; + nir->info.min_subgroup_size = 32; + nir->info.max_subgroup_size = 32; + nir->info.num_ssbos = producer->info.num_ssbos; + nir->info.float_controls_execution_mode = producer->info.float_controls_execution_mode; + nir->num_uniforms = info->push_bytes; + + nir_function *fn = nir_function_create(nir, "main"); + fn->is_entrypoint = true; + nir_function_impl *impl = nir_function_impl_create(fn); + nir_builder b = nir_builder_at(nir_before_impl(impl)); + + const enum gl_access_qualifier read = ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER; + nir_def *wg_id = nir_load_workgroup_id(&b); + nir_def *lid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *sg = nir_load_subgroup_id(&b); + nir_def *lane = nir_load_subgroup_invocation(&b); + + nir_def *n = dw_push(&b, info->n_offset_B, info->push_bytes); + nir_def *k = dw_push(&b, info->k_offset_B, info->push_bytes); + nir_def *bias_mode = (info->has_bias_buffer && info->has_bias_mode) + ? dw_push(&b, info->bias_mode_offset_B, info->push_bytes) + : NULL; + nir_def *m = info->is_guarded + ? dw_push(&b, info->m_offset_B, info->push_bytes) + : NULL; + + nir_def *wg_col = nir_ishl_imm(&b, nir_channel(&b, wg_id, 0), tile_n == 64 ? 6 : 5); + nir_def *wg_row = nir_ishl_imm(&b, nir_channel(&b, wg_id, 1), 6); + + nir_def *sg_row = (tile_n == 64) + ? nir_ishl_imm(&b, nir_ushr_imm(&b, sg, 1), 4) + : nir_ishl_imm(&b, sg, 4); + nir_def *sg_col = (tile_n == 64) + ? nir_ishl_imm(&b, nir_iand_imm(&b, sg, 1), 5) + : nir_imm_int(&b, 0); + + nir_def *row_in_8 = nir_ior(&b, nir_iand_imm(&b, nir_ushr_imm(&b, lane, 1), 3), + nir_iand_imm(&b, nir_ushr_imm(&b, lane, 2), 4)); + nir_def *col_in_8 = nir_ior(&b, nir_ishl_imm(&b, nir_iand_imm(&b, lane, 1), 1), + nir_iand_imm(&b, nir_ushr_imm(&b, lane, 1), 4)); + + nir_deref_instr *a_sh_base = nir_build_deref_var(&b, a_sh_var); + nir_deref_instr *a_sh_f32 = nir_build_deref_cast_with_alignment( + &b, &a_sh_base->def, nir_var_mem_shared, + glsl_array_type(glsl_float_type(), 0, 4), 0, 4, 0); + nir_deref_instr *a_sh_v2 = nir_build_deref_cast_with_alignment( + &b, &a_sh_base->def, nir_var_mem_shared, + glsl_array_type(glsl_vector_type(GLSL_TYPE_FLOAT, 2), 0, 8), 0, 8, 0); + nir_deref_instr *a_sh_v4 = nir_build_deref_cast_with_alignment( + &b, &a_sh_base->def, nir_var_mem_shared, + glsl_array_type(glsl_vector_type(GLSL_TYPE_FLOAT, 4), 0, 16), 0, 16, 0); + + /* Precompute loop-invariant u16 XOR-swizzled shared A indices and hoisted + * global base offsets to minimize live registers and inner-loop ALU. */ + nir_def *a_c4_pre = nir_iand_imm(&b, lid, 3); + nir_def *a_r0_pre = nir_ushr_imm(&b, lid, 2); + nir_def *a_sh_idx4_0_16 = nir_u2u16( + &b, nir_ior(&b, nir_ishl_imm(&b, a_r0_pre, 2), + nir_ixor(&b, a_c4_pre, nir_iand_imm(&b, a_r0_pre, 3)))); + + nir_def *a_rd_r0 = nir_iadd(&b, sg_row, row_in_8); + nir_def *a_rd_c4 = nir_ixor(&b, nir_ushr_imm(&b, col_in_8, 2), + nir_iand_imm(&b, a_rd_r0, 3)); + nir_def *a_rd_idx2_0_16 = nir_u2u16( + &b, nir_ior(&b, nir_ior(&b, nir_ishl_imm(&b, a_rd_r0, 3), + nir_ishl_imm(&b, a_rd_c4, 1)), + nir_iand_imm(&b, nir_ushr_imm(&b, col_in_8, 1), 1))); + + nir_def *k4 = nir_ushr_imm(&b, k, 2); + nir_def *a_g_base4_0 = nir_iadd(&b, nir_imul(&b, nir_iadd(&b, wg_row, a_r0_pre), k4), + a_c4_pre); + nir_def *a_row32_stride4 = (tile_n == 32) ? nir_ishl_imm(&b, k4, 5) : NULL; + + nir_def *b_col0 = nir_iadd(&b, nir_iadd(&b, wg_col, sg_col), col_in_8); + nir_def *b_k0_base = nir_iadd(&b, nir_imul(&b, row_in_8, n), b_col0); + nir_def *b_stride8 = nir_ishl_imm(&b, n, 3); + nir_def *b_stride16 = nir_ishl_imm(&b, n, 4); + + nir_def *tile_m_full = NULL, *tile_n_full = NULL; + nir_def *k_aligned4 = NULL; + if (info->is_guarded) { + tile_m_full = nir_iand(&b, nir_uge_imm(&b, m, 64), + nir_uge(&b, nir_iadd_imm(&b, m, -64), wg_row)); + tile_n_full = nir_iand(&b, nir_uge_imm(&b, n, tile_n), + nir_uge(&b, nir_iadd_imm(&b, n, -(int32_t)tile_n), wg_col)); + k_aligned4 = nir_ieq_imm(&b, nir_iand_imm(&b, k, 3), 0); + } + + nir_def *zero_i = nir_imm_int(&b, 0); + nir_def *zero_f = nir_imm_float(&b, 0.0f); + nir_def *zero_v2 = nir_vec2(&b, zero_f, zero_f); + nir_def *zero_v4 = nir_vec4(&b, zero_f, zero_f, zero_f, zero_f); + + nir_loop *k_lp = nir_push_loop(&b); + k_lp->control = nir_loop_control_dont_unroll; + nir_block *k_pre = nir_cf_node_as_block(nir_cf_node_prev(&k_lp->cf_node)); + nir_block *k_hdr = nir_loop_first_block(k_lp); + + nir_phi_instr *kb_phi = nir_phi_instr_create(b.shader); + nir_def_init(&kb_phi->instr, &kb_phi->def, 1, 32); + nir_phi_instr_add_src(kb_phi, k_pre, zero_i); + + nir_phi_instr *b_idx_phi = nir_phi_instr_create(b.shader); + nir_def_init(&b_idx_phi->instr, &b_idx_phi->def, 1, 32); + nir_phi_instr_add_src(b_idx_phi, k_pre, b_k0_base); + + nir_phi_instr *a0_phi[4], *a1_phi[4]; + for (unsigned t = 0; t < 4; ++t) { + a0_phi[t] = nir_phi_instr_create(b.shader); + nir_def_init(&a0_phi[t]->instr, &a0_phi[t]->def, 2, 32); + nir_phi_instr_add_src(a0_phi[t], k_pre, zero_v2); + + a1_phi[t] = nir_phi_instr_create(b.shader); + nir_def_init(&a1_phi[t]->instr, &a1_phi[t]->def, 2, 32); + nir_phi_instr_add_src(a1_phi[t], k_pre, zero_v2); + } + + nir_def *k_base = &kb_phi->def; + nir_def *b_idx_cur = &b_idx_phi->def; + nir_if *k_done = nir_push_if(&b, nir_ige(&b, k_base, k)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, k_done); + + nir_def *a_sh_idx4_0 = nir_u2u32(&b, a_sh_idx4_0_16); + nir_def *kb4 = nir_ushr_imm(&b, k_base, 2); + nir_def *k_full = NULL; + + /* Phase 1: Stage 64x16 tile of A into 4 KiB XOR-swizzled shared memory. */ + if (!info->is_guarded) { + nir_def *a_idx4 = nir_iadd(&b, a_g_base4_0, kb4); + nir_def *va0 = nir_load_global( + &b, 4, 32, + gemm_vec4_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], + a_idx4, read), + .align_mul = 16, .access = read); + nir_store_deref(&b, nir_build_deref_array(&b, a_sh_v4, a_sh_idx4_0), va0, 0xf); + if (tile_n == 32) { + nir_def *va1 = nir_load_global( + &b, 4, 32, + gemm_vec4_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], + nir_iadd(&b, a_idx4, a_row32_stride4), read), + .align_mul = 16, .access = read); + nir_store_deref(&b, nir_build_deref_array(&b, a_sh_v4, + nir_iadd_imm(&b, a_sh_idx4_0, 128)), va1, 0xf); + } + } else { + k_full = nir_iand(&b, nir_uge_imm(&b, k, 16), + nir_uge(&b, nir_iadd_imm(&b, k, -16), k_base)); + nir_def *fast_a = nir_iand(&b, nir_iand(&b, tile_m_full, k_full), k_aligned4); + nir_if *fa_if = nir_push_if(&b, fast_a); + { + nir_def *a_idx4 = nir_iadd(&b, a_g_base4_0, kb4); + /* Guarded dispatch only enforces 4-byte alignment on A (minimum SSBO + * offset alignment is 4B), so address via gemm_f32_addr and declare + * align_mul = 4 on these vec4 loads. */ + nir_def *va0 = nir_load_global( + &b, 4, 32, + gemm_f32_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], + nir_ishl_imm(&b, a_idx4, 2), read), + .align_mul = 4, .access = read); + nir_store_deref(&b, nir_build_deref_array(&b, a_sh_v4, a_sh_idx4_0), va0, 0xf); + if (tile_n == 32) { + nir_def *va1 = nir_load_global( + &b, 4, 32, + gemm_f32_addr(&b, info->reads[0], info->desc_comps, info->read_res_type[0], + nir_ishl_imm(&b, nir_iadd(&b, a_idx4, a_row32_stride4), 2), + read), + .align_mul = 4, .access = read); + nir_store_deref(&b, nir_build_deref_array(&b, a_sh_v4, + nir_iadd_imm(&b, a_sh_idx4_0, 128)), va1, 0xf); + } + } + nir_push_else(&b, fa_if); + { + nir_if *k4_if = nir_push_if(&b, k_aligned4); + { + nir_def *lid_e = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *a_r0 = nir_ushr_imm(&b, lid_e, 2); + nir_def *a_c4 = nir_iand_imm(&b, lid_e, 3); + nir_def *kc4 = nir_iadd(&b, kb4, a_c4); + nir_def *k_ok = nir_ult(&b, kc4, k4); + const unsigned n_rows = (tile_n == 32) ? 2 : 1; + for (unsigned rr = 0; rr < n_rows; ++rr) { + nir_def *ar = rr ? nir_iadd_imm(&b, a_r0, 32) : a_r0; + nir_def *gr = nir_iadd(&b, wg_row, ar); + nir_def *va_ld = NULL; + nir_if *a_ok = nir_push_if(&b, nir_iand(&b, nir_ult(&b, gr, m), k_ok)); + { + nir_def *idx4 = nir_iadd(&b, nir_imul(&b, gr, k4), kc4); + va_ld = nir_load_global( + &b, 4, 32, + gemm_f32_addr(&b, info->reads[0], info->desc_comps, + info->read_res_type[0], + nir_ishl_imm(&b, idx4, 2), read), + .align_mul = 4, .access = read); + } + nir_push_else(&b, a_ok); + nir_pop_if(&b, a_ok); + nir_def *va_v = nir_if_phi(&b, va_ld, zero_v4); + nir_def *sh_i = rr ? nir_iadd_imm(&b, a_sh_idx4_0, 128) : a_sh_idx4_0; + nir_store_deref(&b, nir_build_deref_array(&b, a_sh_v4, sh_i), va_v, 0xf); + } + } + nir_push_else(&b, k4_if); + { + nir_def *lid_s = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *a_r0 = nir_ushr_imm(&b, lid_s, 2); + nir_def *a_c0 = nir_ishl_imm(&b, nir_iand_imm(&b, lid_s, 3), 2); + const unsigned n_rows = (tile_n == 32) ? 2 : 1; + for (unsigned rr = 0; rr < n_rows; ++rr) { + nir_def *ar = rr ? nir_iadd_imm(&b, a_r0, 32) : a_r0; + nir_def *gr = nir_iadd(&b, wg_row, ar); + nir_def *r_ok = nir_ult(&b, gr, m); + nir_def *sh_base = nir_ishl_imm(&b, rr ? nir_iadd_imm(&b, a_sh_idx4_0, 128) : a_sh_idx4_0, 2); + nir_def *gk_base = nir_iadd(&b, k_base, a_c0); + nir_def *g_row_base = nir_iadd(&b, nir_imul(&b, gr, k), gk_base); + + nir_loop *cc_lp = nir_push_loop(&b); + cc_lp->control = nir_loop_control_dont_unroll; + nir_block *cc_pre = nir_cf_node_as_block(nir_cf_node_prev(&cc_lp->cf_node)); + nir_block *cc_hdr = nir_loop_first_block(cc_lp); + nir_phi_instr *cc_phi = nir_phi_instr_create(b.shader); + nir_def_init(&cc_phi->instr, &cc_phi->def, 1, 32); + nir_phi_instr_add_src(cc_phi, cc_pre, zero_i); + nir_if *cc_done = nir_push_if(&b, nir_ige_imm(&b, &cc_phi->def, 4)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, cc_done); + + nir_def *gk = nir_iadd(&b, gk_base, &cc_phi->def); + nir_def *v_ld = NULL; + nir_if *ok_if = nir_push_if(&b, nir_iand(&b, r_ok, nir_ult(&b, gk, k))); + { + v_ld = nir_load_global(&b, 1, 32, + gemm_f32_addr(&b, info->reads[0], info->desc_comps, + info->read_res_type[0], + nir_iadd(&b, g_row_base, &cc_phi->def), read), + .align_mul = 4, .access = read); + } + nir_push_else(&b, ok_if); + nir_pop_if(&b, ok_if); + nir_def *av = nir_if_phi(&b, v_ld, zero_f); + nir_store_deref(&b, nir_build_deref_array(&b, a_sh_f32, nir_iadd(&b, sh_base, &cc_phi->def)), av, 1); + + nir_block *cc_back = nir_loop_last_block(cc_lp); + nir_phi_instr_add_src(cc_phi, cc_back, nir_iadd_imm(&b, &cc_phi->def, 1)); + nir_instr_insert(nir_before_block(cc_hdr), &cc_phi->instr); + nir_pop_loop(&b, cc_lp); + } + } + nir_pop_if(&b, k4_if); + } + nir_pop_if(&b, fa_if); + } + + nir_barrier(&b, .execution_scope = SCOPE_WORKGROUP, + .memory_scope = SCOPE_WORKGROUP, + .memory_modes = nir_var_mem_shared, + .memory_semantics = NIR_MEMORY_ACQ_REL); + + /* Phase 2: Direct-B f32matmad8x8 (2x8-step). */ + nir_def *next0[4], *next1[4]; + nir_def *a_rd_idx2_0 = nir_u2u32(&b, a_rd_idx2_0_16); + if (!info->is_guarded) { + for (unsigned t = 0; t < 4; ++t) { + next0[t] = &a0_phi[t]->def; + next1[t] = &a1_phi[t]->def; + } + for (unsigned ks = 0; ks < 2; ++ks) { + nir_def *a_idx0 = ks ? nir_ixor(&b, a_rd_idx2_0, nir_imm_int(&b, 4)) : a_rd_idx2_0; + nir_def *left0 = nir_load_deref(&b, nir_build_deref_array(&b, a_sh_v2, a_idx0)); + nir_def *left1 = nir_load_deref(&b, nir_build_deref_array(&b, a_sh_v2, + nir_iadd_imm(&b, a_idx0, 64))); + nir_def *b_ks = ks ? nir_iadd(&b, b_idx_cur, b_stride8) : b_idx_cur; + for (unsigned t = 0; t < 4; ++t) { + nir_def *bi = t ? nir_iadd_imm(&b, b_ks, 8 * t) : b_ks; + nir_def *right = nir_load_global( + &b, 2, 32, + gemm_f32_addr(&b, info->reads[1], info->desc_comps, info->read_res_type[1], + bi, read), + .align_mul = 4, .access = read); + next0[t] = nir_cmat_muladd_agx(&b, left0, right, next0[t], + .src_type = nir_type_float32, .src_type2 = nir_type_float32); + next1[t] = nir_cmat_muladd_agx(&b, left1, right, next1[t], + .src_type = nir_type_float32, .src_type2 = nir_type_float32); + } + } + } else { + nir_def *b_full = nir_iand(&b, tile_n_full, k_full); + nir_def *ft0[4], *ft1[4], *ge0[4], *ge1[4]; + nir_if *bf_if = nir_push_if(&b, b_full); + { + nir_loop *ks_lp = nir_push_loop(&b); + ks_lp->control = nir_loop_control_dont_unroll; + nir_block *ks_pre = nir_cf_node_as_block(nir_cf_node_prev(&ks_lp->cf_node)); + nir_block *ks_hdr = nir_loop_first_block(ks_lp); + + nir_phi_instr *ks_phi = nir_phi_instr_create(b.shader); + nir_def_init(&ks_phi->instr, &ks_phi->def, 1, 32); + nir_phi_instr_add_src(ks_phi, ks_pre, zero_i); + + nir_phi_instr *bks_phi = nir_phi_instr_create(b.shader); + nir_def_init(&bks_phi->instr, &bks_phi->def, 1, 32); + nir_phi_instr_add_src(bks_phi, ks_pre, b_idx_cur); + + nir_phi_instr *s0_phi[4], *s1_phi[4]; + for (unsigned t = 0; t < 4; ++t) { + s0_phi[t] = nir_phi_instr_create(b.shader); + nir_def_init(&s0_phi[t]->instr, &s0_phi[t]->def, 2, 32); + nir_phi_instr_add_src(s0_phi[t], ks_pre, &a0_phi[t]->def); + + s1_phi[t] = nir_phi_instr_create(b.shader); + nir_def_init(&s1_phi[t]->instr, &s1_phi[t]->def, 2, 32); + nir_phi_instr_add_src(s1_phi[t], ks_pre, &a1_phi[t]->def); + } + + nir_def *ks_v = &ks_phi->def; + nir_def *b_ks = &bks_phi->def; + nir_def *a_idx0 = nir_ixor(&b, a_rd_idx2_0, nir_ishl_imm(&b, ks_v, 2)); + nir_def *left0 = nir_load_deref(&b, nir_build_deref_array(&b, a_sh_v2, a_idx0)); + nir_def *left1 = nir_load_deref(&b, nir_build_deref_array(&b, a_sh_v2, + nir_iadd_imm(&b, a_idx0, 64))); + for (unsigned t = 0; t < 4; ++t) { + nir_def *bi = t ? nir_iadd_imm(&b, b_ks, 8 * t) : b_ks; + nir_def *right = nir_load_global( + &b, 2, 32, + gemm_f32_addr(&b, info->reads[1], info->desc_comps, info->read_res_type[1], + bi, read), + .align_mul = 4, .access = read); + ft0[t] = nir_cmat_muladd_agx(&b, left0, right, &s0_phi[t]->def, + .src_type = nir_type_float32, .src_type2 = nir_type_float32); + ft1[t] = nir_cmat_muladd_agx(&b, left1, right, &s1_phi[t]->def, + .src_type = nir_type_float32, .src_type2 = nir_type_float32); + } + + nir_def *ks_nxt = nir_iadd_imm(&b, ks_v, 1); + nir_if *ks_done = nir_push_if(&b, nir_ige_imm(&b, ks_nxt, 2)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, ks_done); + + nir_block *ks_back = nir_loop_last_block(ks_lp); + nir_phi_instr_add_src(ks_phi, ks_back, ks_nxt); + nir_phi_instr_add_src(bks_phi, ks_back, nir_iadd(&b, b_ks, b_stride8)); + nir_instr_insert(nir_before_block(ks_hdr), &ks_phi->instr); + nir_instr_insert(nir_before_block(ks_hdr), &bks_phi->instr); + for (unsigned t = 0; t < 4; ++t) { + nir_phi_instr_add_src(s0_phi[t], ks_back, ft0[t]); + nir_phi_instr_add_src(s1_phi[t], ks_back, ft1[t]); + nir_instr_insert(nir_before_block(ks_hdr), &s0_phi[t]->instr); + nir_instr_insert(nir_before_block(ks_hdr), &s1_phi[t]->instr); + } + nir_pop_loop(&b, ks_lp); + } + nir_push_else(&b, bf_if); + { + nir_def *lane_e = nir_load_subgroup_invocation(&b); + nir_def *sg_e = nir_load_subgroup_id(&b); + nir_def *sg_col_e = (tile_n == 64) + ? nir_ishl_imm(&b, nir_iand_imm(&b, sg_e, 1), 5) + : zero_i; + nir_def *row8_e = nir_ior(&b, nir_iand_imm(&b, nir_ushr_imm(&b, lane_e, 1), 3), + nir_iand_imm(&b, nir_ushr_imm(&b, lane_e, 2), 4)); + nir_def *col8_e = nir_ior(&b, nir_ishl_imm(&b, nir_iand_imm(&b, lane_e, 1), 1), + nir_iand_imm(&b, nir_ushr_imm(&b, lane_e, 1), 4)); + nir_def *b_col_e = nir_iadd(&b, nir_iadd(&b, wg_col, sg_col_e), col8_e); + + nir_loop *ks_lp = nir_push_loop(&b); + ks_lp->control = nir_loop_control_dont_unroll; + nir_block *ks_pre = nir_cf_node_as_block(nir_cf_node_prev(&ks_lp->cf_node)); + nir_block *ks_hdr = nir_loop_first_block(ks_lp); + + nir_phi_instr *ks_phi = nir_phi_instr_create(b.shader); + nir_def_init(&ks_phi->instr, &ks_phi->def, 1, 32); + nir_phi_instr_add_src(ks_phi, ks_pre, zero_i); + + nir_phi_instr *bks_phi = nir_phi_instr_create(b.shader); + nir_def_init(&bks_phi->instr, &bks_phi->def, 1, 32); + nir_phi_instr_add_src(bks_phi, ks_pre, b_idx_cur); + + nir_phi_instr *s0_phi[4], *s1_phi[4]; + for (unsigned t = 0; t < 4; ++t) { + s0_phi[t] = nir_phi_instr_create(b.shader); + nir_def_init(&s0_phi[t]->instr, &s0_phi[t]->def, 2, 32); + nir_phi_instr_add_src(s0_phi[t], ks_pre, &a0_phi[t]->def); + + s1_phi[t] = nir_phi_instr_create(b.shader); + nir_def_init(&s1_phi[t]->instr, &s1_phi[t]->def, 2, 32); + nir_phi_instr_add_src(s1_phi[t], ks_pre, &a1_phi[t]->def); + } + + nir_def *ks_v = &ks_phi->def; + nir_def *b_ks = &bks_phi->def; + nir_def *a_idx0 = nir_ixor(&b, a_rd_idx2_0, nir_ishl_imm(&b, ks_v, 2)); + nir_def *left0 = nir_load_deref(&b, nir_build_deref_array(&b, a_sh_v2, a_idx0)); + nir_def *left1 = nir_load_deref(&b, nir_build_deref_array(&b, a_sh_v2, + nir_iadd_imm(&b, a_idx0, 64))); + nir_def *bk_row = nir_iadd(&b, nir_iadd(&b, k_base, nir_ishl_imm(&b, ks_v, 3)), row8_e); + nir_def *row_ok = nir_ult(&b, bk_row, k); + + for (unsigned t = 0; t < 4; ++t) { + nir_def *bc = t ? nir_iadd_imm(&b, b_col_e, 8 * t) : b_col_e; + nir_def *bi = t ? nir_iadd_imm(&b, b_ks, 8 * t) : b_ks; + nir_def *v2_ld = NULL, *v1_ld = NULL; + nir_if *pair_ok = nir_push_if(&b, nir_iand(&b, row_ok, nir_ult(&b, nir_iadd_imm(&b, bc, 1), n))); + { + v2_ld = nir_load_global( + &b, 2, 32, + gemm_f32_addr(&b, info->reads[1], info->desc_comps, info->read_res_type[1], + bi, read), + .align_mul = 4, .access = read); + } + nir_push_else(&b, pair_ok); + { + nir_def *e0 = NULL; + nir_if *c0_ok = nir_push_if(&b, nir_iand(&b, row_ok, nir_ult(&b, bc, n))); + { + e0 = nir_load_global( + &b, 1, 32, + gemm_f32_addr(&b, info->reads[1], info->desc_comps, info->read_res_type[1], + bi, read), + .align_mul = 4, .access = read); + } + nir_push_else(&b, c0_ok); + nir_pop_if(&b, c0_ok); + nir_def *e0_v = nir_if_phi(&b, e0, zero_f); + v1_ld = nir_vec2(&b, e0_v, zero_f); + } + nir_pop_if(&b, pair_ok); + nir_def *right = nir_if_phi(&b, v2_ld, v1_ld); + ge0[t] = nir_cmat_muladd_agx(&b, left0, right, &s0_phi[t]->def, + .src_type = nir_type_float32, .src_type2 = nir_type_float32); + ge1[t] = nir_cmat_muladd_agx(&b, left1, right, &s1_phi[t]->def, + .src_type = nir_type_float32, .src_type2 = nir_type_float32); + } + + nir_def *ks_nxt = nir_iadd_imm(&b, ks_v, 1); + nir_if *ks_done = nir_push_if(&b, nir_ige_imm(&b, ks_nxt, 2)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, ks_done); + + nir_block *ks_back = nir_loop_last_block(ks_lp); + nir_phi_instr_add_src(ks_phi, ks_back, ks_nxt); + nir_phi_instr_add_src(bks_phi, ks_back, nir_iadd(&b, b_ks, b_stride8)); + nir_instr_insert(nir_before_block(ks_hdr), &ks_phi->instr); + nir_instr_insert(nir_before_block(ks_hdr), &bks_phi->instr); + for (unsigned t = 0; t < 4; ++t) { + nir_phi_instr_add_src(s0_phi[t], ks_back, ge0[t]); + nir_phi_instr_add_src(s1_phi[t], ks_back, ge1[t]); + nir_instr_insert(nir_before_block(ks_hdr), &s0_phi[t]->instr); + nir_instr_insert(nir_before_block(ks_hdr), &s1_phi[t]->instr); + } + nir_pop_loop(&b, ks_lp); + } + nir_pop_if(&b, bf_if); + for (unsigned t = 0; t < 4; ++t) { + next0[t] = nir_if_phi(&b, ft0[t], ge0[t]); + next1[t] = nir_if_phi(&b, ft1[t], ge1[t]); + } + } + + nir_barrier(&b, .execution_scope = SCOPE_WORKGROUP, + .memory_scope = SCOPE_WORKGROUP, + .memory_modes = nir_var_mem_shared, + .memory_semantics = NIR_MEMORY_ACQ_REL); + + nir_block *k_back = nir_loop_last_block(k_lp); + nir_phi_instr_add_src(kb_phi, k_back, nir_iadd_imm(&b, k_base, 16)); + nir_phi_instr_add_src(b_idx_phi, k_back, nir_iadd(&b, b_idx_cur, b_stride16)); + nir_instr_insert(nir_before_block(k_hdr), &kb_phi->instr); + nir_instr_insert(nir_before_block(k_hdr), &b_idx_phi->instr); + for (unsigned t = 0; t < 4; ++t) { + nir_phi_instr_add_src(a0_phi[t], k_back, next0[t]); + nir_phi_instr_add_src(a1_phi[t], k_back, next1[t]); + nir_instr_insert(nir_before_block(k_hdr), &a0_phi[t]->instr); + nir_instr_insert(nir_before_block(k_hdr), &a1_phi[t]->instr); + } + nir_pop_loop(&b, k_lp); + + /* Phase 3: Direct-C writeback + optional bias + optional clamp epilogue. */ + nir_def *acc0[4], *acc1[4]; + for (unsigned t = 0; t < 4; ++t) { + acc0[t] = &a0_phi[t]->def; + acc1[t] = &a1_phi[t]->def; + } + nir_def *sg_ep = nir_load_subgroup_id(&b); + nir_def *lane_ep = nir_load_subgroup_invocation(&b); + nir_def *sg_row_ep = (tile_n == 64) + ? nir_ishl_imm(&b, nir_ushr_imm(&b, sg_ep, 1), 4) + : nir_ishl_imm(&b, sg_ep, 4); + nir_def *sg_col_ep = (tile_n == 64) + ? nir_ishl_imm(&b, nir_iand_imm(&b, sg_ep, 1), 5) + : nir_imm_int(&b, 0); + nir_def *row8_ep = nir_ior(&b, nir_iand_imm(&b, nir_ushr_imm(&b, lane_ep, 1), 3), + nir_iand_imm(&b, nir_ushr_imm(&b, lane_ep, 2), 4)); + nir_def *col8_ep = nir_ior(&b, nir_ishl_imm(&b, nir_iand_imm(&b, lane_ep, 1), 1), + nir_iand_imm(&b, nir_ushr_imm(&b, lane_ep, 1), 4)); + nir_def *c_row0 = nir_iadd(&b, nir_iadd(&b, wg_row, sg_row_ep), row8_ep); + nir_def *c_col0 = nir_iadd(&b, nir_iadd(&b, wg_col, sg_col_ep), col8_ep); + + if (!info->is_guarded) { + emit_gemm_cmat_store_fast(&b, info, epilogue, n, bias_mode, c_row0, + nir_iadd_imm(&b, c_row0, 8), c_col0, acc0, acc1); + } else { + nir_if *cf_if = nir_push_if(&b, nir_iand(&b, tile_m_full, tile_n_full)); + { + emit_gemm_cmat_store_fast(&b, info, epilogue, n, bias_mode, c_row0, + nir_iadd_imm(&b, c_row0, 8), c_col0, acc0, acc1); + } + nir_push_else(&b, cf_if); + { + emit_gemm_cmat_store_guarded_row(&b, info, epilogue, m, n, bias_mode, + c_row0, c_col0, acc0); + emit_gemm_cmat_store_guarded_row(&b, info, epilogue, m, n, bias_mode, + nir_iadd_imm(&b, c_row0, 8), c_col0, acc1); + } + nir_pop_if(&b, cf_if); + } + + nir_opt_dce(nir); + nir_shader_gather_info(nir, impl); + return nir; +} diff --git a/src/asahi/vulkan/hk_nir_match_pointwise_clamp.h b/src/asahi/vulkan/hk_nir_match_pointwise_clamp.h index f1912bd27d01..cbb3733f0ee9 100644 --- a/src/asahi/vulkan/hk_nir_match_pointwise_clamp.h +++ b/src/asahi/vulkan/hk_nir_match_pointwise_clamp.h @@ -96,6 +96,9 @@ struct hk_nir_gemm_output { struct hk_nir_clamp_buffer output; struct hk_nir_clamp_buffer reads[3]; /* 0: A, 1: B, 2: bias (optional) */ uint32_t m_offset_B, n_offset_B, k_offset_B, bias_mode_offset_B; + uint32_t push_bytes; + uint32_t out_res_type, read_res_type[3]; + uint32_t desc_comps; uint32_t local_size[3]; uint32_t rows_per_thread; uint32_t float_controls_execution_mode; @@ -103,6 +106,7 @@ struct hk_nir_gemm_output { bool has_bias_mode; bool has_bias_buffer; bool is_guarded; + bool cmat_valid; }; enum hk_compute_pair_role { @@ -111,7 +115,7 @@ enum hk_compute_pair_role { HK_COMPUTE_PAIR_GEMM = 3, }; -#define HK_COMPUTE_PAIR_INFO_VERSION 4u +#define HK_COMPUTE_PAIR_INFO_VERSION 5u struct hk_compute_pair_info { uint32_t version; @@ -167,13 +171,47 @@ hk_nir_splice_epilogue(const struct nir_shader *producer, struct hk_nir_clamp_buffer output, const struct hk_nir_clamp_epilogue *epilogue); -/* Build a packed vec4 2-pixel-per-thread depthwise convolution NIR alternate - * from a certified depthwise producer (with vec4_valid == true). When - * `epilogue` is non-NULL, folds that exact clamp epilogue into both pixel - * outputs; handles both biased and biasless depthwise kernels. */ +/* Build a packed vec4 2-pixel-per-thread (horizontal pair (ox, ox+1) with Z + * carrying output row oy) depthwise convolution NIR alternate from a certified + * depthwise producer (with vec4_valid == true). When `epilogue` is non-NULL, + * folds that exact clamp epilogue into both pixel outputs; handles both biased + * and biasless depthwise kernels. */ struct nir_shader * hk_nir_build_depthwise_vec4(const struct nir_shader *producer, const struct hk_nir_depthwise_output *info, const struct hk_nir_clamp_epilogue *epilogue); +/* Build a Direct-B 4 KiB XOR-swizzled Shared-A f32matmad8x8 GEMM NIR alternate + * (tile_n == 32 or 64) from a certified row-major GEMM producer (with + * cmat_valid == true). When `epilogue` is non-NULL, folds that exact clamp + * epilogue into output writeback; handles arbitrary push layouts, bias_mode + * arms, unconditional row/column bias, and biasless kernels. */ +struct nir_shader * +hk_nir_build_gemm_cmat(const struct nir_shader *producer, + const struct hk_nir_gemm_output *info, + uint32_t tile_n, + const struct hk_nir_clamp_epilogue *epilogue); + +/* Validate dispatch dimensions for cooperative-matrix GEMM replacement. + * Unguarded GEMM executes ceil(K/32) unconditional 32-wide tiles, so K must + * be a multiple of 32 (not merely 16) to match the original shader exactly. */ +static inline bool +hk_gemm_cmat_dispatch_dims_ok(bool is_guarded, uint64_t m_u, uint32_t n_u, + uint32_t k_u, const uint32_t grid[3]) +{ + if (n_u == 0 || k_u == 0 || m_u == 0 || grid[2] != 1) + return false; + if (is_guarded) { + const uint64_t need_x = ((uint64_t)n_u + 31ull) / 32ull; + const uint64_t need_y = (m_u + 31ull) / 32ull; + return (uint64_t)grid[0] >= need_x && + (uint64_t)grid[1] >= need_y && + (uint64_t)grid[0] * 32ull <= (uint64_t)INT32_MAX && + (uint64_t)grid[1] * 32ull <= (uint64_t)INT32_MAX; + } + return (n_u % 32u) == 0 && (k_u % 32u) == 0 && (m_u % 64ull) == 0 && + grid[1] != 0 && (uint64_t)grid[0] * 32ull == (uint64_t)n_u && + (uint64_t)grid[1] * 32ull == m_u && m_u <= (uint64_t)INT32_MAX; +} + #endif diff --git a/src/asahi/vulkan/hk_queue.c b/src/asahi/vulkan/hk_queue.c index 6c5bd7d77940..5d7035dce049 100644 --- a/src/asahi/vulkan/hk_queue.c +++ b/src/asahi/vulkan/hk_queue.c @@ -3223,7 +3223,7 @@ hk_pack_runs(struct hk_device *dev, struct hk_queue *queue, const struct hk_compute_pair_dispatch *p = members[i].cs->compute_pair; const struct hk_compute_pair_dispatch *c = members[i + 1].cs->compute_pair; struct hk_shader *shader = hk_compute_pair_get_or_compile_fused( - dev, p->producer, &c->info.clamp.epilogue, p->is_depthwise_vec4); + dev, p->producer, &c->info.clamp.epilogue, p->alt_kind); if (shader && hk_fused_compute_shader_eligible(dev, shader, p)) { if (AGX3_G17P_NATIVE_COMPUTE_DISPATCH_SIZE > members[i].bytes) members[i].bytes = AGX3_G17P_NATIVE_COMPUTE_DISPATCH_SIZE; diff --git a/src/asahi/vulkan/hk_shader.c b/src/asahi/vulkan/hk_shader.c index b9d562f7f97d..c27f08db70a6 100644 --- a/src/asahi/vulkan/hk_shader.c +++ b/src/asahi/vulkan/hk_shader.c @@ -451,8 +451,15 @@ hk_compute_pair_info_valid(const struct hk_compute_pair_info *pair) return false; if (pair->role == HK_COMPUTE_PAIR_DEPTHWISE) return true; - if (pair->role == HK_COMPUTE_PAIR_GEMM) - return pair->gemm.rows_per_thread >= 1 && pair->gemm.rows_per_thread <= 16; + if (pair->role == HK_COMPUTE_PAIR_GEMM) { + if (pair->gemm.rows_per_thread < 1 || pair->gemm.rows_per_thread > 16) + return false; + if (pair->gemm.cmat_valid && + (pair->gemm.rows_per_thread != 8 || + pair->gemm.desc_comps < 3 || pair->gemm.desc_comps > 5)) + return false; + return true; + } if (pair->role == HK_COMPUTE_PAIR_CLAMP) return hk_nir_clamp_epilogue_valid(&pair->clamp.epilogue); return false; @@ -6590,6 +6597,14 @@ hk_api_shader_destroy(struct vk_device *vk_dev, struct vk_shader *vk_shader, hk_shader_destroy(dev, obj->depthwise_vec4, true); free(obj->depthwise_vec4); } + if (obj->gemm_cmat32) { + hk_shader_destroy(dev, obj->gemm_cmat32, true); + free(obj->gemm_cmat32); + } + if (obj->gemm_cmat64) { + hk_shader_destroy(dev, obj->gemm_cmat64, true); + free(obj->gemm_cmat64); + } if (obj->binary_cache_entry) hk_shader_binary_cache_entry_unref(dev, obj->binary_cache_entry); @@ -9673,22 +9688,28 @@ struct hk_shader * hk_compute_pair_get_or_compile_fused(struct hk_device *dev, struct hk_compute_pair_producer *prod, const struct hk_nir_clamp_epilogue *epilogue, - bool use_depthwise_vec4) + enum hk_compute_pair_alt_kind alt_kind) { if (!dev || !prod || !prod->nir || !hk_nir_clamp_epilogue_valid(epilogue)) return NULL; if (prod->info.role != HK_COMPUTE_PAIR_DEPTHWISE && prod->info.role != HK_COMPUTE_PAIR_GEMM) return NULL; - if (use_depthwise_vec4 && + if (alt_kind == HK_COMPUTE_PAIR_ALT_DEPTHWISE_VEC4 && (prod->info.role != HK_COMPUTE_PAIR_DEPTHWISE || !prod->info.depthwise.vec4_valid)) return NULL; + if ((alt_kind == HK_COMPUTE_PAIR_ALT_GEMM_CMAT32 || + alt_kind == HK_COMPUTE_PAIR_ALT_GEMM_CMAT64) && + (prod->info.role != HK_COMPUTE_PAIR_GEMM || + !prod->info.gemm.cmat_valid || + !agx_chip_cooperative_matrix_supported(dev->dev.chip))) + return NULL; simple_mtx_lock(&prod->lock); for (uint32_t i = 0; i < prod->variant_count; ++i) { const struct hk_compute_pair_variant *v = &prod->variants[i]; - if (v->use_depthwise_vec4 == use_depthwise_vec4 && + if (v->alt_kind == alt_kind && hk_nir_clamp_epilogue_equal(&v->epilogue, epilogue)) { struct hk_shader *cached = v->shader; simple_mtx_unlock(&prod->lock); @@ -9701,9 +9722,15 @@ hk_compute_pair_get_or_compile_fused(struct hk_device *dev, } nir_shader *fused_nir = NULL; - if (use_depthwise_vec4) { + if (alt_kind == HK_COMPUTE_PAIR_ALT_DEPTHWISE_VEC4) { fused_nir = hk_nir_build_depthwise_vec4(prod->nir, &prod->info.depthwise, epilogue); + } else if (alt_kind == HK_COMPUTE_PAIR_ALT_GEMM_CMAT32) { + fused_nir = hk_nir_build_gemm_cmat(prod->nir, &prod->info.gemm, 32, + epilogue); + } else if (alt_kind == HK_COMPUTE_PAIR_ALT_GEMM_CMAT64) { + fused_nir = hk_nir_build_gemm_cmat(prod->nir, &prod->info.gemm, 64, + epilogue); } else { const struct hk_nir_clamp_buffer out_buf = prod->info.role == HK_COMPUTE_PAIR_DEPTHWISE ? prod->info.depthwise.output @@ -9727,7 +9754,7 @@ hk_compute_pair_get_or_compile_fused(struct hk_device *dev, prod->variants[prod->variant_count++] = (struct hk_compute_pair_variant){ .epilogue = *epilogue, - .use_depthwise_vec4 = use_depthwise_vec4, + .alt_kind = alt_kind, .shader = shader, }; simple_mtx_unlock(&prod->lock); @@ -9796,6 +9823,8 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, bool has_compute_pair = false; struct hk_compute_pair_producer *compute_pair_producer = NULL; nir_shader *depthwise_vec4_nir = NULL; + nir_shader *gemm_cmat32_nir = NULL; + nir_shader *gemm_cmat64_nir = NULL; struct hk_shader *identity_copy4 = NULL; struct hk_shader *im2col_vec4 = NULL; struct hk_identity_copy4 identity_copy4_info = {0}; @@ -9937,6 +9966,13 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, pair.depthwise.vec4_valid) { depthwise_vec4_nir = hk_nir_build_depthwise_vec4(nir, &pair.depthwise, NULL); + } else if (pair.role == HK_COMPUTE_PAIR_GEMM && + pair.gemm.cmat_valid && + agx_chip_cooperative_matrix_supported(dev->dev.chip)) { + gemm_cmat32_nir = + hk_nir_build_gemm_cmat(nir, &pair.gemm, 32, NULL); + gemm_cmat64_nir = + hk_nir_build_gemm_cmat(nir, &pair.gemm, 64, NULL); } } } @@ -10135,6 +10171,8 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, if (result != VK_SUCCESS) { hk_compute_pair_producer_unref(compute_pair_producer); ralloc_free(depthwise_vec4_nir); + ralloc_free(gemm_cmat32_nir); + ralloc_free(gemm_cmat64_nir); if (identity_copy4) { hk_shader_destroy(dev, identity_copy4, true); free(identity_copy4); @@ -10177,14 +10215,24 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, ralloc_memdup(NULL, &compute_pair_info, sizeof(compute_pair_info)); if (obj->compute_pair) { obj->compute_pair_producer = compute_pair_producer; + const enum hk_feature_key hk_features = hk_make_feature_key(features); if (depthwise_vec4_nir) { - const enum hk_feature_key hk_features = hk_make_feature_key(features); obj->depthwise_vec4 = hk_compile_compute_alt_nir( dev, info, pAllocator, hk_features, depthwise_vec4_nir); } + if (gemm_cmat32_nir) { + obj->gemm_cmat32 = hk_compile_compute_alt_nir( + dev, info, pAllocator, hk_features, gemm_cmat32_nir); + } + if (gemm_cmat64_nir) { + obj->gemm_cmat64 = hk_compile_compute_alt_nir( + dev, info, pAllocator, hk_features, gemm_cmat64_nir); + } } else { hk_compute_pair_producer_unref(compute_pair_producer); ralloc_free(depthwise_vec4_nir); + ralloc_free(gemm_cmat32_nir); + ralloc_free(gemm_cmat64_nir); } } @@ -10475,6 +10523,11 @@ hk_compute_pair_info_serialize(struct blob *blob, blob_write_uint32(blob, g->n_offset_B); blob_write_uint32(blob, g->k_offset_B); blob_write_uint32(blob, g->bias_mode_offset_B); + blob_write_uint32(blob, g->push_bytes); + blob_write_uint32(blob, g->out_res_type); + for (unsigned i = 0; i < 3; ++i) + blob_write_uint32(blob, g->read_res_type[i]); + blob_write_uint32(blob, g->desc_comps); for (unsigned i = 0; i < 3; ++i) blob_write_uint32(blob, g->local_size[i]); blob_write_uint32(blob, g->rows_per_thread); @@ -10482,7 +10535,8 @@ hk_compute_pair_info_serialize(struct blob *blob, blob_write_uint8(blob, g->bias_mode_mask); blob_write_uint8(blob, (g->has_bias_mode ? 1u : 0u) | (g->has_bias_buffer ? 2u : 0u) | - (g->is_guarded ? 4u : 0u)); + (g->is_guarded ? 4u : 0u) | + (g->cmat_valid ? 8u : 0u)); } else if (info->role == HK_COMPUTE_PAIR_CLAMP) { const struct hk_nir_pointwise_clamp *c = &info->clamp; hk_nir_clamp_buffer_serialize(blob, &c->input); @@ -10554,17 +10608,23 @@ hk_compute_pair_info_deserialize(struct blob_reader *blob, g->n_offset_B = blob_read_uint32(blob); g->k_offset_B = blob_read_uint32(blob); g->bias_mode_offset_B = blob_read_uint32(blob); + g->push_bytes = blob_read_uint32(blob); + g->out_res_type = blob_read_uint32(blob); + for (unsigned i = 0; i < 3; ++i) + g->read_res_type[i] = blob_read_uint32(blob); + g->desc_comps = blob_read_uint32(blob); for (unsigned i = 0; i < 3; ++i) g->local_size[i] = blob_read_uint32(blob); g->rows_per_thread = blob_read_uint32(blob); g->float_controls_execution_mode = blob_read_uint32(blob); g->bias_mode_mask = blob_read_uint8(blob); const uint8_t flags = blob_read_uint8(blob); - if (flags & ~7u) + if (flags & ~15u) return false; g->has_bias_mode = (flags & 1u) != 0; g->has_bias_buffer = (flags & 2u) != 0; g->is_guarded = (flags & 4u) != 0; + g->cmat_valid = (flags & 8u) != 0; } else if (info->role == HK_COMPUTE_PAIR_CLAMP) { struct hk_nir_pointwise_clamp *c = &info->clamp; hk_nir_clamp_buffer_deserialize(blob, &c->input); @@ -10733,15 +10793,19 @@ hk_deserialize_api_shader_impl(struct vk_device *vk_dev, const unsigned variant_flags3 = blob_read_uint8(blob); const bool has_compute_pair = (variant_flags3 & 1) != 0; const bool has_depthwise_vec4 = (variant_flags3 & 2) != 0; + const bool has_gemm_cmat32 = (variant_flags3 & 4) != 0; + const bool has_gemm_cmat64 = (variant_flags3 & 8) != 0; /* Graphics, compute, task and mesh stages. */ if (blob->overrun || stage >= MESA_SHADER_MESH_STAGES || (clip_z ? !dev->vk.physical->supported_features.depthClipControl : dev->vk.enabled_features.depthClipControl) || (has_mesh_source && (stage != MESA_SHADER_FRAGMENT || dev->dev.chip != AGX_CHIP_G17P)) || - (variant_flags2 & ~127u) || (variant_flags3 & ~3u) || + (variant_flags2 & ~127u) || (variant_flags3 & ~15u) || (has_im2col_vec4 && !has_identity_copy4) || (has_depthwise_vec4 && !has_compute_pair) || + ((has_gemm_cmat32 || has_gemm_cmat64) && + (!has_compute_pair || !agx_chip_cooperative_matrix_supported(dev->dev.chip))) || ((has_compute_pair || has_identity_copy4) && (stage != MESA_SHADER_COMPUTE || !agx_chip_native_or_m5(dev->dev.chip))) || (has_fbl_source && stage != MESA_SHADER_FRAGMENT) || @@ -10790,7 +10854,10 @@ hk_deserialize_api_shader_impl(struct vk_device *vk_dev, if (has_compute_pair) { struct hk_compute_pair_info pair; if (!hk_compute_pair_info_deserialize(blob, &pair) || - (has_depthwise_vec4 && pair.role != HK_COMPUTE_PAIR_DEPTHWISE)) { + (has_depthwise_vec4 && + (pair.role != HK_COMPUTE_PAIR_DEPTHWISE || !pair.depthwise.vec4_valid)) || + ((has_gemm_cmat32 || has_gemm_cmat64) && + (pair.role != HK_COMPUTE_PAIR_GEMM || !pair.gemm.cmat_valid))) { hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator); return vk_error(dev, VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT); } @@ -10854,6 +10921,24 @@ hk_deserialize_api_shader_impl(struct vk_device *vk_dev, } } + if (has_gemm_cmat32) { + VkResult result = hk_deserialize_optional_compute_alt( + dev, blob, &obj->gemm_cmat32); + if (result != VK_SUCCESS) { + hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator); + return result; + } + } + + if (has_gemm_cmat64) { + VkResult result = hk_deserialize_optional_compute_alt( + dev, blob, &obj->gemm_cmat64); + if (result != VK_SUCCESS) { + hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator); + return result; + } + } + /* Restore what the compile set on the composed passthrough object. */ if (stage == MESA_SHADER_MESH && agx_chip_g17_m5(dev->dev.chip)) { struct hk_shader *object = &obj->variants[HK_MESH_VARIANT_RAST]; @@ -11434,7 +11519,9 @@ hk_api_shader_serialize(struct vk_device *vk_dev, (obj->identity_copy4 ? 32 : 0) | (obj->im2col_vec4 ? 64 : 0)); blob_write_uint8(blob, (obj->compute_pair ? 1 : 0) | - (obj->depthwise_vec4 ? 2 : 0)); + (obj->depthwise_vec4 ? 2 : 0) | + (obj->gemm_cmat32 ? 4 : 0) | + (obj->gemm_cmat64 ? 8 : 0)); if (obj->compute_pair) hk_compute_pair_info_serialize(blob, obj->compute_pair); if (obj->identity_copy4) @@ -11489,10 +11576,12 @@ hk_api_shader_serialize(struct vk_device *vk_dev, } } - const struct hk_shader *compute_alts[3] = { + const struct hk_shader *compute_alts[5] = { obj->identity_copy4, obj->im2col_vec4, obj->depthwise_vec4, + obj->gemm_cmat32, + obj->gemm_cmat64, }; for (unsigned ai = 0; ai < ARRAY_SIZE(compute_alts); ++ai) { if (!compute_alts[ai]) diff --git a/src/asahi/vulkan/hk_shader.h b/src/asahi/vulkan/hk_shader.h index 84d698266d37..ae1cdb1d3ede 100644 --- a/src/asahi/vulkan/hk_shader.h +++ b/src/asahi/vulkan/hk_shader.h @@ -526,6 +526,8 @@ struct hk_api_shader { struct hk_shader *identity_copy4; struct hk_shader *im2col_vec4; struct hk_shader *depthwise_vec4; + struct hk_shader *gemm_cmat32; + struct hk_shader *gemm_cmat64; struct hk_identity_copy4 identity_copy4_info; /* Is this an internal passthrough geometry shader? */ diff --git a/src/asahi/vulkan/tests/hk_nir_eval_test.h b/src/asahi/vulkan/tests/hk_nir_eval_test.h index a620b8989e59..4e4500826e93 100644 --- a/src/asahi/vulkan/tests/hk_nir_eval_test.h +++ b/src/asahi/vulkan/tests/hk_nir_eval_test.h @@ -30,6 +30,7 @@ struct hk_eval_ssbo { unsigned binding; void *data; size_t size; + size_t base_offset; /* Simulated runtime VkDescriptorBufferInfo.offset for alignment checks */ }; struct hk_eval_env { @@ -267,6 +268,14 @@ hk_eval_alu(struct hk_eval_env *env, const nir_alu_instr *alu) case nir_op_i2i32: r = (uint32_t)s0; break; + case nir_op_u2u16: + case nir_op_i2i16: + r = (uint16_t)s0; + break; + case nir_op_u2u8: + case nir_op_i2i8: + r = (uint8_t)s0; + break; case nir_op_fadd: r = hk_eval_f2u(hk_eval_u2f((uint32_t)s0) + hk_eval_u2f((uint32_t)s1)); break; @@ -641,4 +650,562 @@ hk_eval_dispatch(nir_shader *nir, const uint32_t grid[3], free(ssa); } + +struct hk_eval_shared_var { + const nir_variable *var; + size_t offset; + size_t size; +}; + +static inline size_t +hk_eval_type_bytes(const struct glsl_type *type) +{ + if (glsl_type_is_array(type)) { + unsigned len = glsl_get_length(type); + uint32_t stride = hk_eval_type_stride(type); + return (size_t)len * stride; + } + return (size_t)glsl_get_components(type) * (glsl_get_bit_size(type) / 8); +} + +enum hk_wg_thr_state { + HK_WG_RUN = 0, + HK_WG_BARRIER, + HK_WG_CMAT, + HK_WG_DONE, +}; + +struct hk_wg_frame { + const struct exec_list *list; + nir_cf_node *node; + nir_instr *next_instr; + bool is_loop; + unsigned iters; + bool entered_block; +}; + +struct hk_wg_thread { + struct hk_eval_env env; + uint32_t sg_id; + uint32_t sg_lane; + nir_block *prev_block; + struct hk_wg_frame stack[16]; + int sp; + enum hk_wg_thr_state state; + const nir_intrinsic_instr *pending_cmat; +}; + +static inline void +hk_wg_decode_addr(const struct hk_eval_env *env, uint8_t *shared_mem, + const struct hk_eval_shared_var *svars, unsigned num_svars, + uint64_t addr, uint8_t **ptr_out, size_t *avail_out, + size_t *align_base_out) +{ + uint64_t tag = addr >> 40; + uint64_t off = addr & ((1ull << 40) - 1); + if (tag >= 1 && tag <= env->num_ssbos) { + const struct hk_eval_ssbo *buf = &env->ssbos[tag - 1]; + HK_EVAL_CHECK(off <= buf->size); + *ptr_out = (uint8_t *)buf->data + off; + *avail_out = buf->size - (size_t)off; + *align_base_out = buf->base_offset + (size_t)off; + return; + } + uint64_t sidx = tag - (env->num_ssbos + 1); + HK_EVAL_CHECK(tag > env->num_ssbos && sidx < num_svars); + HK_EVAL_CHECK(off <= svars[sidx].size); + *ptr_out = shared_mem + svars[sidx].offset + off; + *avail_out = svars[sidx].size - (size_t)off; + *align_base_out = svars[sidx].offset + (size_t)off; +} + +static inline void +hk_wg_step_thread(struct hk_wg_thread *thr, uint8_t *shared_mem, + const struct hk_eval_shared_var *svars, unsigned num_svars) +{ + struct hk_eval_env *env = &thr->env; + while (thr->state == HK_WG_RUN) { + if (thr->sp < 0) { + thr->state = HK_WG_DONE; + return; + } + struct hk_wg_frame *fr = &thr->stack[thr->sp]; + if (!fr->node) { + if (fr->is_loop) { + HK_EVAL_CHECK(++fr->iters < 100000); + fr->node = exec_list_is_empty(fr->list) + ? NULL + : exec_node_data(nir_cf_node, exec_list_get_head_const(fr->list), node); + fr->next_instr = NULL; + fr->entered_block = false; + continue; + } + thr->sp--; + continue; + } + + nir_cf_node *cf = fr->node; + if (cf->type == nir_cf_node_if) { + nir_if *nif = nir_cf_node_as_if(cf); + bool cond = (hk_eval_read_ssa(env, nif->condition.ssa, 0) & 1) != 0; + fr->node = nir_cf_node_next(cf); + fr->next_instr = NULL; + fr->entered_block = false; + const struct exec_list *arm = cond ? &nif->then_list : &nif->else_list; + HK_EVAL_CHECK(thr->sp + 1 < 16); + thr->sp++; + thr->stack[thr->sp] = (struct hk_wg_frame){ + .list = arm, + .node = exec_list_is_empty(arm) + ? NULL + : exec_node_data(nir_cf_node, exec_list_get_head_const(arm), node), + }; + continue; + } + + if (cf->type == nir_cf_node_loop) { + nir_loop *lp = nir_cf_node_as_loop(cf); + fr->node = nir_cf_node_next(cf); + fr->next_instr = NULL; + fr->entered_block = false; + HK_EVAL_CHECK(thr->sp + 1 < 16); + thr->sp++; + thr->stack[thr->sp] = (struct hk_wg_frame){ + .list = &lp->body, + .node = exec_list_is_empty(&lp->body) + ? NULL + : exec_node_data(nir_cf_node, exec_list_get_head_const(&lp->body), node), + .is_loop = true, + }; + continue; + } + + HK_EVAL_CHECK(cf->type == nir_cf_node_block); + nir_block *block = nir_cf_node_as_block(cf); + if (!fr->entered_block) { + fr->entered_block = true; + /* Evaluate phis simultaneously using thr->prev_block. */ + unsigned phi_count = 0; + nir_foreach_phi(phi, block) + phi_count++; + if (phi_count) { + uint64_t (*phi_vals)[4] = calloc(phi_count, sizeof(*phi_vals)); + HK_EVAL_CHECK(phi_vals && thr->prev_block); + unsigned idx = 0; + nir_foreach_phi(phi, block) { + nir_phi_src *src = nir_phi_get_src_from_block(phi, thr->prev_block); + HK_EVAL_CHECK(src); + for (unsigned c = 0; c < phi->def.num_components; ++c) + phi_vals[idx][c] = hk_eval_read_ssa(env, src->src.ssa, c); + idx++; + } + idx = 0; + nir_foreach_phi(phi, block) { + for (unsigned c = 0; c < phi->def.num_components; ++c) + env->ssa[phi->def.index][c] = phi_vals[idx][c]; + idx++; + } + free(phi_vals); + } + fr->next_instr = exec_list_is_empty(&block->instr_list) + ? NULL + : exec_node_data(nir_instr, exec_list_get_head(&block->instr_list), node); + } + + if (!fr->next_instr) { + thr->prev_block = block; + fr->node = nir_cf_node_next(cf); + fr->entered_block = false; + continue; + } + + nir_instr *instr = fr->next_instr; + struct exec_node *nxt = exec_node_get_next(&instr->node); + fr->next_instr = exec_node_is_tail_sentinel(nxt) + ? NULL + : exec_node_data(nir_instr, nxt, node); + + switch (instr->type) { + case nir_instr_type_phi: + break; + case nir_instr_type_load_const: { + nir_load_const_instr *lc = nir_instr_as_load_const(instr); + for (unsigned c = 0; c < lc->def.num_components; ++c) { + if (lc->def.bit_size == 1) + env->ssa[lc->def.index][c] = lc->value[c].b ? 1 : 0; + else if (lc->def.bit_size == 64) + env->ssa[lc->def.index][c] = lc->value[c].u64; + else + env->ssa[lc->def.index][c] = lc->value[c].u32; + } + break; + } + case nir_instr_type_undef: { + nir_undef_instr *u = nir_instr_as_undef(instr); + for (unsigned c = 0; c < u->def.num_components; ++c) + env->ssa[u->def.index][c] = 0; + break; + } + case nir_instr_type_alu: + hk_eval_alu(env, nir_instr_as_alu(instr)); + break; + case nir_instr_type_deref: { + nir_deref_instr *d = nir_instr_as_deref(instr); + uint64_t addr = 0; + switch (d->deref_type) { + case nir_deref_type_var: { + HK_EVAL_CHECK(d->var && d->var->data.mode == nir_var_mem_shared); + unsigned sidx = num_svars; + for (unsigned i = 0; i < num_svars; ++i) { + if (svars[i].var == d->var) { + sidx = i; + break; + } + } + HK_EVAL_CHECK(sidx < num_svars); + addr = (((uint64_t)(env->num_ssbos + 1 + sidx)) << 40); + break; + } + case nir_deref_type_cast: { + uint64_t parent = hk_eval_read_ssa(env, d->parent.ssa, 0); + if (parent >> 40) { + addr = parent; + } else { + unsigned set = (unsigned)(parent >> 16); + unsigned binding = (unsigned)(parent & 0xffffu); + int idx = hk_eval_find_ssbo(env, set, binding); + addr = hk_eval_make_vaddr((unsigned)idx, 0); + } + break; + } + case nir_deref_type_struct: { + nir_deref_instr *parent = nir_deref_instr_parent(d); + uint64_t base = hk_eval_read_ssa(env, d->parent.ssa, 0); + int off = glsl_get_struct_field_offset(parent->type, d->strct.index); + addr = base + (uint64_t)(off > 0 ? off : 0); + break; + } + case nir_deref_type_array: { + nir_deref_instr *parent = nir_deref_instr_parent(d); + uint64_t base = hk_eval_read_ssa(env, d->parent.ssa, 0); + int64_t idx = (int64_t)(int32_t)(uint32_t)hk_eval_read_ssa(env, d->arr.index.ssa, 0); + uint32_t stride = hk_eval_type_stride(parent->type); + HK_EVAL_CHECK(idx >= 0); + addr = base + (uint64_t)idx * stride; + break; + } + default: + HK_EVAL_CHECK(!"unsupported deref type in wg eval"); + } + env->ssa[d->def.index][0] = addr; + break; + } + case nir_instr_type_intrinsic: { + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + switch (intr->intrinsic) { + case nir_intrinsic_load_global_invocation_id: + for (unsigned c = 0; c < 3; ++c) + env->ssa[intr->def.index][c] = env->gid[c]; + break; + case nir_intrinsic_load_workgroup_id: + for (unsigned c = 0; c < 3; ++c) + env->ssa[intr->def.index][c] = env->wg_id[c]; + break; + case nir_intrinsic_load_local_invocation_id: + for (unsigned c = 0; c < 3; ++c) + env->ssa[intr->def.index][c] = env->lid[c]; + break; + case nir_intrinsic_load_base_workgroup_id: + for (unsigned c = 0; c < 3; ++c) + env->ssa[intr->def.index][c] = env->base_wg[c]; + break; + case nir_intrinsic_load_subgroup_id: + env->ssa[intr->def.index][0] = thr->sg_id; + break; + case nir_intrinsic_load_subgroup_invocation: + env->ssa[intr->def.index][0] = thr->sg_lane; + break; + case nir_intrinsic_load_push_constant: { + uint64_t off = nir_intrinsic_base(intr) + + (uint32_t)hk_eval_read_ssa(env, intr->src[0].ssa, 0); + const unsigned nbytes = intr->def.bit_size / 8; + for (unsigned c = 0; c < intr->def.num_components; ++c) { + uint64_t p = off + (uint64_t)c * nbytes; + HK_EVAL_CHECK(p + nbytes <= env->push_size); + uint32_t v = 0; + memcpy(&v, (const uint8_t *)env->push + p, nbytes); + env->ssa[intr->def.index][c] = v; + } + break; + } + case nir_intrinsic_vulkan_resource_index: { + uint64_t key = ((uint64_t)nir_intrinsic_desc_set(intr) << 16) | + nir_intrinsic_binding(intr); + for (unsigned c = 0; c < intr->def.num_components; ++c) + env->ssa[intr->def.index][c] = key; + break; + } + case nir_intrinsic_load_vulkan_descriptor: + for (unsigned c = 0; c < intr->def.num_components; ++c) + env->ssa[intr->def.index][c] = hk_eval_read_ssa(env, intr->src[0].ssa, c); + break; + case nir_intrinsic_deref_buffer_address: + env->ssa[intr->def.index][0] = hk_eval_read_ssa(env, intr->src[0].ssa, 0); + break; + case nir_intrinsic_load_deref: + case nir_intrinsic_load_global: { + uint64_t vaddr = hk_eval_read_ssa(env, intr->src[0].ssa, 0); + uint8_t *ptr = NULL; + size_t avail = 0, abase = 0; + hk_wg_decode_addr(env, shared_mem, svars, num_svars, vaddr, + &ptr, &avail, &abase); + if (intr->intrinsic == nir_intrinsic_load_global) { + unsigned amul = nir_intrinsic_align_mul(intr); + if (amul > 1) + HK_EVAL_CHECK((abase % amul) == 0); + } + const unsigned nbytes = intr->def.bit_size / 8; + HK_EVAL_CHECK((size_t)intr->def.num_components * nbytes <= avail); + for (unsigned c = 0; c < intr->def.num_components; ++c) { + uint32_t v = 0; + memcpy(&v, ptr + (size_t)c * nbytes, nbytes); + env->ssa[intr->def.index][c] = v; + } + break; + } + case nir_intrinsic_store_deref: + case nir_intrinsic_store_global: { + const bool is_deref = intr->intrinsic == nir_intrinsic_store_deref; + uint64_t vaddr = hk_eval_read_ssa(env, intr->src[is_deref ? 0 : 1].ssa, 0); + nir_def *val = intr->src[is_deref ? 1 : 0].ssa; + uint8_t *ptr = NULL; + size_t avail = 0, abase = 0; + hk_wg_decode_addr(env, shared_mem, svars, num_svars, vaddr, + &ptr, &avail, &abase); + if (!is_deref) { + unsigned amul = nir_intrinsic_align_mul(intr); + if (amul > 1) + HK_EVAL_CHECK((abase % amul) == 0); + } + const unsigned nbytes = val->bit_size / 8; + const unsigned wmask = nir_intrinsic_write_mask(intr); + for (unsigned c = 0; c < val->num_components; ++c) { + if (!(wmask & (1u << c))) + continue; + HK_EVAL_CHECK((size_t)(c + 1) * nbytes <= avail); + uint32_t v = (uint32_t)hk_eval_read_ssa(env, val, c); + memcpy(ptr + (size_t)c * nbytes, &v, nbytes); + } + break; + } + case nir_intrinsic_barrier: + if (nir_intrinsic_execution_scope(intr) == SCOPE_WORKGROUP) { + thr->state = HK_WG_BARRIER; + return; + } + break; + case nir_intrinsic_cmat_muladd_agx: + thr->pending_cmat = intr; + thr->state = HK_WG_CMAT; + return; + default: + fprintf(stderr, "hk_nir_eval_test(wg): unsupported intrinsic %s\n", + nir_intrinsic_infos[intr->intrinsic].name); + HK_EVAL_CHECK(!"unsupported intrinsic in wg eval"); + } + break; + } + case nir_instr_type_jump: { + nir_jump_instr *j = nir_instr_as_jump(instr); + thr->prev_block = block; + if (j->type == nir_jump_break) { + while (thr->sp >= 0 && !thr->stack[thr->sp].is_loop) + thr->sp--; + HK_EVAL_CHECK(thr->sp >= 0); + thr->sp--; + } else if (j->type == nir_jump_continue) { + while (thr->sp >= 0 && !thr->stack[thr->sp].is_loop) + thr->sp--; + HK_EVAL_CHECK(thr->sp >= 0); + thr->stack[thr->sp].node = NULL; + thr->stack[thr->sp].next_instr = NULL; + thr->stack[thr->sp].entered_block = false; + } else if (j->type == nir_jump_return) { + thr->sp = -1; + thr->state = HK_WG_DONE; + return; + } + break; + } + default: + HK_EVAL_CHECK(!"unsupported instr type in wg eval"); + } + } +} + +static inline void +hk_eval_dispatch_wg(nir_shader *nir, const uint32_t grid[3], + const struct hk_eval_ssbo *ssbos, unsigned num_ssbos, + const void *push, size_t push_size) +{ + nir_function_impl *impl = nir_shader_get_entrypoint(nir); + nir_index_ssa_defs(impl); + + const uint32_t lx = nir->info.workgroup_size[0]; + const uint32_t ly = nir->info.workgroup_size[1]; + const uint32_t lz = nir->info.workgroup_size[2]; + const uint32_t wg_threads = lx * ly * lz; + HK_EVAL_CHECK(wg_threads > 0 && wg_threads <= 1024); + + struct hk_eval_shared_var svars[16]; + unsigned num_svars = 0; + size_t total_shared = 0; + nir_foreach_variable_with_modes(var, nir, nir_var_mem_shared) { + HK_EVAL_CHECK(num_svars < ARRAY_SIZE(svars)); + total_shared = (total_shared + 15u) & ~(size_t)15u; + size_t sz = hk_eval_type_bytes(var->type); + svars[num_svars++] = (struct hk_eval_shared_var){ + .var = var, + .offset = total_shared, + .size = sz, + }; + total_shared += sz; + } + uint8_t *shared_mem = total_shared ? calloc(1, total_shared) : NULL; + HK_EVAL_CHECK(!total_shared || shared_mem); + + struct hk_wg_thread *thrs = calloc(wg_threads, sizeof(*thrs)); + uint64_t (*all_ssa)[4] = calloc((size_t)wg_threads * (impl->ssa_alloc + 1), + sizeof(*all_ssa)); + HK_EVAL_CHECK(thrs && all_ssa); + + for (uint32_t wz = 0; wz < grid[2]; ++wz) { + for (uint32_t wy = 0; wy < grid[1]; ++wy) { + for (uint32_t wx = 0; wx < grid[0]; ++wx) { + if (total_shared) + memset(shared_mem, 0, total_shared); + memset(all_ssa, 0, + (size_t)wg_threads * (impl->ssa_alloc + 1) * sizeof(*all_ssa)); + + for (uint32_t tid = 0; tid < wg_threads; ++tid) { + uint32_t tx = tid % lx; + uint32_t ty = (tid / lx) % ly; + uint32_t tz = tid / (lx * ly); + thrs[tid] = (struct hk_wg_thread){ + .env = { + .ssbos = ssbos, + .num_ssbos = num_ssbos, + .push = push, + .push_size = push_size, + .wg_id = { wx, wy, wz }, + .lid = { tx, ty, tz }, + .gid = { wx * lx + tx, wy * ly + ty, wz * lz + tz }, + .ssa = all_ssa + (size_t)tid * (impl->ssa_alloc + 1), + .num_ssa = impl->ssa_alloc + 1, + }, + .sg_id = tid / 32u, + .sg_lane = tid % 32u, + .sp = 0, + .state = HK_WG_RUN, + }; + thrs[tid].stack[0] = (struct hk_wg_frame){ + .list = &impl->body, + .node = exec_list_is_empty(&impl->body) + ? NULL + : exec_node_data(nir_cf_node, exec_list_get_head_const(&impl->body), node), + }; + } + + for (;;) { + bool any_run = false; + for (uint32_t tid = 0; tid < wg_threads; ++tid) { + if (thrs[tid].state == HK_WG_RUN) { + hk_wg_step_thread(&thrs[tid], shared_mem, svars, num_svars); + any_run = true; + } + } + + /* Resolve any subgroup where all 32 lanes hit cmat_muladd_agx. */ + bool resolved_cmat = false; + for (uint32_t sg = 0; sg * 32u < wg_threads; ++sg) { + uint32_t base = sg * 32u; + if (base + 32u > wg_threads) + break; + const nir_intrinsic_instr *cm = thrs[base].pending_cmat; + if (thrs[base].state != HK_WG_CMAT || !cm) + continue; + bool all_ready = true; + for (uint32_t l = 1; l < 32u; ++l) { + if (thrs[base + l].state != HK_WG_CMAT || + thrs[base + l].pending_cmat != cm) { + all_ready = false; + break; + } + } + if (!all_ready) + continue; + + /* AGX 8x8 FP32 tile layout across 32 subgroup lanes: + * row = ((lane >> 1) & 3) | ((lane >> 2) & 4) + * col0 = ((lane & 1) << 1) | ((lane >> 1) & 4), col1 = col0 + 1 */ + float A[8][8], B[8][8], C[8][8]; + for (uint32_t l = 0; l < 32u; ++l) { + uint32_t r = ((l >> 1) & 3u) | ((l >> 2) & 4u); + uint32_t c0 = ((l & 1u) << 1) | ((l >> 1) & 4u); + struct hk_eval_env *e = &thrs[base + l].env; + A[r][c0 + 0] = hk_eval_u2f((uint32_t)hk_eval_read_ssa(e, cm->src[0].ssa, 0)); + A[r][c0 + 1] = hk_eval_u2f((uint32_t)hk_eval_read_ssa(e, cm->src[0].ssa, 1)); + B[r][c0 + 0] = hk_eval_u2f((uint32_t)hk_eval_read_ssa(e, cm->src[1].ssa, 0)); + B[r][c0 + 1] = hk_eval_u2f((uint32_t)hk_eval_read_ssa(e, cm->src[1].ssa, 1)); + C[r][c0 + 0] = hk_eval_u2f((uint32_t)hk_eval_read_ssa(e, cm->src[2].ssa, 0)); + C[r][c0 + 1] = hk_eval_u2f((uint32_t)hk_eval_read_ssa(e, cm->src[2].ssa, 1)); + } + float D[8][8]; + for (unsigned r = 0; r < 8; ++r) { + for (unsigned c = 0; c < 8; ++c) { + float acc = C[r][c]; + for (unsigned k = 0; k < 8; ++k) + acc = fmaf(A[r][k], B[k][c], acc); + D[r][c] = acc; + } + } + for (uint32_t l = 0; l < 32u; ++l) { + uint32_t r = ((l >> 1) & 3u) | ((l >> 2) & 4u); + uint32_t c0 = ((l & 1u) << 1) | ((l >> 1) & 4u); + struct hk_eval_env *e = &thrs[base + l].env; + e->ssa[cm->def.index][0] = hk_eval_f2u(D[r][c0 + 0]); + e->ssa[cm->def.index][1] = hk_eval_f2u(D[r][c0 + 1]); + thrs[base + l].pending_cmat = NULL; + thrs[base + l].state = HK_WG_RUN; + } + resolved_cmat = true; + } + if (resolved_cmat) + continue; + + unsigned n_done = 0, n_bar = 0; + for (uint32_t tid = 0; tid < wg_threads; ++tid) { + if (thrs[tid].state == HK_WG_DONE) + n_done++; + else if (thrs[tid].state == HK_WG_BARRIER) + n_bar++; + } + if (n_done == wg_threads) + break; + if (n_bar == wg_threads) { + for (uint32_t tid = 0; tid < wg_threads; ++tid) + thrs[tid].state = HK_WG_RUN; + continue; + } + HK_EVAL_CHECK(any_run); + } + } + } + } + + free(all_ssa); + free(thrs); + free(shared_mem); +} + #endif diff --git a/src/asahi/vulkan/tests/test-hk-compute-pair.c b/src/asahi/vulkan/tests/test-hk-compute-pair.c index e73daa02ab03..12e7db947dbf 100644 --- a/src/asahi/vulkan/tests/test-hk-compute-pair.c +++ b/src/asahi/vulkan/tests/test-hk-compute-pair.c @@ -786,10 +786,9 @@ run_depthwise_case(bool with_bias_buf, bool with_bias_flag, ssbos[3].data = v4_out; const uint32_t out_pairs = DIV_ROUND_UP((uint32_t)cfg->out_w, 2u); const uint32_t v4_grid[3] = { - DIV_ROUND_UP(out_pairs * ((uint32_t)cfg->channels / 4u), - vec4->info.workgroup_size[0]), - DIV_ROUND_UP((uint32_t)cfg->out_h, vec4->info.workgroup_size[1]), - 1, + DIV_ROUND_UP((uint32_t)cfg->channels / 4u, vec4->info.workgroup_size[0]), + DIV_ROUND_UP(out_pairs, vec4->info.workgroup_size[1]), + DIV_ROUND_UP((uint32_t)cfg->out_h, vec4->info.workgroup_size[2]), }; hk_eval_dispatch(vec4, v4_grid, ssbos, 4, cfg, sizeof(*cfg)); HK_EVAL_CHECK(memcmp(ref_out, v4_out, out_n * sizeof(float)) == 0); @@ -974,10 +973,9 @@ test_unit_axis_wgid_compute_pair(void) ssbos[3].data = v4_out; const uint32_t out_pairs = DIV_ROUND_UP((uint32_t)cfg.out_w, 2u); const uint32_t v4_grid[3] = { - DIV_ROUND_UP(out_pairs * ((uint32_t)cfg.channels / 4u), - vec4->info.workgroup_size[0]), - DIV_ROUND_UP((uint32_t)cfg.out_h, vec4->info.workgroup_size[1]), - 1, + DIV_ROUND_UP((uint32_t)cfg.channels / 4u, vec4->info.workgroup_size[0]), + DIV_ROUND_UP(out_pairs, vec4->info.workgroup_size[1]), + DIV_ROUND_UP((uint32_t)cfg.out_h, vec4->info.workgroup_size[2]), }; hk_eval_dispatch(vec4, v4_grid, ssbos, 4, &cfg, sizeof(cfg)); HK_EVAL_CHECK(memcmp(ref_out, v4_out, out_n * sizeof(float)) == 0); @@ -1282,6 +1280,802 @@ test_gemm_match_and_splice(void) run_gemm_case(8, true, true, false, 20, 13, 5, 0); } +static nir_def * +ssbo_elem_deref_off(nir_builder *b, unsigned set, unsigned binding, + uint32_t base_off_B, nir_def *elem_idx) +{ + const struct glsl_type *arr = glsl_array_type(glsl_float_type(), 0, 4); + struct glsl_struct_field field = { + .type = arr, + .name = "data", + .offset = (int)base_off_B, + }; + const struct glsl_type *iface = + glsl_interface_type(&field, 1, GLSL_INTERFACE_PACKING_STD430, false, "Buf"); + nir_def *res = nir_vulkan_resource_index( + b, 4, 32, nir_imm_int(b, 0), .desc_set = set, .binding = binding, + .desc_type = nir_descriptor_type_storage_buffer); + nir_def *desc = nir_load_vulkan_descriptor( + b, 4, 32, res, .desc_type = nir_descriptor_type_storage_buffer); + nir_deref_instr *blk = + nir_build_deref_cast(b, desc, nir_var_mem_ssbo, iface, 0); + nir_deref_instr *arr_d = nir_build_deref_struct(b, blk, 0); + return &nir_build_deref_array(b, arr_d, elem_idx)->def; +} + +struct gemm_test_opts { + bool guarded; + bool has_bias_buf; + bool has_bias_mode; + uint32_t offset_B; + unsigned fp_math_ctrl; + uint32_t inner_bound; + bool transpose_b; + bool extra_store; + bool preserve_nan; + bool use_ffma; + bool split_bias_stores; + bool early_k_break; + bool early_dot_break; + bool swap_bias_arms; + bool bias_in_mode2; + bool drop_mode0_bias; + bool fixed_row_bias; + /* Guarded: store s_a directly in the guard arms instead of via a phi. */ + bool a_store_in_arms; + /* With a_store_in_arms: extra `if (a_row != 0)` around the then-arm store. */ + bool a_store_inner_if; + /* Wrap the whole C store section in an extra `if (col != 0)`. */ + bool c_store_outer_if; + /* Split stores as `if (mode == 0) ... else if (mode == 1) ... else if (mode == 2)`. */ + bool nested_bias_chain; + /* 32-step unrolled dot product with constant tile columns, no dot loop. */ + bool unroll_dot; + /* With unroll_dot: read the shared tile before barrier_1. */ + bool unroll_early_loads; +}; + +/* barrier_1 followed by a 32-step unrolled dot product over the shared tile: + * acc[r] += s_a[ly * 8 + r][kk] * s_b[kk][lx] for kk = 0..31. With + * unroll_early_loads, the tile reads are emitted before barrier_1 instead. */ +static void +emit_unrolled_dot(nir_builder *b, const struct gemm_test_opts *o, + nir_variable *s_a, nir_variable *s_b, nir_def *lx, + nir_def *ly, nir_variable *const acc[8]) +{ + nir_def *a_ld[32][8], *b_ld[32]; + const bool early = o->unroll_early_loads; + + for (unsigned pass = 0; pass < 2; ++pass) { + const bool load_pass = early ? pass == 0 : pass == 1; + if (pass == 1) + nir_barrier(b, .execution_scope = SCOPE_WORKGROUP, + .memory_scope = SCOPE_WORKGROUP, + .memory_semantics = NIR_MEMORY_ACQ_REL, + .memory_modes = nir_var_mem_shared); + for (unsigned kk = 0; kk < 32; ++kk) { + if (load_pass) { + nir_def *kc = nir_imm_int(b, kk); + b_ld[kk] = nir_load_deref(b, nir_build_deref_array( + b, nir_build_deref_array(b, nir_build_deref_var(b, s_b), kc), lx)); + for (unsigned r = 0; r < 8; ++r) { + nir_def *s_row = nir_iadd_imm(b, nir_ishl_imm(b, ly, 3), r); + a_ld[kk][r] = nir_load_deref(b, nir_build_deref_array( + b, nir_build_deref_array(b, nir_build_deref_var(b, s_a), s_row), kc)); + } + } + if (pass == 0) + continue; + for (unsigned r = 0; r < 8; ++r) { + b->fp_math_ctrl = o->fp_math_ctrl; + nir_def *sum = o->use_ffma + ? nir_ffma(b, a_ld[kk][r], b_ld[kk], nir_load_var(b, acc[r])) + : nir_fadd(b, nir_load_var(b, acc[r]), + nir_fmul(b, a_ld[kk][r], b_ld[kk])); + b->fp_math_ctrl = nir_fp_fast_math; + nir_store_var(b, acc[r], sum, 1); + } + } + } +} + +static nir_shader * +build_tiled_gemm_nir_opts(const struct gemm_test_opts *o) +{ + const bool guarded = o->guarded; + const bool has_bias_buf = o->has_bias_buf; + const bool has_bias_mode = o->has_bias_mode; + const uint32_t offset_B = o->offset_B; + const unsigned fp_math_ctrl = o->fp_math_ctrl; + const uint32_t inner_bound = o->inner_bound ? o->inner_bound : 32; + const bool transpose_b = o->transpose_b; + const bool extra_store = o->extra_store; + const bool preserve_nan = o->preserve_nan; + + nir_shader *s = new_compute_shader("tiled_gemm", 32, 4, 1); + s->info.num_ssbos = has_bias_buf ? 4 : 3; + if (preserve_nan) + s->info.float_controls_execution_mode |= + FLOAT_CONTROLS_DENORM_PRESERVE_FP32; + + nir_variable *s_a = nir_variable_create( + s, nir_var_mem_shared, + glsl_array_type(glsl_array_type(glsl_float_type(), 32, 4), 32, 128), "s_a"); + nir_variable *s_b = nir_variable_create( + s, nir_var_mem_shared, + glsl_array_type(glsl_array_type(glsl_float_type(), 32, 4), 32, 128), "s_b"); + + nir_builder b = nir_builder_at(nir_after_impl(nir_shader_get_entrypoint(s))); + nir_def *gid = nir_load_global_invocation_id(&b, 32); + nir_def *lid = nir_load_local_invocation_id(&b); + nir_def *col = nir_channel(&b, gid, 0); + nir_def *gid_y = nir_channel(&b, gid, 1); + nir_def *lx = nir_channel(&b, lid, 0); + nir_def *ly = nir_channel(&b, lid, 1); + + nir_def *K = load_push_i32(&b, offsetof(struct gemm_push_layout, k)); + nir_def *N = load_push_i32(&b, offsetof(struct gemm_push_layout, n)); + nir_def *M = load_push_i32(&b, offsetof(struct gemm_push_layout, m)); + nir_def *bmode = has_bias_mode + ? load_push_i32(&b, offsetof(struct gemm_push_layout, bias_mode)) + : NULL; + + nir_variable *acc[8]; + for (unsigned r = 0; r < 8; ++r) { + acc[r] = nir_local_variable_create(b.impl, glsl_float_type(), "acc"); + nir_store_var(&b, acc[r], nir_imm_float(&b, 0.0f), 1); + } + nir_variable *tile_v = nir_local_variable_create(b.impl, glsl_int_type(), "t"); + nir_store_var(&b, tile_v, nir_imm_int(&b, 0), 1); + nir_def *num_tiles = nir_idiv(&b, nir_iadd_imm(&b, K, 31), nir_imm_int(&b, 32)); + + nir_push_loop(&b); + { + nir_def *t = nir_load_var(&b, tile_v); + nir_push_if(&b, nir_ige(&b, t, num_tiles)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + if (o->early_k_break) { + nir_push_if(&b, nir_ige_imm(&b, t, 1)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + } + + nir_def *k_base = nir_ishl_imm(&b, t, 5); + for (unsigned j = 0; j < 8; ++j) { + nir_def *s_row = nir_iadd_imm(&b, nir_ishl_imm(&b, ly, 3), j); + nir_def *a_row = nir_iadd_imm(&b, nir_ishl_imm(&b, gid_y, 3), j); + nir_def *a_col = nir_iadd(&b, k_base, lx); + nir_def *a_val = NULL; + if (guarded && o->a_store_in_arms) { + nir_deref_instr *da = + nir_build_deref_array(&b, nir_build_deref_array(&b, nir_build_deref_var(&b, s_a), s_row), lx); + nir_push_if(&b, nir_iand(&b, nir_ilt(&b, a_row, M), nir_ilt(&b, a_col, K))); + nir_def *a_idx = nir_iadd(&b, nir_imul(&b, a_row, K), a_col); + nir_def *ld = nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 0, offset_B, a_idx))); + if (o->a_store_inner_if) + nir_push_if(&b, nir_ine_imm(&b, a_row, 0)); + nir_store_deref(&b, da, ld, 1); + if (o->a_store_inner_if) + nir_pop_if(&b, NULL); + nir_push_else(&b, NULL); + nir_store_deref(&b, da, nir_imm_float(&b, 0.0f), 1); + nir_pop_if(&b, NULL); + } else if (guarded) { + nir_variable *av = nir_local_variable_create(b.impl, glsl_float_type(), "av"); + nir_push_if(&b, nir_iand(&b, nir_ilt(&b, a_row, M), nir_ilt(&b, a_col, K))); + nir_def *a_idx = nir_iadd(&b, nir_imul(&b, a_row, K), a_col); + nir_store_var(&b, av, + nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 0, offset_B, a_idx))), 1); + nir_push_else(&b, NULL); + nir_store_var(&b, av, nir_imm_float(&b, 0.0f), 1); + nir_pop_if(&b, NULL); + a_val = nir_load_var(&b, av); + } else { + nir_def *a_idx = nir_iadd(&b, nir_imul(&b, a_row, K), a_col); + a_val = nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 0, offset_B, a_idx))); + } + if (a_val) { + nir_deref_instr *da = + nir_build_deref_array(&b, nir_build_deref_array(&b, nir_build_deref_var(&b, s_a), s_row), lx); + nir_store_deref(&b, da, a_val, 1); + } + + nir_def *b_row = nir_iadd(&b, k_base, s_row); + nir_def *b_val; + nir_def *b_idx = transpose_b + ? nir_iadd(&b, nir_imul(&b, col, K), b_row) + : nir_iadd(&b, nir_imul(&b, b_row, N), col); + if (guarded) { + nir_variable *bv = nir_local_variable_create(b.impl, glsl_float_type(), "bv"); + nir_push_if(&b, nir_iand(&b, nir_ilt(&b, b_row, K), nir_ilt(&b, col, N))); + nir_store_var(&b, bv, + nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 1, offset_B, b_idx))), 1); + nir_push_else(&b, NULL); + nir_store_var(&b, bv, nir_imm_float(&b, 0.0f), 1); + nir_pop_if(&b, NULL); + b_val = nir_load_var(&b, bv); + } else { + b_val = nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 1, offset_B, b_idx))); + } + nir_deref_instr *db = + nir_build_deref_array(&b, nir_build_deref_array(&b, nir_build_deref_var(&b, s_b), s_row), lx); + nir_store_deref(&b, db, b_val, 1); + } + + if (extra_store) { + nir_store_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 3, offset_B, nir_imm_int(&b, 0))), + nir_imm_float(&b, 0.0f), 1); + } + + if (o->unroll_dot) { + emit_unrolled_dot(&b, o, s_a, s_b, lx, ly, acc); + } else { + nir_barrier(&b, .execution_scope = SCOPE_WORKGROUP, + .memory_scope = SCOPE_WORKGROUP, + .memory_semantics = NIR_MEMORY_ACQ_REL, + .memory_modes = nir_var_mem_shared); + + nir_variable *lv = nir_local_variable_create(b.impl, glsl_int_type(), "l"); + nir_store_var(&b, lv, nir_imm_int(&b, 0), 1); + nir_push_loop(&b); + { + nir_def *l = nir_load_var(&b, lv); + nir_push_if(&b, nir_ige_imm(&b, l, inner_bound)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + if (o->early_dot_break) { + nir_push_if(&b, nir_ige_imm(&b, l, 16)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + } + + nir_deref_instr *db = + nir_build_deref_array(&b, nir_build_deref_array(&b, nir_build_deref_var(&b, s_b), l), lx); + nir_def *bv = nir_load_deref(&b, db); + for (unsigned r = 0; r < 8; ++r) { + nir_def *s_row = nir_iadd_imm(&b, nir_ishl_imm(&b, ly, 3), r); + nir_deref_instr *da = + nir_build_deref_array(&b, nir_build_deref_array(&b, nir_build_deref_var(&b, s_a), s_row), l); + nir_def *av = nir_load_deref(&b, da); + b.fp_math_ctrl = fp_math_ctrl; + nir_def *sum; + if (o->use_ffma) { + sum = nir_ffma(&b, av, bv, nir_load_var(&b, acc[r])); + } else { + nir_def *prod = nir_fmul(&b, av, bv); + sum = nir_fadd(&b, nir_load_var(&b, acc[r]), prod); + } + b.fp_math_ctrl = nir_fp_fast_math; + nir_store_var(&b, acc[r], sum, 1); + } + nir_store_var(&b, lv, nir_iadd_imm(&b, l, 1), 1); + } + nir_pop_loop(&b, NULL); + } + + 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_var(&b, tile_v, nir_iadd_imm(&b, t, 1), 1); + } + nir_pop_loop(&b, NULL); + + nir_def *row_base = nir_ishl_imm(&b, nir_channel(&b, gid, 1), 3); + nir_def *col_ok = guarded ? nir_ilt(&b, col, N) : nir_imm_true(&b); + if (o->c_store_outer_if) + nir_push_if(&b, nir_ine_imm(&b, col, 0)); + if (has_bias_buf && has_bias_mode && o->split_bias_stores) { + for (unsigned arm = 0; arm < 3; ++arm) { + nir_if *arm_if = nir_push_if(&b, nir_ieq_imm(&b, bmode, arm)); + for (unsigned r = 0; r < 8; ++r) { + nir_def *row = nir_iadd_imm(&b, row_base, r); + if (guarded) + nir_push_if(&b, nir_iand(&b, nir_ilt(&b, row, M), col_ok)); + nir_def *val = nir_load_var(&b, acc[r]); + nir_def *b_idx = NULL; + if (arm == 0 && !o->drop_mode0_bias) + b_idx = o->swap_bias_arms ? col : row; + else if (arm == 1) + b_idx = o->swap_bias_arms ? row : col; + else if (arm == 2 && o->bias_in_mode2) + b_idx = row; + if (b_idx) { + nir_def *bv = nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 2, offset_B, b_idx))); + val = nir_fadd(&b, val, bv); + } + nir_def *o_idx = nir_iadd(&b, nir_imul(&b, row, N), col); + nir_store_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 3, offset_B, o_idx)), val, 1); + if (guarded) + nir_pop_if(&b, NULL); + } + if (o->nested_bias_chain && arm < 2) + nir_push_else(&b, arm_if); + else + nir_pop_if(&b, NULL); + } + if (o->nested_bias_chain) { + nir_pop_if(&b, NULL); + nir_pop_if(&b, NULL); + } + } else { + for (unsigned r = 0; r < 8; ++r) { + nir_def *row = nir_iadd_imm(&b, row_base, r); + if (guarded) + nir_push_if(&b, nir_iand(&b, nir_ilt(&b, row, M), col_ok)); + + nir_def *val = nir_load_var(&b, acc[r]); + if (has_bias_buf) { + if (has_bias_mode) { + nir_push_if(&b, nir_ieq_imm(&b, bmode, 0)); + { + if (!o->drop_mode0_bias) { + nir_def *bv = nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 2, offset_B, + o->swap_bias_arms ? col : row))); + nir_store_var(&b, acc[r], nir_fadd(&b, val, bv), 1); + } + } + nir_push_else(&b, NULL); + { + nir_push_if(&b, nir_ieq_imm(&b, bmode, 1)); + { + nir_def *bv = nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 2, offset_B, + o->swap_bias_arms ? row : col))); + nir_store_var(&b, acc[r], nir_fadd(&b, val, bv), 1); + } + nir_push_else(&b, NULL); + { + if (o->bias_in_mode2) { + nir_def *bv = nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 2, offset_B, row))); + nir_store_var(&b, acc[r], nir_fadd(&b, val, bv), 1); + } + } + nir_pop_if(&b, NULL); + } + nir_pop_if(&b, NULL); + val = nir_load_var(&b, acc[r]); + } else { + nir_def *bv = nir_load_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 2, offset_B, + o->fixed_row_bias ? row : col))); + val = nir_fadd(&b, val, bv); + } + } + + nir_def *o_idx = nir_iadd(&b, nir_imul(&b, row, N), col); + nir_store_deref(&b, nir_def_as_deref( + ssbo_elem_deref_off(&b, 0, 3, offset_B, o_idx)), val, 1); + + if (guarded) + nir_pop_if(&b, NULL); + } + } + if (o->c_store_outer_if) + nir_pop_if(&b, NULL); + + NIR_PASS(_, s, nir_lower_vars_to_ssa); + NIR_PASS(_, s, nir_opt_dce); + nir_validate_shader(s, "build_tiled_gemm_nir"); + return s; +} + +static bool +shader_has_cmat_muladd(const nir_shader *s) +{ + nir_foreach_function_impl(impl, s) { + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + if (instr->type == nir_instr_type_intrinsic && + nir_instr_as_intrinsic(instr)->intrinsic == + nir_intrinsic_cmat_muladd_agx) + return true; + } + } + } + return false; +} + +static uint32_t +gemm_test_lcg(uint32_t *state) +{ + *state = *state * 1664525u + 1013904223u; + return *state; +} + +static float +gemm_test_rand_f32(uint32_t *state) +{ + uint32_t r = gemm_test_lcg(state); + if ((r & 0x3fu) == 0) + return 0.0f; + if ((r & 0x7fu) == 1) + return -0.0f; + if ((r & 0xffu) == 2) + return 1e-40f; /* subnormal */ + int32_t s = (int32_t)(r >> 12) - (1 << 19); + return (float)s * (1.0f / 131072.0f); +} + +/* Runs the original and the cmat alternate of `opts` through the CPU + * workgroup evaluator and returns how many C elements differ bitwise. + * seed == 0 feeds all-1.0f inputs and pre-fills C with -99.0f. With + * `force_uncertified`, the shader must match as a GEMM but fail certification + * (cmat_valid == false); the alternate is then built anyway to show what + * certifying it would have produced. */ +static unsigned +gemm_eval_mismatches(const struct gemm_test_opts *opts, uint32_t M, + uint32_t N, uint32_t K, int32_t bias_mode, + size_t runtime_a_off, size_t runtime_b_off, + uint32_t tile_n, + const struct hk_nir_clamp_epilogue *epilogue, + uint32_t seed, bool force_uncertified) +{ + nir_shader *orig = build_tiled_gemm_nir_opts(opts); + nir_shader *pre = nir_shader_clone(NULL, orig); + run_hk_preprocess_for_test(pre, false); + + struct hk_nir_gemm_output m = {0}; + HK_EVAL_CHECK(hk_nir_match_gemm_output( + pre, nir_address_format_64bit_global_32bit_offset, &m)); + HK_EVAL_CHECK(m.cmat_valid != force_uncertified); + m.cmat_valid = true; + + nir_shader *alt = hk_nir_build_gemm_cmat(pre, &m, tile_n, epilogue); + HK_EVAL_CHECK(alt); + nir_validate_shader(alt, "gemm_cmat_eval_alt"); + HK_EVAL_CHECK(shader_has_cmat_muladd(alt)); + + const uint32_t off_elems = opts->offset_B / 4u; + const size_t a_elems = (size_t)M * K + off_elems; + const size_t b_elems = (size_t)K * N + off_elems; + const size_t bias_elems = (size_t)(M > N ? M : N) + off_elems + 1; + const size_t c_elems = (size_t)M * N + off_elems; + + float *a_buf = calloc(a_elems, sizeof(float)); + float *b_buf = calloc(b_elems, sizeof(float)); + float *bias_buf = calloc(bias_elems, sizeof(float)); + float *c_orig = calloc(c_elems, sizeof(float)); + float *c_alt = calloc(c_elems, sizeof(float)); + HK_EVAL_CHECK(a_buf && b_buf && bias_buf && c_orig && c_alt); + + uint32_t rng = seed; + for (size_t i = off_elems; i < a_elems; ++i) + a_buf[i] = seed ? gemm_test_rand_f32(&rng) : 1.0f; + for (size_t i = off_elems; i < b_elems; ++i) + b_buf[i] = seed ? gemm_test_rand_f32(&rng) : 1.0f; + for (size_t i = off_elems; i < bias_elems; ++i) + bias_buf[i] = seed ? gemm_test_rand_f32(&rng) : 1.0f; + for (size_t i = 0; i < c_elems; ++i) { + if (i < off_elems || !seed) { + c_orig[i] = seed ? -123.5f : -99.0f; + c_alt[i] = c_orig[i]; + } + } + + struct gemm_push_layout push = { + .k = (int32_t)K, + .n = (int32_t)N, + .m = (int32_t)M, + .bias_mode = bias_mode, + }; + + const uint32_t orig_grid[3] = { + (N + 31u) / 32u, + (M + 31u) / 32u, + 1u, + }; + HK_EVAL_CHECK(hk_gemm_cmat_dispatch_dims_ok(opts->guarded, M, N, K, orig_grid)); + + struct hk_eval_ssbo ssbos_orig[4] = { + { 0, 0, a_buf, a_elems * sizeof(float), runtime_a_off }, + { 0, 1, b_buf, b_elems * sizeof(float), runtime_b_off }, + { 0, 2, bias_buf, bias_elems * sizeof(float), runtime_b_off }, + { 0, 3, c_orig, c_elems * sizeof(float), runtime_b_off }, + }; + hk_eval_dispatch_wg(orig, orig_grid, ssbos_orig, 4, &push, sizeof(push)); + + if (epilogue) { + float lo = hk_eval_u2f(epilogue->lower_bits); + float hi = hk_eval_u2f(epilogue->upper_bits); + for (size_t i = off_elems; i < c_elems; ++i) { + float v = c_orig[i]; + if (epilogue->upper_first) { + if (epilogue->has_upper) v = fminf(v, hi); + if (epilogue->has_lower) v = fmaxf(v, lo); + } else { + if (epilogue->has_lower) v = fmaxf(v, lo); + if (epilogue->has_upper) v = fminf(v, hi); + } + c_orig[i] = v; + } + } + + const uint32_t alt_grid[3] = { + (N + tile_n - 1u) / tile_n, + (M + 63u) / 64u, + 1u, + }; + struct hk_eval_ssbo ssbos_alt[4] = { + { 0, 0, a_buf, a_elems * sizeof(float), runtime_a_off }, + { 0, 1, b_buf, b_elems * sizeof(float), runtime_b_off }, + { 0, 2, bias_buf, bias_elems * sizeof(float), runtime_b_off }, + { 0, 3, c_alt, c_elems * sizeof(float), runtime_b_off }, + }; + hk_eval_dispatch_wg(alt, alt_grid, ssbos_alt, 4, &push, sizeof(push)); + + unsigned mismatches = 0; + for (size_t i = 0; i < c_elems; ++i) { + uint32_t uo = hk_eval_f2u(c_orig[i]); + uint32_t ua = hk_eval_f2u(c_alt[i]); + if (uo != ua) { + if (!mismatches) + fprintf(stderr, + "GEMM eval %s (M=%u N=%u K=%u bmode=%d tile_n=%u off=%u): " + "first idx=%zu orig=0x%08x (%g) alt=0x%08x (%g)\n", + force_uncertified ? "mismatch (uncertified, expected)" : "mismatch", + M, N, K, bias_mode, tile_n, opts->offset_B, i, uo, c_orig[i], + ua, c_alt[i]); + mismatches++; + } + } + + free(a_buf); + free(b_buf); + free(bias_buf); + free(c_orig); + free(c_alt); + ralloc_free(alt); + ralloc_free(pre); + ralloc_free(orig); + return mismatches; +} + +static void +eval_compare_gemm_case(const struct gemm_test_opts *opts, uint32_t M, + uint32_t N, uint32_t K, int32_t bias_mode, + size_t runtime_a_off, size_t runtime_b_off, + uint32_t tile_n, + const struct hk_nir_clamp_epilogue *epilogue, + uint32_t seed) +{ + HK_EVAL_CHECK(gemm_eval_mismatches(opts, M, N, K, bias_mode, runtime_a_off, + runtime_b_off, tile_n, epilogue, seed, + false) == 0); +} + +static void +test_gemm_cmat_certify_and_build(void) +{ + const struct hk_nir_clamp_epilogue ep = { + .has_lower = true, .has_upper = true, .upper_first = false, + .lower_bits = 0x00000000u, .upper_bits = 0x40c00000u, + .max_fp_math_ctrl = nir_fp_preserve_inf, + .min_fp_math_ctrl = nir_fp_preserve_inf, + }; + + const struct gemm_test_opts pos_cases[] = { + { .guarded = false, .has_bias_buf = true, .has_bias_mode = true, .offset_B = 0 }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .offset_B = 0 }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .offset_B = 4, .split_bias_stores = true }, + { .guarded = false, .has_bias_buf = true, .has_bias_mode = true, .offset_B = 16, .split_bias_stores = true }, + { .guarded = false, .has_bias_buf = false, .has_bias_mode = false, .offset_B = 0 }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = false, .offset_B = 16 }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = false, .offset_B = 4, .fixed_row_bias = true }, + }; + + for (unsigned i = 0; i < ARRAY_SIZE(pos_cases); ++i) { + nir_shader *orig = build_tiled_gemm_nir_opts(&pos_cases[i]); + + nir_shader *g17p = nir_shader_clone(NULL, orig); + run_hk_preprocess_for_test(g17p, false); + struct hk_nir_gemm_output m_g17p = {0}; + HK_EVAL_CHECK(hk_nir_match_gemm_output( + g17p, nir_address_format_64bit_global_32bit_offset, &m_g17p)); + HK_EVAL_CHECK(m_g17p.cmat_valid); + HK_EVAL_CHECK(m_g17p.output.offset_B == pos_cases[i].offset_B); + HK_EVAL_CHECK(m_g17p.reads[0].offset_B == pos_cases[i].offset_B); + HK_EVAL_CHECK(m_g17p.reads[1].offset_B == pos_cases[i].offset_B); + HK_EVAL_CHECK(m_g17p.desc_comps == 4); + + for (unsigned t = 0; t < 2; ++t) { + const uint32_t tile_n = t ? 64 : 32; + nir_shader *cmat = hk_nir_build_gemm_cmat(g17p, &m_g17p, tile_n, NULL); + HK_EVAL_CHECK(cmat); + nir_validate_shader(cmat, "gemm_cmat"); + HK_EVAL_CHECK(shader_has_cmat_muladd(cmat)); + ralloc_free(cmat); + + nir_shader *cmat_ep = hk_nir_build_gemm_cmat(g17p, &m_g17p, tile_n, &ep); + HK_EVAL_CHECK(cmat_ep); + nir_validate_shader(cmat_ep, "gemm_cmat_ep"); + HK_EVAL_CHECK(shader_has_cmat_muladd(cmat_ep)); + ralloc_free(cmat_ep); + } + ralloc_free(g17p); + + nir_shader *m5 = nir_shader_clone(NULL, orig); + rewrite_ssbo_desc_comps(m5, 5); + run_hk_preprocess_for_test(m5, true); + struct hk_nir_gemm_output m_m5 = {0}; + HK_EVAL_CHECK(hk_nir_match_gemm_output( + m5, nir_address_format_64bit_global_32bit_offset_map, &m_m5)); + HK_EVAL_CHECK(m_m5.cmat_valid); + HK_EVAL_CHECK(m_m5.desc_comps == 5); + nir_shader *cmat_m5 = hk_nir_build_gemm_cmat(m5, &m_m5, 64, &ep); + HK_EVAL_CHECK(cmat_m5); + nir_validate_shader(cmat_m5, "gemm_cmat_m5"); + HK_EVAL_CHECK(shader_has_cmat_muladd(cmat_m5)); + ralloc_free(cmat_m5); + ralloc_free(m5); + + ralloc_free(orig); + } + + /* Negative certifier cases: cmat_valid MUST be false (or unmatched). */ + const struct gemm_test_opts neg_cases[] = { + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .fp_math_ctrl = nir_fp_preserve_nan }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .preserve_nan = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .inner_bound = 31 }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .transpose_b = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .extra_store = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .early_k_break = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .early_dot_break = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .split_bias_stores = true, .swap_bias_arms = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .split_bias_stores = true, .bias_in_mode2 = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .split_bias_stores = true, .drop_mode0_bias = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .swap_bias_arms = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .bias_in_mode2 = true }, + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .drop_mode0_bias = true }, + { .guarded = false, .has_bias_buf = false, .has_bias_mode = false, .offset_B = 4 }, + }; + for (unsigned i = 0; i < ARRAY_SIZE(neg_cases); ++i) { + nir_shader *bad = build_tiled_gemm_nir_opts(&neg_cases[i]); + run_hk_preprocess_for_test(bad, false); + struct hk_nir_gemm_output m_bad = {0}; + bool matched = hk_nir_match_gemm_output( + bad, nir_address_format_64bit_global_32bit_offset, &m_bad); + HK_EVAL_CHECK(!matched || !m_bad.cmat_valid); + ralloc_free(bad); + } + + /* Dispatch dimension gate: unguarded K = 16 mod 32 MUST be refused. */ + const uint32_t g64x64[3] = { 2, 2, 1 }; + const uint32_t g32x64[3] = { 1, 2, 1 }; + HK_EVAL_CHECK(!hk_gemm_cmat_dispatch_dims_ok(false, 64, 64, 48, g64x64)); + HK_EVAL_CHECK(!hk_gemm_cmat_dispatch_dims_ok(false, 64, 64, 16, g64x64)); + HK_EVAL_CHECK( hk_gemm_cmat_dispatch_dims_ok(false, 64, 64, 32, g64x64)); + HK_EVAL_CHECK( hk_gemm_cmat_dispatch_dims_ok(false, 64, 32, 64, g32x64)); + HK_EVAL_CHECK( hk_gemm_cmat_dispatch_dims_ok(true, 64, 64, 48, g64x64)); + HK_EVAL_CHECK( hk_gemm_cmat_dispatch_dims_ok(true, 37, 35, 19, g64x64)); + + /* Original vs alternate bit-exact NIR evaluation on random FP32 inputs. */ + const struct gemm_test_opts o_guarded_dyn = { + .guarded = true, .has_bias_buf = true, .has_bias_mode = true, .use_ffma = true, + }; + const struct gemm_test_opts o_guarded_split_off4 = { + .guarded = true, .has_bias_buf = true, .has_bias_mode = true, + .offset_B = 4, .use_ffma = true, .split_bias_stores = true, + }; + const struct gemm_test_opts o_unguarded_dyn = { + .guarded = false, .has_bias_buf = true, .has_bias_mode = true, + .offset_B = 16, .use_ffma = true, + }; + const struct gemm_test_opts o_unguarded_split = { + .guarded = false, .has_bias_buf = true, .has_bias_mode = true, + .use_ffma = true, .split_bias_stores = true, + }; + const struct gemm_test_opts o_guarded_fixed_row = { + .guarded = true, .has_bias_buf = true, .has_bias_mode = false, + .use_ffma = true, .fixed_row_bias = true, + }; + const struct gemm_test_opts o_guarded_fixed_col = { + .guarded = true, .has_bias_buf = true, .has_bias_mode = false, + .use_ffma = true, + }; + const struct gemm_test_opts o_guarded_nobias = { + .guarded = true, .has_bias_buf = false, .has_bias_mode = false, + .use_ffma = true, + }; + + for (int bm = 0; bm <= 2; ++bm) { + eval_compare_gemm_case(&o_guarded_dyn, 37, 35, 19, bm, 4, 4, 32, NULL, 100u + bm); + eval_compare_gemm_case(&o_guarded_dyn, 67, 69, 48, bm, 4, 4, 64, &ep, 200u + bm); + eval_compare_gemm_case(&o_guarded_split_off4, 33, 41, 20, bm, 4, 4, 64, NULL, 300u + bm); + } + eval_compare_gemm_case(&o_guarded_split_off4, 71, 29, 48, 0, 4, 4, 32, &ep, 350u); + + for (int bm = 0; bm <= 2; ++bm) { + eval_compare_gemm_case(&o_unguarded_dyn, 64, 64, 32, bm, 0, 4, 64, NULL, 400u + bm); + eval_compare_gemm_case(&o_unguarded_split, 64, 32, 64, bm, 0, 4, 32, &ep, 500u + bm); + } + + eval_compare_gemm_case(&o_guarded_fixed_row, 23, 39, 33, 0, 4, 4, 64, &ep, 600u); + eval_compare_gemm_case(&o_guarded_fixed_col, 23, 39, 33, 1, 4, 4, 32, NULL, 601u); + eval_compare_gemm_case(&o_guarded_nobias, 19, 25, 17, 2, 4, 4, 32, &ep, 602u); + + /* Shapes the certifier must keep accepting: shared stores directly in the + * guard arms, split stores under an if/else-if bias_mode chain, and the + * unrolled dot product. */ + const struct gemm_test_opts o_a_store_in_arms = { + .guarded = true, .has_bias_buf = true, .has_bias_mode = true, + .use_ffma = true, .a_store_in_arms = true, + }; + const struct gemm_test_opts o_nested_chain = { + .guarded = true, .has_bias_buf = true, .has_bias_mode = true, + .use_ffma = true, .split_bias_stores = true, .nested_bias_chain = true, + }; + const struct gemm_test_opts o_unroll_dot = { + .guarded = true, .has_bias_buf = true, .has_bias_mode = true, + .use_ffma = true, .unroll_dot = true, + }; + for (int bm = 0; bm <= 2; ++bm) { + eval_compare_gemm_case(&o_a_store_in_arms, 37, 35, 19, bm, 4, 4, 32, NULL, 700u + bm); + eval_compare_gemm_case(&o_nested_chain, 33, 41, 20, bm, 4, 4, 64, &ep, 710u + bm); + eval_compare_gemm_case(&o_unroll_dot, 37, 35, 48, bm, 4, 4, 32, NULL, 720u + bm); + } + + /* Control-flow negative controls. Each shape matches as a GEMM but adds + * a predicate (or a read order) the cmat alternate does not reproduce, so + * it must not certify; built anyway, its alternate differs from the + * original on M=64 N=32 K=32 all-1.0f inputs with C pre-filled to -99.0f. + * Each is paired with the same shape without the defect, which certifies + * and matches bit-exactly on the same inputs. */ + const struct { + const char *name; + struct gemm_test_opts bad; + int32_t bias_mode; + unsigned expect; /* forced-alternate mismatches; 0 = any nonzero */ + } cf_cases[] = { + /* s_a store inside `if (a_row != 0)` in the guard's then-arm: matrix + * row 0 stays 0.0 in the original, 32.0 in the alternate. */ + { "shared store in inner if", + { .guarded = true, .use_ffma = true, .a_store_in_arms = true, + .a_store_inner_if = true }, 2, 32 }, + /* C stores under `if (col != 0)`: the original keeps column 0 at + * -99.0, the alternate writes all 64 rows of it. */ + { "C stores in outer if, guarded", + { .guarded = true, .use_ffma = true, .c_store_outer_if = true }, 2, 64 }, + { "C stores in outer if, unguarded", + { .guarded = false, .use_ffma = true, .c_store_outer_if = true }, 2, 64 }, + { "split C stores in outer if", + { .guarded = true, .has_bias_buf = true, .has_bias_mode = true, + .use_ffma = true, .split_bias_stores = true, + .c_store_outer_if = true }, 0, 64 }, + /* Unrolled dot product reading the tile before barrier_1. */ + { "tile read before barrier", + { .guarded = true, .use_ffma = true, .unroll_dot = true, + .unroll_early_loads = true }, 2, 0 }, + }; + for (unsigned i = 0; i < ARRAY_SIZE(cf_cases); ++i) { + struct gemm_test_opts good = cf_cases[i].bad; + good.a_store_inner_if = false; + good.c_store_outer_if = false; + good.unroll_early_loads = false; + HK_EVAL_CHECK(gemm_eval_mismatches(&good, 64, 32, 32, + cf_cases[i].bias_mode, 0, 0, 32, + NULL, 0, false) == 0); + const unsigned diff = + gemm_eval_mismatches(&cf_cases[i].bad, 64, 32, 32, + cf_cases[i].bias_mode, 0, 0, 32, NULL, 0, true); + printf("gemm cmat negative control '%s': not certified; forced " + "alternate differs in %u outputs\n", cf_cases[i].name, diff); + HK_EVAL_CHECK(cf_cases[i].expect ? diff == cf_cases[i].expect : diff > 0); + } +} + int main(void) { @@ -1292,6 +2086,7 @@ main(void) test_depthwise_vec4_and_fusion(); test_gemm_match_and_splice(); test_unit_axis_wgid_compute_pair(); + test_gemm_cmat_certify_and_build(); glsl_type_singleton_decref(); printf("test-hk-compute-pair: PASS\n"); return 0;