From 848345d20b295051ac66c229d5b5f83adf2cfff8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:58:02 +0000 Subject: [PATCH 1/4] startup: accept sample_b and get_lod under entry EXEC after a join image_sample_b and image_get_lod refused any prior branch target even when EXEC was still the entry mask (M200-01 B/L: outside straight-line with every lane active). Drop the blocks gate; keep the pixel + exec_known proof. Fixtures: uniform join before the op accepted; divergent EXEC refused; WARP draw of join-before sample_b bias -1. Refs #2618 Co-authored-by: SimSalabimse --- docs/experiments.md | 4 +- tests/startup_gfx2hlsl_image_get_lod_check.py | 41 ++++++++++---- tests/startup_image_sample_b_check.py | 55 +++++++++++++++++-- tools/startup/gfx2hlsl.py | 12 ++-- 4 files changed, 89 insertions(+), 23 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 8c9b7049a8..725c1d384d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14494,9 +14494,9 @@ For binary32 arithmetic and compare sources, the translator reads the inline int ## Startup translator: biased image sampling -`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form is refused outside a pixel stage, after the exec mask was modified and after a branch (there the plain sample is lowered to level 0, which would drop the bias), and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. +`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask (implicit derivatives); a uniform join or later loop does not drop that proof, while divergent EXEC before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. -`tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). +`tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. A uniform join before the sample is accepted and drawn (same mip as the plain bias -1 case); divergent EXEC before the sample is refused. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). ```powershell cmake --build --preset dev --target offscreen_check diff --git a/tests/startup_gfx2hlsl_image_get_lod_check.py b/tests/startup_gfx2hlsl_image_get_lod_check.py index e9443d9ca1..4e7c248c61 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -1,17 +1,18 @@ -"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py. +"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py (M200-01 L). image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp (Mesa nir_texop_lod, emitted by ACO as image_get_lod; GLSL textureQueryLod x/y). It is lowered to HLSL CalculateLevelOfDetail / CalculateLevelOfDetailUnclamped, which take implicit derivatives like Sample, so the stage -must be a pixel stage, straight-line, with every lane active. The clamped value depends on the sampler's LOD limits -and bias, so the sampler must be a constant descriptor under the validation of image_sample_b. +must be a pixel stage whose EXEC is still the entry mask (every lane active). A uniform join or later loop does not +drop that proof; divergent EXEC before the read does. The clamped value depends on the sampler's LOD limits and bias, +so the sampler must be a constant descriptor under the validation of image_sample_b. Fixture (synthetic): the recorded c_lz stage of startup_image_sample_c_check with the MIMG opcode set to 0x60 (image_get_lod; the decoder reads it back with a 2-register address), sampler word 2 loaded from a literal (mip filter point), and for the second form dmask 0x3. -Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. Controls (refused): -dmask 0x4, a 2D array, a branch before the read, a sampler LOD bias, a sampler with mipmapping disabled, and the -stage without op_image_get_lod (negative control: refused as on main). +Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. A uniform join +before the read is accepted. Controls (refused): dmask 0x4, a 2D array, divergent EXEC before the read, a sampler LOD +bias, a sampler with mipmapping disabled, and the stage without op_image_get_lod (negative control: refused as on main). draw [fxc]: also compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). """ import struct @@ -34,7 +35,11 @@ MIP_POINT = 1 << 26 # SQ_IMG_SAMP_WORD2 bits 27:26 MIP_FILTER -def stage(dmask=1, dim=1, branch=False, word2=MIP_POINT): +def sopp(op, simm): + return struct.pack(' reassemble every fixture source and compare it with the recorded words @@ -12,7 +12,8 @@ IntrinsicsAMDGPU.td lists the extra argument of AMDGPUSample_b as llvm_anyfloat_ty "bias" and MIMGInstructions.td gives IMAGE_SAMPLE_B the gfx10 opcode 0x25. HLSL Texture.SampleBias(sampler, location, bias) adds the bias to the implicit mip level, so the lowering is tex.SampleBias(smp, uv, bias). D3D documents the bias range as -16.0 to 15.99; -the ISA text states no hardware clamp, so values outside that range are an unverified difference. +the ISA text states no hardware clamp, so values outside that range are an unverified difference. Accepted under the +entry EXEC mask even after a uniform join or later loop; divergent EXEC before the sample stays refused. Each fixture is a source-built gfx1013 pixel stage: v0 = bias, v1 = u = 0.75, v2 = v = 0.25 and v3 = the slice (root constant 1, s9). Constant coordinates have no derivatives (the implicit LOD would be log2(0) and the bias is lost), so @@ -399,13 +400,20 @@ def call(coords, kind='ps', exec_known=True, blocks=()): else: raise AssertionError('image_sample_b accepted %d address registers' % count) for label, kwargs in (('vertex stage', {'kind': 'vs'}), ('compute stage', {'kind': 'cs'}), - ('exec modified', {'exec_known': False}), ('after a branch', {'blocks': [object()]})): + ('exec modified', {'exec_known': False})): try: call('[v1, v2, v3]', **kwargs) except G.Unsupported as error: assert 'image_sample_b needs implicit derivatives' in str(error), (label, error) else: raise AssertionError('image_sample_b accepted: %s' % label) + # A prior branch target (non-empty blocks) is fine while EXEC is still the entry mask (M200-01 B). + try: + call('[v1, v2, v3]', blocks=[object()]) + except G.Unsupported as error: + raise AssertionError('image_sample_b refused with entry EXEC after a join: %s' % error) + except AttributeError: + pass # The legal case gets past both guards: the bare stage then stops where it needs a pipeline. try: call('[v1, v2, v3]') @@ -413,7 +421,24 @@ def call(coords, kind='ps', exec_known=True, blocks=()): raise AssertionError('legal image_sample_b refused: %s' % error) except AttributeError: pass - print('refused: wrong address count, vertex and compute stages, modified exec, code after a branch') + print('refused: wrong address count, vertex and compute stages, modified exec; join with entry EXEC accepted') + + +def sopp(op, simm): + return struct.pack(' r0'), @@ -588,6 +623,18 @@ def sampler_line(pipe): if run.returncode: raise AssertionError('%s %s slice=%d\n%s\n%s' % (kind, name, slice_index, run.stdout, run.stderr)) print('%s sample_b %s slice=%d: %s' % (kind, name, slice_index, expected), flush=True) + # M200-01 B: the same bias-1 array sample after a uniform join must still read mip 0. + join_words = with_join_before_sample(bytes.fromhex(WORDS['array -1'])) + join_pipe = G.Pipeline(VS_WORDS, join_words, root_blob()) + join_shader = compile_hlsl(compiler, kind, drawable(join_pipe.hlsl_ps()), 'ps_join_m1_%s' % kind, + ps_profile, directory) + join_line = sampler_line(join_pipe) + for slice_index in (0, 1): + expected = texel_cell(mip_for(-1), slice_index) + run = draw_once(vs, join_shader, slice_index, expected, join_line) + if run.returncode: + raise AssertionError('%s join sample_b slice=%d\n%s\n%s' % (kind, slice_index, run.stdout, run.stderr)) + print('%s sample_b join-before bias=-1 slice=%d: %s' % (kind, slice_index, expected), flush=True) # Negative control: without a bias the draw reads mip 1, so the bias -1 and bias +1 expectations must fail. line = sampler_line(stage('array nobias')) nobias = compile_hlsl(compiler, kind, drawable(translated['array nobias']), 'ps_nobias_%s' % kind, ps_profile, directory) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9c3d579e50..cb2ce87f1a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5241,9 +5241,11 @@ def image(self, ops, mods, how): else: # The bias is added to the LOD derived from the coordinate derivatives of the pixel quad: only a # pixel stage that still runs with its entry mask has them. Elsewhere the plain sample is lowered - # to level 0, which would drop the bias, so the bias form is refused instead. - if self.kind != 'ps' or not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_sample_b needs implicit derivatives: pixel stage, entry mask, no branches') + # to level 0, which would drop the bias, so the bias form is refused instead. A uniform join or + # later loop does not drop the proof: every lane still reaches the sample with the entry EXEC + # (M200-01 B/L). Divergent EXEC before the sample stays refused. + if self.kind != 'ps' or not self.exec_known: + raise Unsupported('image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask') bias, cs = cs[0], cs[1:] if how == 'get_lod': # image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp @@ -5255,8 +5257,8 @@ def image(self, ops, mods, how): if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or not dmask or dmask & ~3 or len(cs) != 2: raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) # Both HLSL calls take implicit derivatives, so the rule of image_sample_b applies. - if not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_get_lod needs implicit derivatives: pixel stage, entry mask, no branches') + if not self.exec_known: + raise Unsupported('image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask') desc_key = self.descriptor(ops[2]) tex = self.pipe.resource(desc_key, kinds[dim]) if how in ('load', 'load_mip'): From edd25d8f8b6cd77cf0641b1fd1d64bcf24a888d0 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 01:08:36 +0000 Subject: [PATCH 2/4] startup: require wave-uniform CF for sample_b and get_lod Review on #2659: dropping only the blocks gate accepted vcc/exec branches before SampleBias / CalculateLevelOfDetail. Track uniform_cf (cleared by divergent s_cbranch_*), keep scc-uniform joins, and refuse vccz/vccnz/execz/execnz before the op in both fixtures. Refs #2618 Co-authored-by: SimSalabimse --- docs/experiments.md | 4 +- tests/startup_gfx2hlsl_image_get_lod_check.py | 22 ++++++--- tests/startup_image_sample_b_check.py | 49 +++++++++++++------ tools/startup/gfx2hlsl.py | 23 ++++++--- 4 files changed, 66 insertions(+), 32 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 725c1d384d..36ebc0259d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14494,9 +14494,9 @@ For binary32 arithmetic and compare sources, the translator reads the inline int ## Startup translator: biased image sampling -`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask (implicit derivatives); a uniform join or later loop does not drop that proof, while divergent EXEC before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. +`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask with wave-uniform control flow (implicit derivatives); a uniform (scc) join or later loop does not drop that proof, while divergent EXEC or a vcc/exec-conditioned branch before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. -`tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. A uniform join before the sample is accepted and drawn (same mip as the plain bias -1 case); divergent EXEC before the sample is refused. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). +`tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. A uniform (scc) join before the sample is accepted and drawn (same mip as the plain bias -1 case); divergent EXEC or a vcc/exec-conditioned branch before the sample is refused. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). ```powershell cmake --build --preset dev --target offscreen_check diff --git a/tests/startup_gfx2hlsl_image_get_lod_check.py b/tests/startup_gfx2hlsl_image_get_lod_check.py index 4e7c248c61..9ca1feecf6 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -3,16 +3,18 @@ image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp (Mesa nir_texop_lod, emitted by ACO as image_get_lod; GLSL textureQueryLod x/y). It is lowered to HLSL CalculateLevelOfDetail / CalculateLevelOfDetailUnclamped, which take implicit derivatives like Sample, so the stage -must be a pixel stage whose EXEC is still the entry mask (every lane active). A uniform join or later loop does not -drop that proof; divergent EXEC before the read does. The clamped value depends on the sampler's LOD limits and bias, -so the sampler must be a constant descriptor under the validation of image_sample_b. +must be a pixel stage whose EXEC is still the entry mask (every lane active) with wave-uniform control flow. A +uniform (scc) join or later loop does not drop that proof; divergent EXEC or a vcc/exec-conditioned branch before +the read does. The clamped value depends on the sampler's LOD limits and bias, so the sampler must be a constant +descriptor under the validation of image_sample_b. Fixture (synthetic): the recorded c_lz stage of startup_image_sample_c_check with the MIMG opcode set to 0x60 (image_get_lod; the decoder reads it back with a 2-register address), sampler word 2 loaded from a literal (mip filter point), and for the second form dmask 0x3. Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. A uniform join -before the read is accepted. Controls (refused): dmask 0x4, a 2D array, divergent EXEC before the read, a sampler LOD -bias, a sampler with mipmapping disabled, and the stage without op_image_get_lod (negative control: refused as on main). +before the read is accepted. Controls (refused): dmask 0x4, a 2D array, divergent EXEC, s_cbranch_vccz/execz before +the read, a sampler LOD bias, a sampler with mipmapping disabled, and the stage without op_image_get_lod +(negative control: refused as on main). draw [fxc]: also compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). """ import struct @@ -39,7 +41,7 @@ def sopp(op, simm): return struct.pack(' +1; s_mov (vcc/exec: divergent CF) + insert += bytes.fromhex('800380be') + sopp(cf_op, 1) + bytes.fromhex('810381be') if insert: code = code[:AT] + insert + code[AT:] return code @@ -93,6 +97,8 @@ def controls(): refused(stage(dmask=4), 'image_get_lod form') refused(stage(dim=5), 'image_get_lod form') # SQ_RSRC_IMG_2D_ARRAY refused(stage(divergent=True), 'image_get_lod needs implicit derivatives') + for op in (6, 7, 8, 9): # vccz, vccnz, execz, execnz + refused(stage(cf_op=op), 'image_get_lod needs implicit derivatives') refused(stage(word2=MIP_POINT | 1), 'image_get_lod with a sampler LOD bias') refused(stage(word2=0), 'image_get_lod with mipmapping disabled') saved = G.Stage.op_image_get_lod @@ -102,8 +108,8 @@ def controls(): finally: G.Stage.op_image_get_lod = saved print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3; uniform join/branch before ' - 'the read accepted; dmask 0x4, a 2D array, divergent EXEC, a sampler bias and a sampler without mipmapping ' - 'refused; refused without the handler') + 'the read accepted; dmask 0x4, a 2D array, divergent EXEC, vcc/exec branches, a sampler bias and a ' + 'sampler without mipmapping refused; refused without the handler') return pipe diff --git a/tests/startup_image_sample_b_check.py b/tests/startup_image_sample_b_check.py index 0aa82a1f5e..21d6c7b00d 100644 --- a/tests/startup_image_sample_b_check.py +++ b/tests/startup_image_sample_b_check.py @@ -13,7 +13,8 @@ IMAGE_SAMPLE_B the gfx10 opcode 0x25. HLSL Texture.SampleBias(sampler, location, bias) adds the bias to the implicit mip level, so the lowering is tex.SampleBias(smp, uv, bias). D3D documents the bias range as -16.0 to 15.99; the ISA text states no hardware clamp, so values outside that range are an unverified difference. Accepted under the -entry EXEC mask even after a uniform join or later loop; divergent EXEC before the sample stays refused. +entry EXEC mask and wave-uniform control flow even after a uniform (scc) join or later loop; divergent EXEC or a +vcc/exec-conditioned branch before the sample stays refused. Each fixture is a source-built gfx1013 pixel stage: v0 = bias, v1 = u = 0.75, v2 = v = 0.25 and v3 = the slice (root constant 1, s9). Constant coordinates have no derivatives (the implicit LOD would be log2(0) and the bias is lost), so @@ -387,9 +388,10 @@ def texel_cell(mip, slice_index): def check_guards(): """The stage guard and the address-count guard are decided before any state is read, so a bare stage reaches them.""" - def call(coords, kind='ps', exec_known=True, blocks=()): + def call(coords, kind='ps', exec_known=True, blocks=(), uniform_cf=True): bare = G.Stage.__new__(G.Stage) bare.kind, bare.exec_known, bare.blocks = kind, exec_known, list(blocks) + bare.uniform_cf = uniform_cf bare.image(['v5', coords, 's0'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x1'], 'b') for coords, count in (('[v1, v2]', 2), ('[v1, v2, v3, v4]', 4)): @@ -400,20 +402,23 @@ def call(coords, kind='ps', exec_known=True, blocks=()): else: raise AssertionError('image_sample_b accepted %d address registers' % count) for label, kwargs in (('vertex stage', {'kind': 'vs'}), ('compute stage', {'kind': 'cs'}), - ('exec modified', {'exec_known': False})): + ('exec modified', {'exec_known': False}), + ('divergent CF', {'uniform_cf': False})): try: call('[v1, v2, v3]', **kwargs) except G.Unsupported as error: assert 'image_sample_b needs implicit derivatives' in str(error), (label, error) else: raise AssertionError('image_sample_b accepted: %s' % label) - # A prior branch target (non-empty blocks) is fine while EXEC is still the entry mask (M200-01 B). + # A prior join (non-empty blocks) is fine while EXEC and wave-uniform CF hold (M200-01 B). try: - call('[v1, v2, v3]', blocks=[object()]) + call('[v1, v2, v3]', blocks=[object()], uniform_cf=True) except G.Unsupported as error: - raise AssertionError('image_sample_b refused with entry EXEC after a join: %s' % error) + raise AssertionError('image_sample_b refused with entry EXEC after a uniform join: %s' % error) except AttributeError: pass + else: + raise AssertionError('image_sample_b after a join returned without needing a pipeline') # The legal case gets past both guards: the bare stage then stops where it needs a pipeline. try: call('[v1, v2, v3]') @@ -421,7 +426,10 @@ def call(coords, kind='ps', exec_known=True, blocks=()): raise AssertionError('legal image_sample_b refused: %s' % error) except AttributeError: pass - print('refused: wrong address count, vertex and compute stages, modified exec; join with entry EXEC accepted') + else: + raise AssertionError('legal image_sample_b returned without needing a pipeline') + print('refused: wrong address count, vertex and compute stages, modified exec, divergent CF; ' + 'join with entry EXEC and uniform CF accepted') def sopp(op, simm): @@ -441,6 +449,13 @@ def with_divergent_exec_before_sample(data): return data[:off] + bytes.fromhex('8003febe') + data[off:] +def with_branch_before_sample(data, sopp_op): + """Insert s_mov; s_cbranch_ +1; s_mov immediately before the sample_b (review probe).""" + off = next(o for o, _s, _n, a in G.decode(data) if 'image_sample_b' in a) + insert = bytes.fromhex('800380be') + sopp(sopp_op, 1) + bytes.fromhex('810381be') + return data[:off] + insert + data[off:] + + def controls(): assert WORDS, 'no recorded words' locate() @@ -449,13 +464,19 @@ def controls(): plain = bytes.fromhex(WORDS['plain']) join_ps = G.Pipeline(VS_WORDS, with_join_before_sample(plain), root_blob()).hlsl_ps() assert 'SampleBias' in join_ps and bias_call(join_ps, 'float2') == (['v1', 'v2'], 'v0'), join_ps - try: - G.Pipeline(VS_WORDS, with_divergent_exec_before_sample(plain), root_blob()).hlsl_ps() - except G.Unsupported as error: - assert 'image_sample_b needs implicit derivatives' in str(error), error - else: - raise AssertionError('image_sample_b accepted after divergent EXEC') - print('uniform join before sample_b accepted; divergent EXEC before sample_b refused') + for label, mutate in ( + ('divergent EXEC', with_divergent_exec_before_sample), + ('s_cbranch_vccz', lambda d: with_branch_before_sample(d, 6)), + ('s_cbranch_vccnz', lambda d: with_branch_before_sample(d, 7)), + ('s_cbranch_execz', lambda d: with_branch_before_sample(d, 8)), + ('s_cbranch_execnz', lambda d: with_branch_before_sample(d, 9))): + try: + G.Pipeline(VS_WORDS, mutate(plain), root_blob()).hlsl_ps() + except G.Unsupported as error: + assert 'image_sample_b needs implicit derivatives' in str(error), (label, error) + else: + raise AssertionError('image_sample_b accepted after %s' % label) + print('uniform join before sample_b accepted; divergent EXEC and vcc/exec branches before sample_b refused') # Address order: the bias register comes first and is the third SampleBias argument. expected = { 'array 1': (['v1', 'v2', 'v3'], 'v0', 'float3', 'Texture2DArray r0'), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index cb2ce87f1a..ea7bf66e6a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2683,6 +2683,8 @@ def translate(self): self.sym = dict(init_sym) self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec + # True until a wave-divergent branch: SampleBias / CalculateLevelOfDetail need uniform CF. + self.uniform_cf = True self.masks = set(init_masks) self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined) last_write = {} # SGPR -> offset of its last write in program order @@ -2857,6 +2859,8 @@ def translate(self): raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) cond_uniform = True if not cond_uniform: + # Divergent CF: later SampleBias / CalculateLevelOfDetail would see uneven quads. + self.uniform_cf = False b_target = int(parse(asm)[1][0].split('_')[1], 16) regs, affected = div_targets.get(off, (set(), set())) regs = {r for r in regs if isinstance(r, int)} @@ -5240,12 +5244,14 @@ def image(self, ops, mods, how): lod, cs = cs[-1], cs[:-1] else: # The bias is added to the LOD derived from the coordinate derivatives of the pixel quad: only a - # pixel stage that still runs with its entry mask has them. Elsewhere the plain sample is lowered - # to level 0, which would drop the bias, so the bias form is refused instead. A uniform join or - # later loop does not drop the proof: every lane still reaches the sample with the entry EXEC - # (M200-01 B/L). Divergent EXEC before the sample stays refused. - if self.kind != 'ps' or not self.exec_known: - raise Unsupported('image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask') + # pixel stage that still runs with its entry mask and wave-uniform control flow has them. + # Elsewhere the plain sample is lowered to level 0, which would drop the bias, so the bias form is + # refused instead. A uniform join (scc with scc_uniform) or later loop does not drop the proof + # (M200-01 B/L). Divergent EXEC or a vcc/exec-conditioned branch before the sample stays refused. + if (self.kind != 'ps' or not self.exec_known or + not getattr(self, 'uniform_cf', True)): + raise Unsupported('image_sample_b needs implicit derivatives: pixel stage with the entry EXEC ' + 'mask and wave-uniform control flow') bias, cs = cs[0], cs[1:] if how == 'get_lod': # image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp @@ -5257,8 +5263,9 @@ def image(self, ops, mods, how): if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or not dmask or dmask & ~3 or len(cs) != 2: raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) # Both HLSL calls take implicit derivatives, so the rule of image_sample_b applies. - if not self.exec_known: - raise Unsupported('image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask') + if not self.exec_known or not getattr(self, 'uniform_cf', True): + raise Unsupported('image_get_lod needs implicit derivatives: pixel stage with the entry EXEC ' + 'mask and wave-uniform control flow') desc_key = self.descriptor(ops[2]) tex = self.pipe.resource(desc_key, kinds[dim]) if how in ('load', 'load_mip'): From 31913ad3d25c7e674c40b13d0cd19bc9c3852033 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Thu, 26 Nov 2026 03:02:28 +0100 Subject: [PATCH 3/4] startup: refuse sample_b and get_lod inside a loop with a divergent back edge A divergent backward branch after the read still lets lanes of one quad leave the loop at different passes, so the read runs again with uneven quads although no divergent branch precedes it in program order. Record the read sites and the divergent back edges and refuse a read that one of them spans. Tests: synthetic words with s_cbranch_vccnz/execnz right after the read, back to it (fail before, pass after). --- tests/startup_gfx2hlsl_image_get_lod_check.py | 6 +++++- tests/startup_image_sample_b_check.py | 11 ++++++++++- tools/startup/gfx2hlsl.py | 16 ++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/tests/startup_gfx2hlsl_image_get_lod_check.py b/tests/startup_gfx2hlsl_image_get_lod_check.py index 9ca1feecf6..70475ee591 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -41,7 +41,7 @@ def sopp(op, simm): return struct.pack(' right after the read, back to it (a divergent back edge spanning the read) + code = code[:AT + 8] + sopp(back_op, -3) + code[AT + 8:] insert = b'' if branch: # s_cbranch_scc0 to the next instruction: uniform control flow before the read insert += sopp(4, 0) @@ -97,6 +99,8 @@ def controls(): refused(stage(dmask=4), 'image_get_lod form') refused(stage(dim=5), 'image_get_lod form') # SQ_RSRC_IMG_2D_ARRAY refused(stage(divergent=True), 'image_get_lod needs implicit derivatives') + for op in (7, 9): # vccnz, execnz back edge after the read + refused(stage(back_op=op), 'image_get_lod needs implicit derivatives') for op in (6, 7, 8, 9): # vccz, vccnz, execz, execnz refused(stage(cf_op=op), 'image_get_lod needs implicit derivatives') refused(stage(word2=MIP_POINT | 1), 'image_get_lod with a sampler LOD bias') diff --git a/tests/startup_image_sample_b_check.py b/tests/startup_image_sample_b_check.py index 21d6c7b00d..356010aa7c 100644 --- a/tests/startup_image_sample_b_check.py +++ b/tests/startup_image_sample_b_check.py @@ -456,6 +456,13 @@ def with_branch_before_sample(data, sopp_op): return data[:off] + insert + data[off:] +def with_divergent_back_edge_after_sample(data, sopp_op): + """Insert s_cbranch_ right after the sample_b, jumping back to it: the branch comes later in program order, but + the sample runs again on the next pass, with lanes that left the loop at different passes.""" + off, size = next((o, s) for o, s, _n, a in G.decode(data) if 'image_sample_b' in a) + return data[:off + size] + sopp(sopp_op, -(size // 4 + 1)) + data[off + size:] + + def controls(): assert WORDS, 'no recorded words' locate() @@ -469,7 +476,9 @@ def controls(): ('s_cbranch_vccz', lambda d: with_branch_before_sample(d, 6)), ('s_cbranch_vccnz', lambda d: with_branch_before_sample(d, 7)), ('s_cbranch_execz', lambda d: with_branch_before_sample(d, 8)), - ('s_cbranch_execnz', lambda d: with_branch_before_sample(d, 9))): + ('s_cbranch_execnz', lambda d: with_branch_before_sample(d, 9)), + ('s_cbranch_vccnz back edge after the sample', lambda d: with_divergent_back_edge_after_sample(d, 7)), + ('s_cbranch_execnz back edge after the sample', lambda d: with_divergent_back_edge_after_sample(d, 9))): try: G.Pipeline(VS_WORDS, mutate(plain), root_blob()).hlsl_ps() except G.Unsupported as error: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ea7bf66e6a..5a2cc11a17 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2685,6 +2685,8 @@ def translate(self): self.wqm_exec = init_wqm_exec # True until a wave-divergent branch: SampleBias / CalculateLevelOfDetail need uniform CF. self.uniform_cf = True + self.derivative_sites = [] # (offset, name) of image_sample_b / image_get_lod, for the back-edge proof + self.divergent_back_edges = [] # (target, branch offset) of divergent backward branches self.masks = set(init_masks) self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined) last_write = {} # SGPR -> offset of its last write in program order @@ -2865,6 +2867,7 @@ def translate(self): regs, affected = div_targets.get(off, (set(), set())) regs = {r for r in regs if isinstance(r, int)} if b_target <= off: + self.divergent_back_edges.append((b_target, off)) regs.update(r for r in joined.get(b_target, ()) if isinstance(r, int)) for tgt_off in affected: bad_at_target.setdefault(tgt_off, set()).update(regs) @@ -2922,6 +2925,15 @@ def translate(self): if refusals is None: raise Unsupported(reason) refusals.append((reason, self.kind)) + for at, name in self.derivative_sites: + # A divergent back edge that spans the call lets lanes of one quad leave the loop at different passes, so + # the call runs again with uneven quads even though no divergent branch precedes it in program order. + if any(target <= at <= branch for target, branch in self.divergent_back_edges): + reason = ('%s needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform ' + 'control flow' % name) + if refusals is None: + raise Unsupported(reason) + refusals.append((reason, self.kind)) self.pinned_low16_v.update(self.low16_only_v) try: self.check_vcc_paths() @@ -5252,6 +5264,8 @@ def image(self, ops, mods, how): not getattr(self, 'uniform_cf', True)): raise Unsupported('image_sample_b needs implicit derivatives: pixel stage with the entry EXEC ' 'mask and wave-uniform control flow') + if hasattr(self, 'derivative_sites'): + self.derivative_sites.append((self.pc, 'image_sample_b')) bias, cs = cs[0], cs[1:] if how == 'get_lod': # image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp @@ -5266,6 +5280,8 @@ def image(self, ops, mods, how): if not self.exec_known or not getattr(self, 'uniform_cf', True): raise Unsupported('image_get_lod needs implicit derivatives: pixel stage with the entry EXEC ' 'mask and wave-uniform control flow') + if hasattr(self, 'derivative_sites'): + self.derivative_sites.append((self.pc, 'image_get_lod')) desc_key = self.descriptor(ops[2]) tex = self.pipe.resource(desc_key, kinds[dim]) if how in ('load', 'load_mip'): From c8e0537584442261ae2d941c64ea43f76ee14949 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 02:22:21 +0000 Subject: [PATCH 4/4] test: allow s_mul_hi_* own-arity templates in scalar table check #2405 added s_mul_hi_i32 (and an early arity refuse for both mul_hi forms). The negative control still expected only one non-IndexError survivor. Co-authored-by: SimSalabimse --- ...startup_gfx2hlsl_scalar_table_arity_check.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/tests/startup_gfx2hlsl_scalar_table_arity_check.py b/tests/startup_gfx2hlsl_scalar_table_arity_check.py index 7a2d86ebcf..f33cff0f59 100644 --- a/tests/startup_gfx2hlsl_scalar_table_arity_check.py +++ b/tests/startup_gfx2hlsl_scalar_table_arity_check.py @@ -16,6 +16,9 @@ HERE = Path(__file__).resolve().parent SOURCE = HERE.parent / 'tools' / 'startup' / 'gfx2hlsl.py' +# Templates that refuse a short form in their own body (before the shared SCA arity guard). +OWN_ARITY = frozenset(('s_bfm_b32', 's_mul_hi_u32', 's_mul_hi_i32')) + def load(text=None): spec = importlib.util.spec_from_loader('gfx2hlsl_table', loader=None) @@ -91,17 +94,19 @@ def refusal(module, op, sources): changed.append(op) check('a complete form is never refused for its operand count', not changed, repr(changed[:4])) -# Negative control: with the guard removed the short form raises IndexError again. One template keeps its own -# arity check (s_bfm_b32 spells "expected 3" in its body), so it refuses either way and is excluded here rather -# than counted as a survivor. +# Negative control: with the guard removed the short form raises IndexError again. Templates that keep +# their own arity check refuse either way and are excluded here rather than counted as survivors. stripped = load(SOURCE.read_text(encoding='utf-8').replace(' if len(srcs) < needed:', ' if False:')) control = [op for op in TWO_SOURCE if refusal(stripped, op, needed_sources(stripped, op) - 1) == 'IndexError'] -check('control: without the guard the short form raises IndexError', len(control) >= len(TWO_SOURCE) - 1, +check('control: without the guard the short form raises IndexError', + len(control) >= len(TWO_SOURCE) - len(OWN_ARITY), '%d of %d' % (len(control), len(TWO_SOURCE))) kept = [op for op in TWO_SOURCE if op not in control] -check('the one template with its own arity check still refuses without the guard', - all(refusal(stripped, op, needed_sources(stripped, op) - 1).startswith(op) for op in kept), repr(kept)) +check('templates with their own arity check still refuse without the guard', + set(kept) <= OWN_ARITY and all( + refusal(stripped, op, needed_sources(stripped, op) - 1).startswith(op) for op in kept), + repr(kept)) print('scalar table arity checks: %d failed' % len(failures)) sys.exit(1 if failures else 0)