From 114f108ea41264b80fe6d7e976f31169a1b876cb Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:07:03 +0100 Subject: [PATCH 1/2] shader: lower uniform scalar loops in the mesh frontend The mesh frontend emitted DXIL in one forward pass and refused every back edge. Accept one narrow shape: one header, one back edge (s_cbranch_scc0, s_cbranch_scc1 or s_branch), and a body of the 32-bit scalar ALU that is already allowed between a diamond join and its EXEC restore, scalar compares, scalar loads, waits and forward exits past the back edge inside the enclosing EXECZ region. The pass stays forward-only: registers the body writes after reading them, and SCC, live in local slots stored before the header and at the back edge and loaded in the header. A register the body only writes is unbound in the header; one it never writes keeps its entry value. Exits use the existing forward-join merge. Every other loop keeps a named refusal. The scalar ALU list moves to function scope so the loop check and the post-join check share it. Co-Authored-By: Claude Opus 5.5 --- docs/experiments/native-mesh-scalar-loop.md | 54 +++++++++ src/gfx1013_direct_mesh.inl | 128 ++++++++++++++++++-- tests/native_direct_mesh_check.py | 42 +++++++ 3 files changed, 212 insertions(+), 12 deletions(-) create mode 100644 docs/experiments/native-mesh-scalar-loop.md diff --git a/docs/experiments/native-mesh-scalar-loop.md b/docs/experiments/native-mesh-scalar-loop.md new file mode 100644 index 0000000000..949b76dda5 --- /dev/null +++ b/docs/experiments/native-mesh-scalar-loop.md @@ -0,0 +1,54 @@ +# Uniform scalar loops in the mesh frontend + +The C++ mesh frontend (`lower_mesh`) emits DXIL in one forward pass, so it accepted only forward branches. It now also +accepts one narrow loop shape, a *uniform scalar loop*. The loop has one header and one back edge +(`s_cbranch_scc0`, `s_cbranch_scc1` or `s_branch`). The body contains only: + +- the 32-bit scalar ALU already allowed between a diamond join and its EXEC restore; +- scalar compares; +- scalar loads (`s_load_dword*`, `s_buffer_load_dword*`); +- `s_waitcnt`, `s_nop` and `s_clause`; +- forward exits (`s_cbranch_scc0/scc1`) past the back edge, inside the enclosing EXECZ region. + +The pass stays forward-only. A register the body writes and reads before that write carries a value into the next +iteration; it lives in a local slot, as does SCC. The slots are stored before the header and at the back edge, and +loaded in the header. In the header these registers become plain numbers. A register the body only writes is +unbound there; a register the body never writes keeps its entry value. The exits use the existing forward-join +merge. The trip count comes from guest data, as on the GPU. + +The following keep a refusal: + +| Case | Refusal | +|---|---| +| Two back edges to one header | `mesh loop needs exactly one back edge` | +| A vector, LDS, EXEC or export instruction in the body | `mesh loop body holds an unsupported instruction: ` | +| A back edge on VCC or EXEC | `mesh loop back edge needs SCC or an unconditional branch` | +| A branch into the body other than at the header | `mesh loop is entered other than at its header` | +| A loop after GS_ALLOC_REQ, under a per-lane else, or outside full EXEC and any EXECZ region | `mesh loop outside a uniform scalar region` | +| A carried register without a numeric entry value | `mesh loop carries a register without a numeric entry value: sN` | + +## Checks + +`tests/native_direct_mesh_check.py`, `scalar-loop`: a source-built loop counts s20 from 0 while it is below the root +constant s21, and leaves early when s20 is 5. The two exits set s20 to 7 or 9 and join before the export reads s20. +The IR check covers: + +- only s20 and SCC get slots; +- s20 is stored twice, before the header and at the back edge; +- the back edge branches on SCC == 0; +- the body compares with 5 and with s21. + +`scalar-loop-branch-back` uses an unconditional `s_branch` back edge. Its only exit is the early one, and it emits +no exit block after the back edge. The four refusals above have a case each: `scalar-loop-vector`, `-vcc-back`, `-two-back`, `-enter-body`. + +Controls: + +- Without the frontend change, `scalar-loop` fails with `unsupported mesh scalar branch destination`. +- With the back-edge stores removed, the store count assertion fails. + +## Local requests + +In 18 captured slot 86 mesh requests, the same loop searches records of 0x130 bytes for a flag bit, bounded by dword +0 of root SRV 3 (#3703). With #3702 and #3704 applied, all 18 now pass the loop without any stand-in. Their next +refusal is `mesh image load lacks a remapped Texture1D heap contract` (item 4 of #3703). These are counts only, from +`compile_dxil gfx1013-container-ms-texture-heap .m86 .cso`. diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 575612d031..74e1472fac 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -743,7 +743,105 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout exec_value[0]=mask.words[0]; exec_value[1]=mask.words[1]; }; std::optional pending_saveexec_restore; + // SGPRs, M0, null, inline and literal constants, and SCC; not VCC, EXEC, VCCZ or EXECZ. + const auto lane_free=[](unsigned s) { return s<106 || s==124 || s==125 || (s>=128 && s<=250) || s==253 || s==255; }; + // 32-bit scalar ALU only: no 64-bit mask forms, calls, register writes or relative moves. + static const std::set scalar_alu32{ + "s_mov_b32","s_not_b32","s_brev_b32","s_movk_i32","s_addk_i32","s_mulk_i32", + "s_add_u32","s_sub_u32","s_add_i32","s_sub_i32","s_addc_u32","s_subb_u32","s_mul_i32", + "s_mul_hi_u32","s_mul_hi_i32","s_min_i32","s_min_u32","s_max_i32","s_max_u32","s_absdiff_i32", + "s_cselect_b32","s_and_b32","s_or_b32","s_xor_b32","s_andn2_b32","s_orn2_b32","s_nand_b32", + "s_nor_b32","s_xnor_b32","s_lshl_b32","s_lshr_b32","s_ashr_i32","s_bfm_b32","s_bfe_u32", + "s_bfe_i32","s_lshl1_add_u32","s_lshl2_add_u32","s_lshl3_add_u32","s_lshl4_add_u32", + "s_pack_ll_b32_b16","s_pack_lh_b32_b16","s_pack_hh_b32_b16"}; + // A uniform scalar loop (#3703): one header, one back edge (s_cbranch_scc0/scc1 or s_branch), and a body of + // the scalar ALU above, scalar compares, scalar loads, waits and forward exits past the back edge. The pass + // stays forward-only: registers the body reads before it writes them, and SCC, live in local slots that are + // stored before the header and at the back edge and loaded in the header. + std::map> back_edges; + for (unsigned at=0;at>16)&127; + if ((w&0xff800000u)==0xbf800000u && (sopp==2 || (sopp>=4 && sopp<=9))) { + const int64_t target=int64_t(at)+4+4*int64_t(int16_t(w&0xffff)); + if (target>=0 && target<=int64_t(at)) back_edges[unsigned(target)].push_back(at); + } + at+=op.size; + } + struct MeshLoop { unsigned head, back; std::vector> slots; }; + std::optional loop; unsigned pc = 0; + auto open_loop=[&](const std::vector &backs) { + const unsigned head=pc, back=backs.front(); + if (backs.size()!=1) refuse(head,"mesh loop needs exactly one back edge"); + if (lane_else || branch || allocated || (!full_exec && !exec_skip) || (exec_skip && back>=exec_skip->end)) + refuse(head,"mesh loop outside a uniform scalar region"); + for (const auto &edge : forward) + if (edge.first>head && edge.first<=back) refuse(head,"mesh loop is entered other than at its header"); + // A register the body writes, and reads before that write in one pass, carries a value into the next + // iteration. A register the body never writes keeps its entry value. + std::set written, read_first, carried; + const auto read=[&](unsigned r) { if (r<106 && !written.count(r)) read_first.insert(r); }; + unsigned at=head; + while (at<=back) { + const auto i=decode(code,at,true,true); + const string name(i.name); + if (i.enc==Encoding::Smem) { + const unsigned offset_reg=i.b>>25, count=memory_count(i); + if (!(i.op<=4 || (i.op>=8 && i.op<=12)) || i.dst+count>106 || i.src[0]>=104 || + (offset_reg!=125 && offset_reg>=106)) + refuse(at,"mesh loop body holds an unsupported scalar load"); + for (unsigned j=0;j<(i.op>=8 ? 4u : 2u);++j) read(i.src[0]+j); + if (offset_reg!=125) read(offset_reg); + for (unsigned j=0;j=code.size() || (exec_skip && i.target()>exec_skip->end)) + refuse(at,"mesh loop exit must branch forward past the back edge"); + } else if (i.enc==Encoding::Sopc && (name.rfind("s_cmp",0)==0 || name.rfind("s_bitcmp",0)==0) && + lane_free(i.src[0]) && lane_free(i.src[1])) { + read(i.src[0]); read(i.src[1]); + } else if ((i.enc==Encoding::Sop1 || i.enc==Encoding::Sop2 || i.enc==Encoding::Sopk) && + scalar_alu32.count(name) && i.dst<106 && lane_free(i.src[0]) && + (i.enc!=Encoding::Sop2 || lane_free(i.src[1]))) { + if (i.enc!=Encoding::Sopk) read(i.src[0]); + if (i.enc==Encoding::Sop2) read(i.src[1]); + if (name=="s_addk_i32" || name=="s_mulk_i32") read(i.dst); + written.insert(i.dst); + } else { + refuse(at,"mesh loop body holds an unsupported instruction: "+name); + } + if (at==back) break; + at=i.next; + } + if (at!=back) refuse(head,"mesh loop back edge splits an instruction"); + for (auto r : read_first) if (written.count(r)) carried.insert(r); + // SCC is always carried: any of these instructions may read or write it. + std::vector> slots; + for (auto r : carried) { + const auto value=alu.graphics_registers.find(r); + if (!state[r].numeric() || value==alu.graphics_registers.end() || value->second.empty()) + refuse(head,"mesh loop carries a register without a numeric entry value: s"+to_string(r)); + slots.emplace_back(r,"%mesh_loop"+to_string(head)+"_s"+to_string(r)); + } + slots.emplace_back(128,"%mesh_loop"+to_string(head)+"_scc"); + for (const auto &[r,slot] : slots) { + const auto value=alu.graphics_registers.find(r); + const string entry=value==alu.graphics_registers.end() || value->second.empty() ? "0" : value->second; + ir.setup<<" "<=128 && s<=250) || s==253 || s==255; }; bool independent=false; if (next.enc==Encoding::Smem) // opcodes 0-4: s_load_dword{,x2..x16}; 8-12: s_buffer_load_dword{,...} independent=(next.op<=4 || (next.op>=8 && next.op<=12)) && next.dst+memory_count(next)<=106; @@ -898,20 +994,12 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout independent=(name.rfind("s_cmp",0)==0 || name.rfind("s_bitcmp",0)==0) && lane_free(next.src[0]) && lane_free(next.src[1]); else if (next.enc==Encoding::Sop1 || next.enc==Encoding::Sop2 || next.enc==Encoding::Sopk) { - // 32-bit scalar ALU only: no 64-bit mask forms, calls, register writes or relative moves. - static const std::set salu{ - "s_mov_b32","s_not_b32","s_brev_b32","s_movk_i32","s_addk_i32","s_mulk_i32", - "s_add_u32","s_sub_u32","s_add_i32","s_sub_i32","s_addc_u32","s_subb_u32","s_mul_i32", - "s_mul_hi_u32","s_mul_hi_i32","s_min_i32","s_min_u32","s_max_i32","s_max_u32","s_absdiff_i32", - "s_cselect_b32","s_and_b32","s_or_b32","s_xor_b32","s_andn2_b32","s_orn2_b32","s_nand_b32", - "s_nor_b32","s_xnor_b32","s_lshl_b32","s_lshr_b32","s_ashr_i32","s_bfm_b32","s_bfe_u32", - "s_bfe_i32","s_lshl1_add_u32","s_lshl2_add_u32","s_lshl3_add_u32","s_lshl4_add_u32", - "s_pack_ll_b32_b16","s_pack_lh_b32_b16","s_pack_hh_b32_b16"}; - independent=salu.count(name) && next.dst<106 && lane_free(next.src[0]) && + independent=scalar_alu32.count(name) && next.dst<106 && lane_free(next.src[0]) && (next.enc==Encoding::Sopk || lane_free(next.src[1])); } if (!independent) diamond_joined=false; } + if (const auto edges=back_edges.find(pc); edges!=back_edges.end() && !loop) open_loop(edges->second); program.at[pc]=0; alu.graphics_pc = pc; const auto raw = word(code,pc); @@ -1367,6 +1455,22 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout exec_skip=Skip{pc,i.target(),save_edge(),wave_active.empty(),lane_active,wave_active}; ir.body<<" br i1 "<<(wave_active.empty() ? lane_active : wave_active)<<", label %mesh_work"<back) { + // The back edge: store the carried registers, then repeat or fall through to the exit. An + // unconditional back edge leaves only through the body's forward exits. + const bool always=i.name=="s_branch"; + const auto take=always ? string{} : alu.cmp(i.name=="s_cbranch_scc0" ? "eq" : "ne",alu.read(128),"0"); + for (const auto &[r,slot] : loop->slots) + ir.body<<" store i32 "<head); + if (always) { + ir.body<<" br label %mesh_loop"<=2 + # A uniform scalar loop (#3703): s20 counts from 0 while s20 < root0[0] (s21), leaving early when s20 == 5. + # The exits set s20 to 7 (bound reached) or 9 (early exit) and join before the export reads s20. + def sopp(op, at, target): + return 0xbf800000 | (op << 16) | (((target - at - 4) // 4) & 0xffff) + def scalar_loop(extra=(), back_op=4, second_back=False, enter=False): + w = [0xbf068015, None] if enter else [] # s_cmp_eq_u32 s21, 0; s_cbranch_scc1 into the body + w += [0xbe940380] # s_mov_b32 s20, 0 + head = 4*len(w) + w += [0x81148114, *extra, 0xbf068514] # s_add_i32 s20, s20, 1; s_cmp_eq_u32 s20, 5 + early = 4*len(w); w += [None] # s_cbranch_scc1 found + if second_back: w += [None] # s_cbranch_scc1 back to the header + w += [0xbf091514] # s_cmp_ge_u32 s20, s21 + back = 4*len(w); w += [None] # s_cbranch_scc0 header (back_op 4) or another branch + w += [0xbe940387]; jump = 4*len(w); w += [None] # s_mov_b32 s20, 7; s_branch join + found = 4*len(w); w += [0xbe940389] # found: s_mov_b32 s20, 9 + w[early//4] = sopp(5, early, found) + w[back//4] = sopp(back_op, back, head) + w[jump//4] = sopp(2, jump, 4*len(w)) + if second_back: w[early//4+1] = sopp(5, early+4, head) + if enter: w[1] = sopp(5, 4, head+4) + return w + controlled + text = run('scalar-loop', scalar_loop()) + # s20 and SCC are carried through local slots; the bound s21 is read in place. + for slot in ('%mesh_loop4_s20', '%mesh_loop4_scc'): + assert re.search(rf'{slot} = alloca i32', text) and re.search(rf'load i32, i32\* {slot}', text), slot + assert '%mesh_loop4_s21' not in text, text + # Stored before the header and again at the back edge. + assert len(re.findall(r'store i32 [%\w.]+, i32\* %mesh_loop4_s20', text)) == 2, text + back = re.search(r'br i1 (%[\w.]+), label %mesh_loop4, label %mesh_loop_exit4', text) + assert back and re.search(rf'{re.escape(back[1])} = icmp eq i32 %[\w.]+, 0', text), text + assert re.search(r'icmp eq i32 %[\w.]+, 5', text) and re.search(r'icmp uge i32 %[\w.]+, %[\w.]+', text), text + assert 'storeVertexOutput' in text and text.count('phi i32') >= 1, text + # An unconditional back edge (s_branch) leaves only through the early exit. + text = run('scalar-loop-branch-back', scalar_loop(back_op=2)) + assert re.search(r'br label %mesh_loop4\n', text) and 'mesh_loop_exit4' not in text, text + for name, loop_words, expected in ( + ('scalar-loop-vector', scalar_loop(extra=[0x7e040214]), + 'mesh loop body holds an unsupported instruction: v_mov_b32'), + ('scalar-loop-vcc-back', scalar_loop(back_op=6), 'mesh loop back edge needs SCC or an unconditional branch'), + ('scalar-loop-two-back', scalar_loop(second_back=True), 'mesh loop needs exactly one back edge'), + ('scalar-loop-enter-body', scalar_loop(enter=True), 'mesh loop is entered other than at its header')): + run(name, loop_words, expected) # Count active lanes in both halves of a guest wave using the # logical workgroup index. The unsigned root parameter is the bound. # Use source-built encodings for the group index and range test. From 802f682db7185efe17b1f82dc0d72679ecf2fd4e Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:59:37 +0100 Subject: [PATCH 2/2] shader: carry mesh loop SCC and exit-only values only when proven Track SCC like an SGPR in the loop scan: give it a slot only when the body reads it before defining it, and refuse when its entry value is unknown instead of storing 0. Also carry any value the body writes after its first exit branch, so an exit sees the previous iteration's value; with no entry value it stays unbound and a later read refuses. Inline constant 0 shares operand code 128 with the SCC index, so operand reads stay limited to SGPRs and SCC reads are explicit. Co-Authored-By: Claude Opus 5.5 --- docs/experiments/native-mesh-scalar-loop.md | 45 ++++++++++++---- src/gfx1013_direct_mesh.inl | 54 ++++++++++++------- tests/native_direct_mesh_check.py | 57 ++++++++++++++++++--- 3 files changed, 123 insertions(+), 33 deletions(-) diff --git a/docs/experiments/native-mesh-scalar-loop.md b/docs/experiments/native-mesh-scalar-loop.md index 949b76dda5..1841d92155 100644 --- a/docs/experiments/native-mesh-scalar-loop.md +++ b/docs/experiments/native-mesh-scalar-loop.md @@ -10,11 +10,17 @@ accepts one narrow loop shape, a *uniform scalar loop*. The loop has one header - `s_waitcnt`, `s_nop` and `s_clause`; - forward exits (`s_cbranch_scc0/scc1`) past the back edge, inside the enclosing EXECZ region. -The pass stays forward-only. A register the body writes and reads before that write carries a value into the next -iteration; it lives in a local slot, as does SCC. The slots are stored before the header and at the back edge, and -loaded in the header. In the header these registers become plain numbers. A register the body only writes is -unbound there; a register the body never writes keeps its entry value. The exits use the existing forward-join -merge. The trip count comes from guest data, as on the GPU. +The pass stays forward-only. A value the body writes is *carried* into the next iteration in two cases: one pass +reads it before that write, or an exit branch comes before that write, so the exit sees the previous iteration's +value. SCC counts as a value here, like an SGPR: the body defines it with a compare or with any of the scalar ALU +above except the moves, `s_cselect_b32`, the multiplies, `s_brev_b32`, `s_bfm_b32` and the packs. A carried value +lives in a local slot. The slot is stored before the header and at the back edge, and loaded in the header. In the +header a carried register becomes a plain number. A register the body writes only before every exit is unbound +there. A register the body never writes keeps its entry value. The exits use the existing forward-join merge. The +trip count comes from guest data, as on the GPU. + +A value that only an exit sees can lack a value before the loop. It then stays unbound at that exit, and a read after +the loop refuses with `unbound numeric SGPR sN`. The following keep a refusal: @@ -25,7 +31,8 @@ The following keep a refusal: | A back edge on VCC or EXEC | `mesh loop back edge needs SCC or an unconditional branch` | | A branch into the body other than at the header | `mesh loop is entered other than at its header` | | A loop after GS_ALLOC_REQ, under a per-lane else, or outside full EXEC and any EXECZ region | `mesh loop outside a uniform scalar region` | -| A carried register without a numeric entry value | `mesh loop carries a register without a numeric entry value: sN` | +| A register read in the body before the body writes it, without a numeric entry value | `mesh loop carries a register without a numeric entry value: sN` | +| SCC read in the body before the body defines it, without a known entry value | `mesh loop reads SCC before the body defines it, without a known entry value` | ## Checks @@ -33,18 +40,38 @@ The following keep a refusal: constant s21, and leaves early when s20 is 5. The two exits set s20 to 7 or 9 and join before the export reads s20. The IR check covers: -- only s20 and SCC get slots; +- only s20 gets a slot: the bound s21 is read in place, and the body defines SCC before reading it; - s20 is stored twice, before the header and at the back edge; - the back edge branches on SCC == 0; - the body compares with 5 and with s21. `scalar-loop-branch-back` uses an unconditional `s_branch` back edge. Its only exit is the early one, and it emits -no exit block after the back edge. The four refusals above have a case each: `scalar-loop-vector`, `-vcc-back`, `-two-back`, `-enter-body`. +no exit block after the back edge. The refusals above each have a case: `scalar-loop-vector`, `-vcc-back`, +`-two-back` and `-enter-body`. + +SCC entering the loop: + +- `scalar-loop-scc-unknown` exits on SCC at the top of the body, and nothing before the loop set SCC: it is refused. +- `scalar-loop-scc-after-move` puts `s_mov_b32` before that exit; a move leaves SCC alone, so the refusal stays. +- `scalar-loop-scc-known` sets SCC from the root constant before the loop. SCC gets a slot, and the slot's two stores + are IR values, never a literal 0. + +A value seen only at an early exit: s22 = 7 before the loop, the header exits when s20 reaches the bound, the body +then sets s22 = 9, and only the export after the exit reads s22. The guest exports 7 after zero trips and 9 after +one. `scalar-loop-exit-read-{80,81,15}` (bound 0, bound 1 and the root constant s21) follow the exported x back to +the header's load of the s22 slot. They also check that the slot's only stores are 7 before the loop and 9 at the +back edge. `scalar-loop-exit-unset` leaves s22 unset before the loop: it translates while nothing reads s22, and +`-unset-read` refuses the read at the exit. -Controls: +Controls (one changed line each, `native_direct_mesh` fails): - Without the frontend change, `scalar-loop` fails with `unsupported mesh scalar branch destination`. - With the back-edge stores removed, the store count assertion fails. +- Leaving an unknown SCC uncarried instead of refusing: `scalar-loop-scc-unknown` no longer gets its refusal. +- Carrying only values read before their write (the exit rule off): `scalar-loop-exit-read-80` fails with + `unbound numeric SGPR s22`. +- Carrying an exit-only value even without an entry value: `scalar-loop-exit-unset` is refused. +- Counting `s_mov_b32` as an SCC write: `scalar-loop-scc-after-move` loses its refusal. ## Local requests diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index 74e1472fac..eec4900c72 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -756,8 +756,8 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout "s_pack_ll_b32_b16","s_pack_lh_b32_b16","s_pack_hh_b32_b16"}; // A uniform scalar loop (#3703): one header, one back edge (s_cbranch_scc0/scc1 or s_branch), and a body of // the scalar ALU above, scalar compares, scalar loads, waits and forward exits past the back edge. The pass - // stays forward-only: registers the body reads before it writes them, and SCC, live in local slots that are - // stored before the header and at the back edge and loaded in the header. + // stays forward-only: carried SGPRs and SCC live in local slots that are stored before the header and at the + // back edge and loaded in the header. std::map> back_edges; for (unsigned at=0;at &backs) { const unsigned head=pc, back=backs.front(); if (backs.size()!=1) refuse(head,"mesh loop needs exactly one back edge"); - if (lane_else || branch || allocated || (!full_exec && !exec_skip) || (exec_skip && back>=exec_skip->end)) + if (branch || allocated || (!full_exec && !exec_skip) || (exec_skip && back>=exec_skip->end)) refuse(head,"mesh loop outside a uniform scalar region"); for (const auto &edge : forward) if (edge.first>head && edge.first<=back) refuse(head,"mesh loop is entered other than at its header"); - // A register the body writes, and reads before that write in one pass, carries a value into the next - // iteration. A register the body never writes keeps its entry value. - std::set written, read_first, carried; + // A value the body writes is carried into the next iteration when one pass reads it before that write, + // or when an exit branch comes before that write (the exit then sees the previous iteration's value). + // A value the body never writes keeps its entry value. SCC (128) is tracked like an SGPR. + std::set written, read_first, before_exit, carried; + bool exited=false; + // Operands name SGPRs below 106; 128 there is the inline constant 0, so SCC reads go through read_scc. const auto read=[&](unsigned r) { if (r<106 && !written.count(r)) read_first.insert(r); }; + const auto read_scc=[&] { if (!written.count(128)) read_first.insert(128); }; + const auto write=[&](unsigned r) { written.insert(r); if (!exited) before_exit.insert(r); }; + // Scalar ALU forms here that leave SCC unchanged; every other one writes it. + static const std::set keeps_scc{"s_mov_b32","s_movk_i32","s_cselect_b32","s_mul_i32","s_mul_hi_u32", + "s_mul_hi_i32","s_mulk_i32","s_brev_b32","s_bfm_b32","s_pack_ll_b32_b16","s_pack_lh_b32_b16", + "s_pack_hh_b32_b16"}; unsigned at=head; while (at<=back) { const auto i=decode(code,at,true,true); @@ -795,24 +804,30 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout refuse(at,"mesh loop body holds an unsupported scalar load"); for (unsigned j=0;j<(i.op>=8 ? 4u : 2u);++j) read(i.src[0]+j); if (offset_reg!=125) read(offset_reg); - for (unsigned j=0;j=code.size() || (exec_skip && i.target()>exec_skip->end)) refuse(at,"mesh loop exit must branch forward past the back edge"); + read_scc(); + exited=true; } else if (i.enc==Encoding::Sopc && (name.rfind("s_cmp",0)==0 || name.rfind("s_bitcmp",0)==0) && lane_free(i.src[0]) && lane_free(i.src[1])) { read(i.src[0]); read(i.src[1]); + write(128); } else if ((i.enc==Encoding::Sop1 || i.enc==Encoding::Sop2 || i.enc==Encoding::Sopk) && scalar_alu32.count(name) && i.dst<106 && lane_free(i.src[0]) && (i.enc!=Encoding::Sop2 || lane_free(i.src[1]))) { if (i.enc!=Encoding::Sopk) read(i.src[0]); if (i.enc==Encoding::Sop2) read(i.src[1]); if (name=="s_addk_i32" || name=="s_mulk_i32") read(i.dst); - written.insert(i.dst); + if (name=="s_cselect_b32" || name=="s_addc_u32" || name=="s_subb_u32") read_scc(); + write(i.dst); + if (!keeps_scc.count(name)) write(128); } else { refuse(at,"mesh loop body holds an unsupported instruction: "+name); } @@ -820,21 +835,24 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout at=i.next; } if (at!=back) refuse(head,"mesh loop back edge splits an instruction"); - for (auto r : read_first) if (written.count(r)) carried.insert(r); - // SCC is always carried: any of these instructions may read or write it. std::vector> slots; - for (auto r : carried) { + for (auto r : written) { + const bool read_early=read_first.count(r), exit_early=!before_exit.count(r); + if (!read_early && !exit_early) continue; const auto value=alu.graphics_registers.find(r); - if (!state[r].numeric() || value==alu.graphics_registers.end() || value->second.empty()) - refuse(head,"mesh loop carries a register without a numeric entry value: s"+to_string(r)); - slots.emplace_back(r,"%mesh_loop"+to_string(head)+"_s"+to_string(r)); + const bool known=value!=alu.graphics_registers.end() && !value->second.empty() && + (r==128 || state[r].numeric()); + // A value seen only at an early exit may stay unbound there: a later read of it refuses. + if (!known && !read_early) continue; + if (!known) + refuse(head,r==128 ? string("mesh loop reads SCC before the body defines it, without a known entry value") + : "mesh loop carries a register without a numeric entry value: s"+to_string(r)); + carried.insert(r); + slots.emplace_back(r,"%mesh_loop"+to_string(head)+(r==128 ? string("_scc") : "_s"+to_string(r))); } - slots.emplace_back(128,"%mesh_loop"+to_string(head)+"_scc"); for (const auto &[r,slot] : slots) { - const auto value=alu.graphics_registers.find(r); - const string entry=value==alu.graphics_registers.end() || value->second.empty() ? "0" : value->second; ir.setup<<" "<= bound, the + # body sets s22 = 9, and only the export after the exit reads s22. The guest exports 7 after zero + # iterations and 9 after one. The exported x must come from the header's load of the s22 slot, whose only + # stores are 7 before the loop and 9 at the back edge: zero trips read the entry store, one trip the + # back-edge store. Bounds: immediate 0 (no trip), immediate 1 (one trip) and the root constant s21. + def exit_read(bound, entry=0xbe960387, export=0x7e020c16): + w = [entry, 0xbe940380] # s_mov_b32 s22, 7; s_mov_b32 s20, 0 + head = 4*len(w) + w += [0xbf090014 | bound << 8, None, # s_cmp_ge_u32 s20, bound; s_cbranch_scc1 exit + 0xbe960389, 0x81148114, None] # s_mov_b32 s22, 9; s_add_i32 s20, s20, 1; s_branch head + w[3] = sopp(5, 12, 4*len(w)); w[6] = sopp(2, 24, head) + tail = controlled.copy(); tail[7] = export # export s22 instead of s20 + return w + tail + for bound in (0x80, 0x81, 0x15): + text = run(f'scalar-loop-exit-read-{bound:x}', exit_read(bound)) + defs = dict(re.findall(r'^\s*(%[\w.]+) = (.+)$', text, re.M)) + value = re.search(r'storeVertexOutput\.f32\(i32 \d+, i32 \d+, i32 \d+, i8 0, float (%[\w.]+),', text)[1] + while not defs[value].startswith('load '): + value = re.match(r'(?:bitcast|uitofp) \w+ (%[\w.]+) to \w+$', defs[value])[1] + assert defs[value] == 'load i32, i32* %mesh_loop8_s22, align 4', (defs[value], text) + header = text.split('\nmesh_loop8:', 1)[1].split('\n\n', 1)[0] + assert f'{value} = load' in header, text + stores = re.findall(r'store i32 (\S+), i32\* %mesh_loop8_s22', text) + assert stores == ['7', '9'], (stores, text) + assert re.search(r'store i32 9, i32\* %mesh_loop8_s22, align 4\n br label %mesh_loop8\n', text), text + # Without a value before the loop (s_nop in place of s22 = 7), s22 cannot be carried. The loop still + # translates while nothing reads s22 after it; a read at the exit refuses instead of using a value. + text = run('scalar-loop-exit-unset', exit_read(0x15, entry=0xbf800000, export=0x7e020c14)) + assert '%mesh_loop8_s22' not in text and 'storeVertexOutput' in text, text + run('scalar-loop-exit-unset-read', exit_read(0x15, entry=0xbf800000), 'unbound numeric SGPR s22') # Count active lanes in both halves of a guest wave using the # logical workgroup index. The unsigned root parameter is the bound. # Use source-built encodings for the group index and range test.