Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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. 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
Expand Down
51 changes: 39 additions & 12 deletions tests/startup_gfx2hlsl_image_get_lod_check.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
"""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) 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. 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, 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 <dxc> [fxc]: also compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1).
"""
import struct
Expand All @@ -34,7 +37,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('<I', (simm & 0xffff) | op << 16 | 0x17f << 23)


def stage(dmask=1, dim=1, branch=False, divergent=False, join=False, cf_op=None, word2=MIP_POINT, back_op=None):
w = bytearray(C.WORDS['lz'])
assert w[W2_AT:W2_AT + 4] == bytes.fromhex('80039abe'), w[W2_AT:W2_AT + 4].hex()
w[W2_AT:W2_AT + 4] = struct.pack('<II', 0xbe9a03ff, word2) # s_mov_b32 s26, literal
Expand All @@ -44,8 +51,19 @@ def stage(dmask=1, dim=1, branch=False, word2=MIP_POINT):
if dmask == 3: # export v4, v5
struct.pack_into('<II', w, EXPORT_AT, 0xf800180f, 4 | 5 << 8 | 4 << 16 | 5 << 24)
code = bytes(w)
if branch: # s_cbranch_scc0 to the next instruction: control flow before the read
code = code[:AT] + struct.pack('<I', 0xbf840000) + code[AT:]
if back_op is not None: # s_cbranch_<op> 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)
if join: # uniform forward join; every lane still has the entry EXEC at the read
insert += (bytes.fromhex('800380be') + bytes.fromhex('008006bf') + sopp(5, 1) + bytes.fromhex('810381be'))
if divergent: # s_mov_b32 exec_lo, 0: the entry-mask proof is gone
insert += bytes.fromhex('8003febe')
if cf_op is not None: # s_mov; s_cbranch_<op> +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


Expand Down Expand Up @@ -74,9 +92,17 @@ def controls():
assert call in text and 'v4 = U(t.x);' in text and 'v5 = U(t.y);' in text, text
_, text = ps(stage(dmask=2)) # the unclamped LOD alone lands in the first destination register
assert call in text and 'v4 = U(t.y);' in text and 'U(t.x)' not in text, text
_, text = ps(stage(branch=True))
assert call in text and 'v4 = U(t.x);' in text, text
_, text = ps(stage(join=True))
assert call in text and 'v4 = U(t.x);' in text, text
refused(stage(dmask=4), 'image_get_lod form')
refused(stage(dim=5), 'image_get_lod form') # SQ_RSRC_IMG_2D_ARRAY
refused(stage(branch=True), 'image_get_lod needs implicit derivatives')
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')
refused(stage(word2=0), 'image_get_lod with mipmapping disabled')
saved = G.Stage.op_image_get_lod
Expand All @@ -85,8 +111,9 @@ def controls():
refused(stage(), 'image_get_lod')
finally:
G.Stage.op_image_get_lod = saved
print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3; dmask 0x4, a 2D array, a branch, '
'a sampler bias and a sampler without mipmapping refused; refused without the handler')
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, vcc/exec branches, a sampler bias and a '
'sampler without mipmapping refused; refused without the handler')
return pipe


Expand Down
17 changes: 11 additions & 6 deletions tests/startup_gfx2hlsl_scalar_table_arity_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Loading
Loading