From 656c4ddc9b0e656707fd865b1fb122b1977bfc0a Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Thu, 26 Nov 2026 18:13:25 -0600 Subject: [PATCH 1/3] shader: lower two immutable samplers at uniform explicit-LOD joins Admit a single forward SCC diamond with complete literal definitions of two normalized point samplers, preserve their static LOD limits and choose between complete SampleLevel calls. Exercise both runtime selector outcomes, swapped bindings, six refusals and all eight authored assembly variants. Register the fixture using upstream test-fragment conventions. --- docs/experiments.md | 2 +- docs/experiments/startup-sampler-join.md | 21 ++ .../startup_image_sample_l_join.txt | 1 + .../startup_image_sample_l_join.txt | 1 + tests/cmake/startup_image_sample_l_join.cmake | 10 + tests/offscreen_check.cpp | 14 +- tests/startup_image_3d.cpp | 20 +- tests/startup_image_get_lod_view_check.py | 8 +- tests/startup_image_sample_l_join_check.py | 203 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 81 +++++++ 10 files changed, 352 insertions(+), 9 deletions(-) create mode 100644 docs/experiments/startup-sampler-join.md create mode 100644 tests/checks/pixel-binary/startup_image_sample_l_join.txt create mode 100644 tests/checks/python-linux/startup_image_sample_l_join.txt create mode 100644 tests/cmake/startup_image_sample_l_join.cmake create mode 100644 tests/startup_image_sample_l_join_check.py diff --git a/docs/experiments.md b/docs/experiments.md index f9fb98d4ec..8ecf793477 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15043,7 +15043,7 @@ ctest --preset dev --no-tests=error -R '^startup_image_sample_b' -V The guest sampler's MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) clamp the LOD of every sample form. `tools/startup/gfx2hlsl.py` now carries them for `image_sample`, `image_sample_l` and `image_sample_lz` when the sampler is a constant, through the `smpl` manifest line and `decode_sampler` that `image_sample_b` introduced (#2051); the slice is #2177, split from the run-time heap case (#2221). The three forms share one validation with `image_sample_b`: a descriptor LOD bias (word 2 bits 19:0) and MIN_LOD above MAX_LOD are refused, with the form's own name in the message. Behavior change: a constant sampler with either of those fields set used to translate for these forms (limits ignored) and is now refused. A mip filter of 0 (mipmapping disabled) is not refused for these forms, unlike `image_sample_b` where the bias would count: such a sampler keeps its ordinary `smp` line and its previous behavior. Refusing it would drop every pipeline with an all-zero inline sampler (seven existing check scripts build one); `image_sample_lz` and `_l` with level 0 would be harmless anyway. The one-argument switch is `mip_filter_none_ok` in `Stage.lod_sampler_words`. Also changed: a constant sampler with a non-zero MAX_LOD now clamps the level (it was unbounded before), which is the intended fix. -Not changed: a sampler read through the sampler heap (table or default-sampler shortcut) keeps the ordinary static or heap sampler and is not validated; `translate_to` and `translate_compute` write one line per module to stderr (`: image_sample, image_sample_l through a sampler heap: sampler MIN_LOD, MAX_LOD and LOD bias are not validated (#2221)`). Since then the run-time heap table applies each entry's MIN_LOD and MAX_LOD (`dynamic_sampler()` in `src/startup_stubs/translated_sampler_bindings.h`, checked by `startup_sampler_lod_*`); the entry's LOD bias is not carried, a MIN_LOD above MAX_LOD is passed through unchanged, and the default-sampler shortcut keeps a static sampler with an unbounded LOD range. A sampler that is neither heap nor constant is refused as before. `image_sample_c` keeps its MAX_LOD rule. +Not changed: a sampler read through the sampler heap (table or default-sampler shortcut) keeps the ordinary static or heap sampler and is not validated; `translate_to` and `translate_compute` write one line per module to stderr (`: image_sample, image_sample_l through a sampler heap: sampler MIN_LOD, MAX_LOD and LOD bias are not validated (#2221)`). Since then the run-time heap table applies each entry's MIN_LOD and MAX_LOD (`dynamic_sampler()` in `src/startup_stubs/translated_sampler_bindings.h`, checked by `startup_sampler_lod_*`); the entry's LOD bias is not carried, a MIN_LOD above MAX_LOD is passed through unchanged, and the default-sampler shortcut keeps a static sampler with an unbounded LOD range. Other nonconstant samplers remain refused except for the [proven two-sampler explicit-LOD join](experiments/startup-sampler-join.md). `image_sample_c` keeps its MAX_LOD rule. `tests/startup_image_sample_lod_check.py` draws each form on its own (`startup_image_sample_lod_warp`, `startup_image_sample_lod_hardware`) against the 4x4, two-slice, three-mip array, point sampler with mip filter point, where all six cells differ. Each form's control is the same program through the ordinary `smp` line, which must read a different mip: `image_sample_l` with explicit level 2 and MAX_LOD 1 reads mip 1 (`smp`: mip 2); `image_sample` with MIN_LOD 2 above the implicit level 1 reads mip 2 (`smp`: mip 1); `image_sample_lz` with MIN_LOD 1 reads mip 1 (`smp`: mip 0). The implicit level 1 comes from the technique of the bias check: only the `u` initialiser of the translated HLSL is replaced by `0.75 + 0.5 * (SV_Position.x - 0.5)`, the `Sample` call is untouched. Refusal controls per form: bias, secondary bias and MIN_LOD 3 above MAX_LOD 2; accepted controls per form: mip filter 0 (`smp` line) and a heap sampler (table and default-sampler shortcut, logged once). The three `image_sample_b` discriminators are unchanged. Not covered: a fractional MIN_LOD or MAX_LOD, a linear mip filter, 1D, 3D and packed `a16` draws, the run-time heap sampler's LOD fields (#2221), and compute stages. diff --git a/docs/experiments/startup-sampler-join.md b/docs/experiments/startup-sampler-join.md new file mode 100644 index 0000000000..a169b6faec --- /dev/null +++ b/docs/experiments/startup-sampler-join.md @@ -0,0 +1,21 @@ +# Two inline samplers at a uniform forward join + +For 2D explicit-level `image_sample_l` and `image_sample_lz`, a single forward SCC diamond may select two inline four-word sampler definitions. Both arms must finish by writing all four words as literals, with proven uniform control flow and unchanged EXEC. Only normalized point wrap/clamp XY addressing and point mip filtering are admitted, with validated LOD limits. Two `smpl` static bindings preserve the descriptors; the selected runtime word chooses between complete `SampleLevel` calls. Any intervening overlap write invalidates the join proof. Implicit derivatives, partial definitions and more complex control flow retain their existing refusals. + +The source-built fixture exercises the emitted dispatcher against an independent point-texel oracle for both root-constant selector outcomes and both sample forms. Swapping the sampler bindings changes the result. Six refusal controls and eight binary assembly variants are included. + +Both portable checks passed on Apple Silicon with LLVM 23.1.6. + +```bash +python3 -B tests/startup_image_sample_l_join_check.py +python3 -B tests/startup_image_sample_l_join_check.py binary llvm-mc +``` + +The registered Windows draw consumes the actual translated shader, both manifest lines and the runtime selector. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^startup_image_sample_l_join_' -V +``` + +DXC/WARP/hardware draw execution requires Windows and remains unmeasured locally. diff --git a/tests/checks/pixel-binary/startup_image_sample_l_join.txt b/tests/checks/pixel-binary/startup_image_sample_l_join.txt new file mode 100644 index 0000000000..a0c9ab69c3 --- /dev/null +++ b/tests/checks/pixel-binary/startup_image_sample_l_join.txt @@ -0,0 +1 @@ +tests/startup_image_sample_l_join_check.py binary llvm-mc-15 diff --git a/tests/checks/python-linux/startup_image_sample_l_join.txt b/tests/checks/python-linux/startup_image_sample_l_join.txt new file mode 100644 index 0000000000..db8c2fa17b --- /dev/null +++ b/tests/checks/python-linux/startup_image_sample_l_join.txt @@ -0,0 +1 @@ +tests/startup_image_sample_l_join_check.py diff --git a/tests/cmake/startup_image_sample_l_join.cmake b/tests/cmake/startup_image_sample_l_join.cmake new file mode 100644 index 0000000000..5cf16c9087 --- /dev/null +++ b/tests/cmake/startup_image_sample_l_join.cmake @@ -0,0 +1,10 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_image_sample_l_join_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_l_join_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_l_join_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_l_join_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_image_sample_l_join_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index cdb1d28afd..ac4e1b348b 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1364,15 +1364,23 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -// --startup-image-2d-view prints one RGBA32F pixel. +// --startup-image-2d-view [0|1] prints one RGBA32F pixel. +// The optional selector is forwarded as the existing second root constant. OperationResult run_startup_image_2d_view(const OperationContext& ctx) { const std::string_view window = ctx.argv[6]; if (window.size() != 3 || window[1] != '/' || window[0] < '0' || window[0] > '2' || window[2] < '1' || window[2] > '3') return {OutcomeKind::fail, "expected a first/count mip window on a three-mip texture"}; + float selector = 0.0f; + if (ctx.argc == 8) { + if (std::strcmp(ctx.argv[7], "1") == 0) + selector = 1.0f; + else if (std::strcmp(ctx.argv[7], "0") != 0) + return {OutcomeKind::fail, "view selector must be 0 or 1"}; + } float color[4]{}; - check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], 0, color, ctx.argv[5], false, 3, false, true, + check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], selector, color, ctx.argv[5], false, 3, false, true, UINT(window[0] - '0'), UINT(window[2] - '0')); std::uint32_t bits[4]; std::memcpy(bits, color, sizeof(bits)); @@ -1717,7 +1725,7 @@ const OperationSpec kOperations[] = { {"--startup-image-1d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-1d-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, - {"--startup-image-2d-view", 7, 7, nullptr, kNoGate, run_startup_image_2d_view}, + {"--startup-image-2d-view", 7, 8, nullptr, kNoGate, run_startup_image_2d_view}, {"--startup-image-3d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-store", 7, 7, nullptr, kNoGate, run_startup_image_store}, {"--startup-image-2d-array", 7, 8, nullptr, kNoGate, run_startup_image_3d}, diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index 8305017fdf..ca700aa53c 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -78,8 +78,24 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const const auto vs = read_blob(vertex_path); const auto ps = read_blob(pixel_path); x2w_startup::TranslatedSamplers samplers; - if (!samplers.read_manifest_line(sampler_line) || samplers.statics.size() != 1) - throw std::runtime_error("Expected one inline sampler in the image 3D draw"); + const char* newline = std::strchr(sampler_line, '\n'); + if (!newline) { + if (!samplers.read_manifest_line(sampler_line) || samplers.statics.size() != 1) + throw std::runtime_error("Expected one inline sampler in the image 3D draw"); + } else { + const std::string first(sampler_line, newline); + const char* second = newline + 1; + int first_index = -1, second_index = -1; + if (!two_dimensional || !view_levels || std::strchr(second, '\n') || + (std::sscanf(first.c_str(), "smp %d", &first_index) != 1 && + std::sscanf(first.c_str(), "smpl %d", &first_index) != 1) || + (std::sscanf(second, "smp %d", &second_index) != 1 && + std::sscanf(second, "smpl %d", &second_index) != 1) || + first_index != 0 || second_index != 1 || + !samplers.read_manifest_line(first.c_str()) || !samplers.read_manifest_line(second) || + samplers.statics.size() != 2 || samplers.heap || samplers.comparison[0] || samplers.comparison[1]) + throw std::runtime_error("Expected two ordered noncomparison inline samplers in the 2D view draw"); + } const bool comparison = !samplers.comparison.empty() && samplers.comparison[0]; const auto root = create_root(device, samplers); diff --git a/tests/startup_image_get_lod_view_check.py b/tests/startup_image_get_lod_view_check.py index 9dd9652e8a..e3b6018eeb 100644 --- a/tests/startup_image_get_lod_view_check.py +++ b/tests/startup_image_get_lod_view_check.py @@ -45,9 +45,11 @@ def pipeline(step, low, high, mip_filter): return fixture.G.Pipeline(fixture.VS_WORDS, code, fixture.root_blob(flags=0), ps_hw_inputs=(0x8000, 0x8000)) -def read_pixel(renderer, adapter, vs, ps, sampler, view): - run = subprocess.run([renderer, adapter, '--startup-image-2d-view', vs, ps, sampler, view], - capture_output=True, text=True, timeout=30) +def read_pixel(renderer, adapter, vs, ps, sampler, view, *, selector=None): + args = [renderer, adapter, '--startup-image-2d-view', vs, ps, sampler, view] + if selector is not None: + args.append(str(selector)) + run = subprocess.run(args, capture_output=True, text=True, timeout=30) print(run.stdout, end='') if run.returncode == 77: print(run.stderr, file=sys.stderr) diff --git a/tests/startup_image_sample_l_join_check.py b/tests/startup_image_sample_l_join_check.py new file mode 100644 index 0000000000..f839607e86 --- /dev/null +++ b/tests/startup_image_sample_l_join_check.py @@ -0,0 +1,203 @@ +"""Source-built 2D point wrap/clamp samplers selected by a uniform SCC diamond. + +No arguments: portable translation and independent dispatcher/sample oracle. +binary : reassemble every recorded fixture. +draw : actual translated shader and manifest readback. +""" +import math +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob +from startup_image_sample_b_flow_check import PS_INPUTS, assemble +from startup_image_get_lod_view_check import read_pixel + +CLAMP_XY = 2 | (2 << 3) +PRE = '''s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0 +s_mov_b32 s26, 0x4000000 +s_mov_b32 s27, 0 +v_mov_b32_e32 v0, 0x3f900000 +v_mov_b32_e32 v1, 0x3ec00000 +v_mov_b32_e32 v2, 1.0 +''' +POST = '''s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm +''' + + +def arm(w0): + return (f's_mov_b32 s24, {w0:#x}\ns_mov_b32 s25, 0x200000\n' + 's_mov_b32 s26, 0x4000000\ns_mov_b32 s27, 0\n') + + +def source(name): + form = 'lz' if name == 'lz' else 'b' if name == 'implicit bias' else 'l' + pre = PRE + cond = 's_cmp_lg_u32 s9, 0\ns_cbranch_scc1 BB1\n' + if name == 'nonuniform': + pre = 'v_mov_b32_e32 v8, v0\n' + pre + cond = 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + taken = arm(CLAMP_XY | 0x8000 if name == 'invalid mode' else CLAMP_XY) + if name == 'partial': + taken = f's_mov_b32 s24, {CLAMP_XY:#x}\n' + tail = 's_mov_b32 s24, s9\n' if name == 'overwrite' else '' + if name == 'extra branch': + tail = 's_cbranch_scc1 BB3\nBB3:\n' + addr = 'v[0:1]' if form == 'lz' else 'v[0:2]' + return (pre + cond + arm(0) + 's_branch BB2\nBB1:\n' + taken + 'BB2:\n' + tail + + 's_waitcnt lgkmcnt(0)\n' + + f'image_sample_{form} v[4:7], {addr}, s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D\n' + + POST) + + +WORDS = { + 'l': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'lz': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f9cf00004c400703f8cbf0f1800f804050607000081bf', + 'nonuniform': '0003107e04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e8010847d070086bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'partial': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe010082bf920398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'overwrite': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe090398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'invalid mode': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe070082bfff0398be12800000ff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'implicit bias': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f94f00004c400703f8cbf0f1800f804050607000081bf', + 'extra branch': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe000085bf7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', +} +REFUSALS = { + 'nonuniform': 'descriptor operand s[24:27]', + 'partial': 'descriptor operand s[24:27]', + 'overwrite': 'descriptor operand s[24:27]', + 'invalid mode': 'unsupported joined sampler words', + 'implicit bias': 'image_sample_b with a sampler that is not constant', + 'extra branch': 'descriptor operand s[24:27]', +} + + +def pipeline(name): + return G.Pipeline(VS_WORDS, bytes.fromhex(WORDS[name]), root_blob(), ps_hw_inputs=PS_INPUTS) + + +def texel(mip, x, y): + return struct.pack('>4f', (1 + x + 4 * y + 32 * mip) / 128, x, y, 2 * mip) + + +# u=1.125 wraps to x=0 or clamps to the final column; v=0.375 is interior. +EXPECTED = {'l': (texel(1, 0, 0), texel(1, 1, 0)), 'lz': (texel(0, 0, 1), texel(0, 3, 1))} + + +def sampler_manifest(pipe): + lines = [line for line in pipe.manifest().splitlines() if line.startswith('smpl ')] + assert len(lines) == 2, lines + fields = [line.split() for line in lines] + assert [int(f[1]) for f in fields] == [0, 1], lines + samplers = [tuple(int(w, 0) for w in f[2:]) for f in fields] + assert set(samplers) == {(0, 0x200000, 1 << 26, 0), (CLAMP_XY, 0x200000, 1 << 26, 0)}, samplers + return lines, samplers + + +def selected_texel(text, samplers, selector): + """Execute this authored dispatcher subset and evaluate its selected point sample independently.""" + regs = {} + pc, scc = 0, False + call = re.compile(r't = \(s(\d+) == (0x[0-9a-f]+)u \? r0\.SampleLevel\(q(\d+), ' + r'float2\(F\(v0\), F\(v1\)\), (F\(v2\)|0)\) : r0\.SampleLevel\(q(\d+), ' + r'float2\(F\(v0\), F\(v1\)\), \4\)\);') + for block in re.finditer(r'^\s*if \(pc == (\d+)\) \{\n(.*?)^\s*\}', text, re.M | re.S): + if int(block[1]) != pc: + continue + for line in block[2].splitlines(): + line = line.strip() + m = re.fullmatch(r'([sv]\d+) = (0x[0-9a-f]+)u;', line) + if m: + regs[m[1]] = int(m[2], 16) + continue + m = re.fullmatch(r'scc = ud1 != (0x[0-9a-f]+)u;', line) + if m: + scc = selector != int(m[1], 16) + continue + m = re.fullmatch(r'pc = \(scc\) \? (\d+) : (\d+);', line) + if m: + pc = int(m[1 if scc else 2]) + continue + m = re.fullmatch(r'pc = (\d+);', line) + if m: + pc = int(m[1]) + continue + m = call.fullmatch(line) + if m: + q = int(m[3] if regs['s' + m[1]] == int(m[2], 16) else m[5]) + def f32(reg): + return struct.unpack('> 12) & 0xfff) // 256) + size = 4 >> mip + def address(coord, mode): + index = math.floor(coord * size) + return index % size if mode == 0 else min(max(index, 0), size - 1) + return texel(mip, address(f32('v0'), w0 & 7), address(f32('v1'), (w0 >> 3) & 7)) + raise AssertionError(f'unmodelled dispatcher statement: {line}') + raise AssertionError('dispatcher never sampled') + + +def controls(): + for name, (wrap, clamp) in EXPECTED.items(): + pipe = pipeline(name) + text = pipe.hlsl_ps() + _, samplers = sampler_manifest(pipe) + assert 'udsrc 1 rootconst 1 0' in pipe.manifest() + assert wrap != clamp + for selector, want in ((0, wrap), (0x3f800000, clamp)): + assert selected_texel(text, samplers, selector) == want, (name, selector) + assert selected_texel(text, samplers[::-1], selector) != want, (name, selector, 'swapped') + for name, reason in REFUSALS.items(): + try: + pipeline(name).hlsl_ps() + except G.Unsupported as error: + assert reason in str(error), (name, reason, str(error)) + else: + raise AssertionError(f'{name} unexpectedly accepted') + print('uniform sampler diamond: two forms, both selector outcomes, swapped bindings and six refusal controls passed') + + +def binary(llvm_mc): + for name, encoded in WORDS.items(): + assert assemble(llvm_mc, source(name)) == bytes.fromhex(encoded), name + print('all eight authored fixtures reassemble exactly') + + +def draw(dxc, renderer, adapter): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) + for name, expected in EXPECTED.items(): + pipe = pipeline(name) + ps = compile_hlsl(dxc, 'dxc', pipe.hlsl_ps(), f'joined_{name}', 'ps_6_0', directory) + lines, _ = sampler_manifest(pipe) + manifest = '\n'.join(lines) + for selector, want in enumerate(expected): + got = read_pixel(renderer, adapter, vs, ps, manifest, '0/3', selector=selector) + assert got == want, (name, selector, got.hex(), want.hex()) + swapped = '\n'.join(f'smpl {i} ' + ' '.join(line.split()[2:]) for i, line in enumerate(reversed(lines))) + got = read_pixel(renderer, adapter, vs, ps, swapped, '0/3', selector=0) + assert got == expected[1] and got != expected[0], (name, 'swapped', got.hex()) + print(f'{name}: actual uniform root selector and swapped binding readback matched') + + +if __name__ == '__main__': + args = sys.argv[1:] + if not args: + controls() + elif args[0] == 'binary' and len(args) == 2: + binary(args[1]) + elif args[0] == 'draw' and len(args) == 4: + draw(*args[1:]) + else: + raise SystemExit(__doc__) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 489148b039..03deccaef4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2854,6 +2854,59 @@ def const_words(self, tok): for n in range(r[1], r[2] + 1)] return None if any(w is None for w in words) else words + def sampler_join_shape(self, branches): + # A single forward SCC diamond, with all four final writes in each arm literal. + if (getattr(self, 'kind', None) != 'ps' or len(branches) != 2 or + not any(name in ('image_sample_l', 'image_sample_lz') for _, _, name, _ in self.ins)): + return None + (cond, taken), (skip, join) = sorted(branches) + if not cond < skip < taken < join: + return None + row = {off: (n, name) for off, n, name, _ in self.ins} + if (row[cond][1] not in ('s_cbranch_scc0', 's_cbranch_scc1') or + row[skip][1] != 's_branch' or skip + row[skip][0] != taken): + return None + literals = [set(), set()] + bases = set() + for off, _, name, asm in self.ins: + _, ops, mods = parse(asm) + if off < join and (writes_exec(name, ops) or (cond < off and name == 's_endpgm')): + return None + arm = 0 if cond < off < skip else 1 if taken <= off < join else None + if arm is not None: + dests = scalar_destinations(name, asm) + if 'any' in dests: + return None + literals[arm].difference_update(dests) + if (name == 's_mov_b32' and len(ops) == 2 and not mods and + re.fullmatch(r'(?:0x[0-9a-fA-F]+|\d+)', ops[1])): + literals[arm].update(dests) + if (off >= join and name in ('image_sample_l', 'image_sample_lz') and len(ops) == 4 + and 'dim:SQ_RSRC_IMG_2D' in mods): + r = reg_range(ops[3]) + if r and r[0] == 's' and r[2] == r[1] + 3 and r[2] <= 105: + regs = set(range(r[1], r[2] + 1)) + if all(regs <= written for written in literals): + bases.add(r[1]) + return cond, join, bases + + def joined_sampler_call(self, tex, operand, pair, uv, level, name): + for words in pair: + # Point-filtered normalized wrap/clamp, with an actual point mip filter. + w0, w1, w2, w3 = words + if (w0 & ~0x3f or (w0 & 7) not in (0, 2) or ((w0 >> 3) & 7) not in (0, 2) + or w1 & ~0xffffff or w2 != 1 << 26 or w3): + raise Unsupported('%s with unsupported joined sampler words' % name) + self.lod_sampler_words(name, words) + a, b = pair + base = reg_range(operand)[1] + k = next(i for i in range(4) if a[i] != b[i]) + self.used_s.add(base + k) + qa = self.pipe.sampler(a, lod_limits=True) + qb = self.pipe.sampler(b, lod_limits=True) + return '(s%d == 0x%08xu ? %s.SampleLevel(%s, %s, %s) : %s.SampleLevel(%s, %s, %s))' % ( + base + k, a[k], tex, qa, uv, level, tex, qb, uv, level) + def execz_refusals(self): """{offset: reason} for compute blocks that s_cbranch_execz skips and the one-lane model cannot run. @@ -3459,6 +3512,7 @@ def translate(self): execz_targets = set() if getattr(self, 'kind', None) == 'cs' else { t for t in targets if all(pc < t and names[pc] == 's_cbranch_execz' for pc, to in branches if to == t)} back_targets = {to for pc, to in branches if to <= pc} + sampler_diamond = self.sampler_join_shape(branches) if branches else None self.mesh_allocation_block = None splits = set(targets) if getattr(self, 'kind', None) == 'ms' and targets: @@ -3589,6 +3643,7 @@ def translate(self): incoming = {} kept = {} self.back_force = {} + self.sampler_joins = {} written = set(init_written) falls = True start = 0 @@ -3638,6 +3693,19 @@ def translate(self): arriving = ([({reg: self.sym.get(reg) for reg in here}, written & here)] if falls else []) + \ incoming.get(off, []) written = (written - here) | set().union(*(w for _, w in arriving)) + self.sampler_joins.clear() + if (sampler_diamond and off == sampler_diamond[1] and falls and len(arriving) == 2 + and self.exec_known and self.uniform_cf and sampler_diamond[0] in self.uniform_branches): + for base in sampler_diamond[2]: + regs = range(base, base + 4) + if any(forced.get(off, {}).get(r) is not None for r in regs): + continue + if not all(all(r in w and s.get(r) and s[r][0] == 'const' and len(s[r]) == 2 + for r in regs) for s, w in arriving): + continue + pair = tuple(tuple(s[r][1] & 0xffffffff for r in regs) for s, _ in arriving) + if pair[0] != pair[1]: + self.sampler_joins[base] = pair for reg in here: paths = [s[reg] for s, w in arriving if reg in w] force = forced.get(off, {}).get(reg) @@ -3722,6 +3790,10 @@ def translate(self): reg, 'run' if run_time_symbol(sym) else 'refuse') falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') dests = scalar_destinations(name, asm) + if self.sampler_joins and dests: + for base in tuple(self.sampler_joins): + if 'any' in dests or any(r in dests for r in range(base, base + 4)): + del self.sampler_joins[base] written |= every_sgpr if 'any' in dests else dests last_write.update(dict.fromkeys(every_sgpr if 'any' in dests else dests, off)) self._pre_fconst = dict(self.float_const_s) @@ -7268,6 +7340,11 @@ def image(self, ops, mods, how): heap = self.heap_sampler(ops[3]) words = None if heap else self.const_words(ops[3]) name = 'image_sample' + ('' if how == 'sample' else '_' + how) + sjoin = None + if dim == 'SQ_RSRC_IMG_2D' and how in ('l', 'lz') and not packed_2d and not heap and words is None: + r = reg_range(ops[3]) + if r and r[0] == 's' and r[2] == r[1] + 3: + sjoin = getattr(self, 'sampler_joins', {}).get(r[1]) if how == 'b': # The guest clamps the biased LOD to the sampler's MIN_LOD and MAX_LOD. Only a constant descriptor # can be read here, and only its limits are carried to the static sampler (line smpl), so a sampler @@ -7280,6 +7357,8 @@ def image(self, ops, mods, how): if heap or not words or self.default_sampler_words(words): raise Unsupported('image_get_lod with a sampler that is not constant (LOD limits and bias unknown)') smp = self.pipe.sampler(tuple(self.lod_sampler_words('image_get_lod', words)), lod_limits=True) + elif sjoin is not None: + smp = None elif how in ('sample', 'l', 'lz', 'd') and (heap or (words and self.default_sampler_words(words))): # A heap sampler, or the fixed default that stands in for one, keeps its unbounded static LOD range: the # descriptor is read at run time, so its MIN_LOD, MAX_LOD and bias are not validated here (#2221). @@ -7309,6 +7388,8 @@ def image(self, ops, mods, how): axes = len(grads[0]) dx, dy = ['float%d(%s)' % (axes, ', '.join(self.f(r) for r in g)) for g in grads] call = '%s.SampleGrad(%s, %s, %s, %s)' % (tex, smp, uv, dx, dy) + elif sjoin is not None: + call = self.joined_sampler_call(tex, ops[3], sjoin, uv, self.f(lod) if how == 'l' else '0', name) elif how == 'l': call = '%s.SampleLevel(%s, %s, %s)' % (tex, smp, uv, self.f(lod)) elif how == 'b': From d908804a32f4e01344b5bbfa122011b0d8376475 Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Thu, 26 Nov 2026 18:51:44 -0600 Subject: [PATCH 2/3] shader: cover sampler joins that differ only in maximum LOD Add the authored explicit-level selector-word-1 variant. Both selectors and swapped manifests exercise distinct mips; all nine gfx1013 sources reassemble exactly with LLVM 15.0.7. AI-assisted backport patch from x2w-microlift. --- docs/experiments/startup-sampler-join.md | 4 +-- tests/startup_image_sample_l_join_check.py | 36 ++++++++++++++-------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/docs/experiments/startup-sampler-join.md b/docs/experiments/startup-sampler-join.md index a169b6faec..aa10bf53cc 100644 --- a/docs/experiments/startup-sampler-join.md +++ b/docs/experiments/startup-sampler-join.md @@ -2,9 +2,9 @@ For 2D explicit-level `image_sample_l` and `image_sample_lz`, a single forward SCC diamond may select two inline four-word sampler definitions. Both arms must finish by writing all four words as literals, with proven uniform control flow and unchanged EXEC. Only normalized point wrap/clamp XY addressing and point mip filtering are admitted, with validated LOD limits. Two `smpl` static bindings preserve the descriptors; the selected runtime word chooses between complete `SampleLevel` calls. Any intervening overlap write invalidates the join proof. Implicit derivatives, partial definitions and more complex control flow retain their existing refusals. -The source-built fixture exercises the emitted dispatcher against an independent point-texel oracle for both root-constant selector outcomes and both sample forms. Swapping the sampler bindings changes the result. Six refusal controls and eight binary assembly variants are included. +The source-built fixture evaluates both root-constant selector outcomes for both sample forms with an independent point-texel oracle. A third variant holds word 0 unchanged and varies only MAX_LOD in word 1; the explicit level selects mip 1 or mip 0. Swapping sampler bindings changes the result in every variant. Six refusal controls and nine binary assembly variants are included. -Both portable checks passed on Apple Silicon with LLVM 23.1.6. +Both portable checks passed on Apple Silicon; the expanded nine-variant fixture was assembled with LLVM 15.0.7. ```bash python3 -B tests/startup_image_sample_l_join_check.py diff --git a/tests/startup_image_sample_l_join_check.py b/tests/startup_image_sample_l_join_check.py index f839607e86..87f8b5abe8 100644 --- a/tests/startup_image_sample_l_join_check.py +++ b/tests/startup_image_sample_l_join_check.py @@ -1,4 +1,4 @@ -"""Source-built 2D point wrap/clamp samplers selected by a uniform SCC diamond. +"""Source-built 2D point samplers with differing address modes or maximum LOD. No arguments: portable translation and independent dispatcher/sample oracle. binary : reassemble every recorded fixture. @@ -35,8 +35,8 @@ ''' -def arm(w0): - return (f's_mov_b32 s24, {w0:#x}\ns_mov_b32 s25, 0x200000\n' +def arm(w0, w1=0x200000): + return (f's_mov_b32 s24, {w0:#x}\ns_mov_b32 s25, {w1:#x}\n' 's_mov_b32 s26, 0x4000000\ns_mov_b32 s27, 0\n') @@ -48,6 +48,8 @@ def source(name): pre = 'v_mov_b32_e32 v8, v0\n' + pre cond = 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' taken = arm(CLAMP_XY | 0x8000 if name == 'invalid mode' else CLAMP_XY) + if name == 'l_word1': + taken = arm(0, 0) if name == 'partial': taken = f's_mov_b32 s24, {CLAMP_XY:#x}\n' tail = 's_mov_b32 s24, s9\n' if name == 'overwrite' else '' @@ -63,6 +65,7 @@ def source(name): WORDS = { 'l': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', 'lz': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f9cf00004c400703f8cbf0f1800f804050607000081bf', + 'l_word1': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe050082bf800398be800399beff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', 'nonuniform': '0003107e04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e8010847d070086bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', 'partial': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe010082bf920398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', 'overwrite': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe090398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', @@ -89,16 +92,22 @@ def texel(mip, x, y): # u=1.125 wraps to x=0 or clamps to the final column; v=0.375 is interior. -EXPECTED = {'l': (texel(1, 0, 0), texel(1, 1, 0)), 'lz': (texel(0, 0, 1), texel(0, 3, 1))} +EXPECTED = { + 'l': (texel(1, 0, 0), texel(1, 1, 0)), + 'lz': (texel(0, 0, 1), texel(0, 3, 1)), + 'l_word1': (texel(1, 0, 0), texel(0, 0, 1)), +} -def sampler_manifest(pipe): +def sampler_manifest(pipe, name): lines = [line for line in pipe.manifest().splitlines() if line.startswith('smpl ')] assert len(lines) == 2, lines fields = [line.split() for line in lines] assert [int(f[1]) for f in fields] == [0, 1], lines samplers = [tuple(int(w, 0) for w in f[2:]) for f in fields] - assert set(samplers) == {(0, 0x200000, 1 << 26, 0), (CLAMP_XY, 0x200000, 1 << 26, 0)}, samplers + expected = ({(0, 0, 1 << 26, 0), (0, 0x200000, 1 << 26, 0)} if name == 'l_word1' + else {(0, 0x200000, 1 << 26, 0), (CLAMP_XY, 0x200000, 1 << 26, 0)}) + assert set(samplers) == expected, samplers return lines, samplers @@ -148,13 +157,13 @@ def address(coord, mode): def controls(): - for name, (wrap, clamp) in EXPECTED.items(): + for name, expected in EXPECTED.items(): pipe = pipeline(name) text = pipe.hlsl_ps() - _, samplers = sampler_manifest(pipe) + _, samplers = sampler_manifest(pipe, name) assert 'udsrc 1 rootconst 1 0' in pipe.manifest() - assert wrap != clamp - for selector, want in ((0, wrap), (0x3f800000, clamp)): + assert expected[0] != expected[1] + for selector, want in zip((0, 0x3f800000), expected): assert selected_texel(text, samplers, selector) == want, (name, selector) assert selected_texel(text, samplers[::-1], selector) != want, (name, selector, 'swapped') for name, reason in REFUSALS.items(): @@ -164,13 +173,14 @@ def controls(): assert reason in str(error), (name, reason, str(error)) else: raise AssertionError(f'{name} unexpectedly accepted') - print('uniform sampler diamond: two forms, both selector outcomes, swapped bindings and six refusal controls passed') + print(f'uniform sampler diamond: {len(EXPECTED)} forms, both selector outcomes, ' + f'swapped bindings and {len(REFUSALS)} refusal controls passed') def binary(llvm_mc): for name, encoded in WORDS.items(): assert assemble(llvm_mc, source(name)) == bytes.fromhex(encoded), name - print('all eight authored fixtures reassemble exactly') + print(f'all {len(WORDS)} authored fixtures reassemble exactly') def draw(dxc, renderer, adapter): @@ -180,7 +190,7 @@ def draw(dxc, renderer, adapter): for name, expected in EXPECTED.items(): pipe = pipeline(name) ps = compile_hlsl(dxc, 'dxc', pipe.hlsl_ps(), f'joined_{name}', 'ps_6_0', directory) - lines, _ = sampler_manifest(pipe) + lines, _ = sampler_manifest(pipe, name) manifest = '\n'.join(lines) for selector, want in enumerate(expected): got = read_pixel(renderer, adapter, vs, ps, manifest, '0/3', selector=selector) From 8697fe94dd30ad99e5f6df7192dc3408ccb7918c Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Thu, 26 Nov 2026 19:56:06 -0600 Subject: [PATCH 3/3] test: pin upper sampler word1 refusal at uniform joins Exercise a decoded sampler diamond whose only invalid field is bit 24 of word 1. AI-assisted backport patch from x2w-microlift. --- docs/experiments/startup-sampler-join.md | 4 ++-- tests/startup_image_sample_l_join_check.py | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/experiments/startup-sampler-join.md b/docs/experiments/startup-sampler-join.md index aa10bf53cc..eb6efeb2b4 100644 --- a/docs/experiments/startup-sampler-join.md +++ b/docs/experiments/startup-sampler-join.md @@ -2,9 +2,9 @@ For 2D explicit-level `image_sample_l` and `image_sample_lz`, a single forward SCC diamond may select two inline four-word sampler definitions. Both arms must finish by writing all four words as literals, with proven uniform control flow and unchanged EXEC. Only normalized point wrap/clamp XY addressing and point mip filtering are admitted, with validated LOD limits. Two `smpl` static bindings preserve the descriptors; the selected runtime word chooses between complete `SampleLevel` calls. Any intervening overlap write invalidates the join proof. Implicit derivatives, partial definitions and more complex control flow retain their existing refusals. -The source-built fixture evaluates both root-constant selector outcomes for both sample forms with an independent point-texel oracle. A third variant holds word 0 unchanged and varies only MAX_LOD in word 1; the explicit level selects mip 1 or mip 0. Swapping sampler bindings changes the result in every variant. Six refusal controls and nine binary assembly variants are included. +The source-built fixture evaluates both root-constant selector outcomes for both sample forms with an independent point-texel oracle. A third variant holds word 0 unchanged and varies only MAX_LOD in word 1; the explicit level selects mip 1 or mip 0. Swapping sampler bindings changes the result in every variant. A decoded negative diamond keeps every field valid but sets bit 24 of word 1, above the whole-word-1 mask, so the guard refuses it as unsupported joined sampler words. Seven refusal controls and ten binary assembly variants are included. -Both portable checks passed on Apple Silicon; the expanded nine-variant fixture was assembled with LLVM 15.0.7. +Both portable checks passed on Apple Silicon; the expanded ten-variant fixture was assembled with LLVM 15.0.7. ```bash python3 -B tests/startup_image_sample_l_join_check.py diff --git a/tests/startup_image_sample_l_join_check.py b/tests/startup_image_sample_l_join_check.py index 87f8b5abe8..3cbd4d4d77 100644 --- a/tests/startup_image_sample_l_join_check.py +++ b/tests/startup_image_sample_l_join_check.py @@ -8,6 +8,7 @@ import re import struct import sys +import subprocess import tempfile from pathlib import Path @@ -50,6 +51,9 @@ def source(name): taken = arm(CLAMP_XY | 0x8000 if name == 'invalid mode' else CLAMP_XY) if name == 'l_word1': taken = arm(0, 0) + if name == 'high word1': + # Bit 24 of word1 sits above the translator's whole-word1 mask; a sampler keeping it must be refused. + taken = arm(CLAMP_XY, 0x200000 | (1 << 24)) if name == 'partial': taken = f's_mov_b32 s24, {CLAMP_XY:#x}\n' tail = 's_mov_b32 s24, s9\n' if name == 'overwrite' else '' @@ -70,6 +74,7 @@ def source(name): 'partial': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe010082bf920398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', 'overwrite': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe090398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', 'invalid mode': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe070082bfff0398be12800000ff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'high word1': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002001ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', 'implicit bias': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f94f00004c400703f8cbf0f1800f804050607000081bf', 'extra branch': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe000085bf7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', } @@ -78,6 +83,7 @@ def source(name): 'partial': 'descriptor operand s[24:27]', 'overwrite': 'descriptor operand s[24:27]', 'invalid mode': 'unsupported joined sampler words', + 'high word1': 'unsupported joined sampler words', 'implicit bias': 'image_sample_b with a sampler that is not constant', 'extra branch': 'descriptor operand s[24:27]', }