From 5cd728f82f0e7b6bc5455779a611b1741b4428be Mon Sep 17 00:00:00 2001 From: user Date: Wed, 25 Nov 2026 17:07:39 +1300 Subject: [PATCH] xshader: lower converged pixel quad swaps Use direct X and Y quad reads for proven whole-quad pixel prefixes. Keep independent wave width requirements and refuse exchanges with unverified control flow. --- tools/check_straight_pixel_quads.py | 124 +++++++++++++ tools/check_translator_gpu.py | 1 + tools/reference/straight-pixel-quads/main.cpp | 112 ++++++++++++ .../examples/straight_pixel_quads.rs | 88 +++++++++ tools/shader-compiler/src/hlsl.rs | 2 + .../src/hlsl/driver/pipeline.rs | 6 +- .../src/hlsl/emitter/control_flow.rs | 5 + .../src/hlsl/emitter/scalar.rs | 8 +- .../shader-compiler/src/hlsl/emitter/setup.rs | 1 + tools/shader-compiler/src/hlsl/pixel_quad.rs | 68 ++++++- .../src/tests/hlsl/pixel_quad.rs | 172 ++++++++++++++++++ 11 files changed, 582 insertions(+), 5 deletions(-) create mode 100644 tools/check_straight_pixel_quads.py create mode 100644 tools/reference/straight-pixel-quads/main.cpp create mode 100644 tools/shader-compiler/examples/straight_pixel_quads.rs diff --git a/tools/check_straight_pixel_quads.py b/tools/check_straight_pixel_quads.py new file mode 100644 index 00000000..9c2f9369 --- /dev/null +++ b/tools/check_straight_pixel_quads.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Check synthetic nonheap FI=1 DPP16 pixel X/Y swaps with GPU readback. + +The check compares full-target and scissored draws with an integer CPU oracle, +and records whether translation rejects a control with a guarded prefix. +""" +import argparse +import hashlib +import json +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from tools.frosty_gpu_guest import run_gpu_guest + +SIDE = 16 +GUARD = (17, 29, 43, 71) + + +def sha(path): + """Return the SHA-256 identity of one tool, shader, or readback file.""" + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def expected(variant, clipped): + """Return expected little-endian RGBA uints for one draw. + + ``variant`` selects copy-style or in-place X/Y swaps. ``clipped`` preserves + the clear color outside the draw rectangle, including helper lanes whose + positions remain defined by the oversized triangle. + """ + def value(x, y): + """Encode integer pixel coordinates as a distinct per-pixel value.""" + return 99 + x + 32 * y + + pixels = [] + for y in range(SIDE): + for x in range(SIDE): + original = value(x, y) + across_x = value(x ^ 1, y) + across_y = value(x, y ^ 1) + value(x ^ 1, y ^ 1) + total = across_y + (original + across_x if variant == "copy" else across_x) + color = (across_x, across_y, total, original) + if clipped and not (3 <= x < 11 and 3 <= y < 11): + color = GUARD + pixels.append(struct.pack("<4I", *color)) + return b"".join(pixels) + + +def main(argv=None): + """Compile emitter output, run four GPU draws, and write a JSON report. + + Required paths identify the emitter, provider, Proton files, source prefix, + compiler DLLs, work directory, and new report file; ``--adapter`` selects + the expected GPU. The report records shader and tool hashes, guest status, + guarded-prefix refusal, and exact results for four 16-by-16 readbacks. + """ + ap = argparse.ArgumentParser(description=__doc__) + for name in ("emitter", "provider", "proton", "prefix", "compiler-dir", "dxc", "dxv", "work", "output"): + ap.add_argument("--" + name, type=Path, required=True) + ap.add_argument("--adapter", required=True) + a = ap.parse_args(argv) + if a.work.exists() or a.output.exists(): + ap.error("fresh work/output required") + a.work.mkdir(parents=True) + fingerprints = {name: sha(getattr(a, name)) for name in ("emitter", "provider", "dxc", "dxv")} + rows, shaders = [], {} + with TemporaryDirectory(dir=a.work) as tmp: + trial = Path(tmp) + negative = subprocess.run([a.emitter, "guarded"], capture_output=True, text=True, timeout=15) + refused = negative.returncode == 1 and not negative.stdout and ( + "wave operation requires complete 32-lane compute waves" in negative.stderr) + sources = {"vertex": "float4 main(uint id:SV_VertexID):SV_Position { return float4(id==2?3:-1,id==1?3:-1,0.5,1); }"} + for variant in ("copy", "inplace"): + sources[variant] = subprocess.check_output([a.emitter, variant], text=True, timeout=15) + for name, source in sources.items(): + hlsl = trial / (name + ".hlsl") + hlsl.write_text(source) + blob = trial / (name + ".cso") + subprocess.run([a.dxc, "-T", "vs_6_0" if name == "vertex" else "ps_6_6", "-E", "main", "-O3", "-Fo", blob, hlsl], + check=True, timeout=30) + subprocess.run([a.dxv, blob], check=True, timeout=30) + shaders[name] = {"hlsl_sha256": sha(hlsl), "dxil_sha256": sha(blob)} + exe, status, fields = run_gpu_guest( + ROOT / "tools/reference/straight-pixel-quads/main.cpp", "straight-pixel-quads.exe", + trial, a.work, a.proton, a.prefix, a.provider, a.compiler_dir, + extra_env={"TUXBOX_NULL_PIPELINES": "0"}) + for variant in ("copy", "inplace"): + for clipped in (False, True): + name = variant + ("_clipped" if clipped else "_full") + want = expected(variant, clipped) + path = trial / (name + ".bin") + data = path.read_bytes() if path.is_file() else b"" + row = dict(case=name, matched=data == want, expected_sha256=hashlib.sha256(want).hexdigest(), + actual_sha256=hashlib.sha256(data).hexdigest(), actual_bytes=len(data)) + if len(data) == len(want) and data != want: + offset = next(i for i in range(0, len(want), 16) if data[i:i+16] != want[i:i+16]) + row.update(first_mismatch_pixel=[offset // 16 % SIDE, offset // 16 // SIDE], + expected=list(struct.unpack_from("<4I", want, offset)), + actual=list(struct.unpack_from("<4I", data, offset))) + rows.append(row) + unchanged = fingerprints == {name: sha(getattr(a, name)) for name in fingerprints} + report = dict(schema=1, scope="Synthetic nonheap FI=1 DPP16 pixel axis swaps", + passed=status == 0 and fields.get("adapter") == a.adapter.lower() and unchanged + and refused and all(row["matched"] for row in rows), + adapter=fields.get("adapter"), guest_exit=status, cases=len(rows), pixels=SIDE*SIDE*len(rows), + guarded_refused=refused, guarded_exit=negative.returncode, guarded_error=negative.stderr.strip(), + tools_unchanged=unchanged, tools_sha256=fingerprints, guest_sha256=sha(exe), shaders=shaders, rows=rows) + if fields.get("error"): + report["error"] = fields["error"] + with a.output.open("x") as stream: + json.dump(report, stream, indent=2) + stream.write("\n") + print(report["passed"], report["cases"], report["pixels"], "guarded_refused", refused, + "failures", sum(not row["matched"] for row in rows), report.get("error", "")) + return int(not report["passed"]) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/check_translator_gpu.py b/tools/check_translator_gpu.py index 6d09f9b5..3fee4e88 100644 --- a/tools/check_translator_gpu.py +++ b/tools/check_translator_gpu.py @@ -56,6 +56,7 @@ def assembled(tool, *extra): "lockstep": Check("check_lockstep_gpu", emitter="lockstep", llvm=True, dxc=True), "dpp8-exchange": Check("check_dpp8_exchange", emitter="lone_lane_probe", dxc=True), "pixel-heap-offsets": Check("check_pixel_heap_offsets", emitter="pixel_heap_offsets", dxc=True), + "straight-pixel-quads": Check("check_straight_pixel_quads", emitter="straight_pixel_quads", dxc=True), "pixel-link": Check("check_portable_pixel_link", emitter="xshader", dxc=True), "pixel-link-slot86": Check("check_slot86_portable_link", emitter="xshader", dxc=True), "raw-index": Check("check_raw_index", diff --git a/tools/reference/straight-pixel-quads/main.cpp b/tools/reference/straight-pixel-quads/main.cpp new file mode 100644 index 00000000..e62426e7 --- /dev/null +++ b/tools/reference/straight-pixel-quads/main.cpp @@ -0,0 +1,112 @@ +// Synthetic uint render-target readback for nonheap FI=1 DPP16 axis swaps. +// Shared control headers include a static upload helper unused by this draw-only guest. +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" +#endif +#include "../independent-shaders/context.h" +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +using namespace shader_control; +static constexpr UINT side = 16, pitch = 256, bytes = side * pitch; + +// Create and return the fixed-size uint render target used for exact component +// comparisons. The device supplies allocation, and the caller owns the resource. +static ComPtr target_image(ID3D12Device* device) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = d.Height = side; + d.DepthOrArraySize = d.MipLevels = d.SampleDesc.Count = 1; + d.Format = DXGI_FORMAT_R32G32B32A32_UINT; + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + D3D12_HEAP_PROPERTIES hp{}; + hp.Type = D3D12_HEAP_TYPE_DEFAULT; + hp.CreationNodeMask = hp.VisibleNodeMask = 1; + ComPtr target; + check(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&target)), "target"); + return target; +} + +// Draw the named translated shader with full or clipped scissor coverage, then +// save its uint pixels under a name derived from the shader and coverage mode. +// The oversized triangle covers scissor helper lanes, so their position inputs +// remain defined while the clear color identifies pixels outside the scissor. +static void draw(Context& ctx, const std::string& shader, bool clipped) { + auto device = ctx.device.Get(); + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rd{}; + rd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + ComPtr blob; + check(D3D12SerializeVersionedRootSignature(&rd, &blob, nullptr), "serialize root"); + ComPtr root; + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&root)), "root"); + auto vs = read_shader("vertex"), ps = read_shader(shader); + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.Get(); + pd.VS = {vs.data(), vs.size()}; + pd.PS = {ps.data(), ps.size()}; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.SampleDesc.Count = 1; + pd.SampleMask = UINT_MAX; + pd.NumRenderTargets = 1; + pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_UINT; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + ComPtr pipeline; + check(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pipeline)), "pipeline"); + auto target = target_image(device); + auto readback = buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr rtv; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtv)), "RTV heap"); + auto rt = rtv->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.Get(), nullptr, rt); + ComPtr allocator; + ComPtr list; + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), pipeline.Get(), + IID_PPV_ARGS(&list)), "list"); + const float guard[]{17, 29, 43, 71}; + list->ClearRenderTargetView(rt, guard, 0, nullptr); + list->OMSetRenderTargets(1, &rt, FALSE, nullptr); + list->SetGraphicsRootSignature(root.Get()); + D3D12_VIEWPORT vp{0, 0, side, side, 0, 1}; + D3D12_RECT rect = clipped ? D3D12_RECT{3, 3, 11, 11} : D3D12_RECT{0, 0, side, side}; + list->RSSetViewports(1, &vp); + list->RSSetScissorRects(1, &rect); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + transition(list.Get(), target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION from{}, to{}; + from.pResource = target.Get(); + from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + to.pResource = readback.Get(); + to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + to.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_UINT, side, side, 1, pitch}}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + submit_and_wait(device, ctx.queue.Get(), list.Get()); + write_buffer(readback.Get(), shader + (clipped ? "_clipped" : "_full"), bytes); +} + +// Run both register layouts in full and clipped coverage modes. Write adapter +// and guest errors to result.txt, and return nonzero when setup or drawing fails. +int main() { + FILE* report{}; + if (fopen_s(&report, "result.txt", "wb")) return 2; + int status = 0; + try { + Context ctx(report); + for (const char* shader : {"copy", "inplace"}) { + draw(ctx, shader, false); + draw(ctx, shader, true); + } + } catch (const std::exception& e) { + std::fprintf(report, "error=%s\n", e.what()); + status = 1; + } + return std::fclose(report) ? 2 : status; +} diff --git a/tools/shader-compiler/examples/straight_pixel_quads.rs b/tools/shader-compiler/examples/straight_pixel_quads.rs new file mode 100644 index 00000000..3d71d543 --- /dev/null +++ b/tools/shader-compiler/examples/straight_pixel_quads.rs @@ -0,0 +1,88 @@ +//! Independently authored nonheap FI=1 DPP16 pixel programs for GPU readback. +//! +//! The emitted programs use `SV_Position` as their pixel-coordinate input and +//! export exact unsigned integer values through `SV_Target`. +//! +//! # Boundaries +//! +//! This example constructs synthetic shader metadata and ISA, then delegates +//! translation to `tuxbox_xshader`. Its outputs are translated HLSL on stdout +//! and translation diagnostics on stderr. +use tuxbox_xshader::{hlsl, ShaderExtract, Stage}; + +/// Build a synthetic pixel shader for a selected quad-swap case. +/// +/// `variant` is `copy`, `inplace`, or `guarded`; the returned shader declares +/// `SV_Position` input and unsigned `SV_Target` output. Position seeds the +/// pixel-coordinate registers, and integer exports preserve exact lane values. +fn shader(variant: &str) -> ShaderExtract { + let mut words = vec![ + 0xbe88047eu32, // s_mov_b64 s[8:9], exec: preserve raster coverage. + 0xbefe0a7e, // s_wqm_b64 exec, exec: evaluate complete quads. + 0x7e040f02, 0x7e060f03, // Convert pixel X/Y to unsigned integers. + 0x34060685, 0x4a080702, // v4 = x + (y << 5). + 0x4a0808ff, 99, // f(x,y) = 99 + x + 32*y. + ]; + match variant { + "copy" | "guarded" => words.extend([ + 0x7e0a02fa, 0xff0cb104, // v5 = X(v4), FI=1, full row/bank masks. + 0x4a0c0905, // v6 = v5 + v4. + 0x7e0e02fa, 0xff0c4e06, // v7 = Y(v6), FI=1. + 0x4a140f06, // v10 = v7 + v6. + 0x87fe087e, // Restore original coverage for export. + 0xf800180f, 0x040a0705, // Export v5,v7,v10,v4 as uint RGBA. + ]), + "inplace" => words.extend([ + 0x7e160304, // v11 = v4: preserve the unswapped input. + 0x7e0802fa, 0xff0cb104, // v4 = X(v4), FI=1. + 0x4a0c1704, // v6 = v4 + v11. + 0x7e0c02fa, 0xff0c4e06, // v6 = Y(v6), FI=1 (in-place). + 0x4a140906, // v10 = v6 + v4. + 0x87fe087e, + 0xf800180f, 0x0b0a0604, // Export v4,v6,v10,v11. + ]), + _ => panic!("variant must be copy, inplace, or guarded"), + } + words.push(0xbf810000); // s_endpgm. + if variant == "guarded" { + // A scalar branch before the first exchange invalidates convergence proof. + words.insert(2, 0xbf840002); // s_cbranch_scc0 skips both position conversions. + } + let isa: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + ShaderExtract { + stage: Stage::Pixel, shader_model: (6, 6), required_features: None, + bitcode_stripped: true, fspx_config: None, ps09_pixel_inputs: None, + fssm: Vec::new(), entry: Some("main".into()), isa_data: isa.clone(), isa, + isa_offset_in_fssm: 0, psv_threads: None, flat_inputs: Vec::new(), + flat_outputs: Vec::new(), isa_preamble: [0, 64, 1, 1], + has_input_sig: true, has_output_sig: true, has_psv0: false, + has_root_sig: false, input_sig: vec![tuxbox_xshader::meta::SigElement { + name: "SV_Position".into(), index: 0, sysval: 1, comp_type: 3, + register: 0, mask: 15, rw_mask: 15, + }], + output_sig: vec![tuxbox_xshader::meta::SigElement { + name: "SV_Target".into(), index: 0, sysval: 64, comp_type: 1, + register: 0, mask: 15, rw_mask: 15, + }], resources: Vec::new(), gs_info: None, mesh_info: None, + primitive_sig: Vec::new(), root_sig: None, + } +} + +/// Translate the `copy`, `inplace`, or `guarded` command-line variant. +/// +/// Successful translation prints native `ps_6_6` HLSL to stdout. Translation +/// refusal prints the diagnostic to stderr and exits with status 1. +fn main() { + let variant = std::env::args().nth(1).expect("variant: copy, inplace, guarded"); + match hlsl::translate(&shader(&variant)) { + Ok(t) => { + assert_eq!(t.profile, "ps_6_6"); + assert_eq!(t.required_wave_size, None); + print!("{}", t.hlsl); + } + Err(error) => { + eprintln!("{error}"); + std::process::exit(1); + } + } +} diff --git a/tools/shader-compiler/src/hlsl.rs b/tools/shader-compiler/src/hlsl.rs index 2b320999..1f349a03 100644 --- a/tools/shader-compiler/src/hlsl.rs +++ b/tools/shader-compiler/src/hlsl.rs @@ -357,6 +357,8 @@ struct Emitter<'a> { pulled_attrs: BTreeSet, /// Each pixel is a wave of its own. pixel_wave: bool, + /// Entry WQM proven to dominate converged nonheap pixel axis swaps. + straight_pixel_quad: Option, dispatched: bool, /// The reduction being emitted adds. pixel_sum: bool, diff --git a/tools/shader-compiler/src/hlsl/driver/pipeline.rs b/tools/shader-compiler/src/hlsl/driver/pipeline.rs index a3dd57df..7a4c65d4 100644 --- a/tools/shader-compiler/src/hlsl/driver/pipeline.rs +++ b/tools/shader-compiler/src/hlsl/driver/pipeline.rs @@ -272,6 +272,8 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti em.pixel_wave = ex.stage == Stage::Pixel && em.pixel_heap && scan_width.is_none() && register_wave_size.is_none() && em.insns.iter().all(|i| i.op != wave_sum::DPP_REDUCE || i.enc != Enc::Vop2 || matches!(i.mnemonic.as_str(), "v_and_b32" | "v_or_b32" | "v_min_u32" | "v_max_u32" | "v_min_f32" | "v_max_f32" | "v_add_nc_u32" | "v_add_f32")); + em.straight_pixel_quad = (ex.stage == Stage::Pixel && !em.pixel_heap) + .then(|| pixel_quad::straight_prefix(&em.insns)).flatten(); let required_wave_size = if em.pixel_wave { None } else { required_wave_size }; let required_wave_size = required_wave_size.or(scan_width).or(register_wave_size).or((requires_ballot || !em.vote_uses.is_empty()).then_some(64)); // With more than 32 threads, rows 2 and 3 could instead be rows 0 and 1 of @@ -285,7 +287,7 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti { return Err("asymmetric DPP16 row mask requires a known guest wave width".into()); } - let required_wave_size = required_wave_size.or((uses_quad_add && (!em.pixel_wave || em.insns.iter().any(is_row_move)) || uses_bpermute || group_extrema).then_some(32)); + let required_wave_size = required_wave_size.or((uses_quad_add && em.straight_pixel_quad.is_none() && (!em.pixel_wave || em.insns.iter().any(is_row_move)) || uses_bpermute || group_extrema).then_some(32)); // A ballot or minimum over active invocations also works in the final // partial subgroup. Keep the full-wave requirement for every other user. let partial_election = required_wave_size.is_none() && election == Some(ElectionLowering::Native32); @@ -498,7 +500,7 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti "cs_6_6" } else if em.compute_heap && !is_ps { "cs_6_6" - } else if em.uses_heap_sampler || em.resource_heap_base.is_some() || em.pixel_heap { + } else if em.uses_heap_sampler || em.resource_heap_base.is_some() || em.pixel_heap || em.straight_pixel_quad.is_some() { "ps_6_6" } else if probe_trace { "cs_6_5" diff --git a/tools/shader-compiler/src/hlsl/emitter/control_flow.rs b/tools/shader-compiler/src/hlsl/emitter/control_flow.rs index d7f4a531..7f131e56 100644 --- a/tools/shader-compiler/src/hlsl/emitter/control_flow.rs +++ b/tools/shader-compiler/src/hlsl/emitter/control_flow.rs @@ -222,6 +222,11 @@ impl<'a> Emitter<'a> { } if self.pixel_wave && !is_row_move(ins) { self.emit_pixel_quad_exchange(i, ins)?; + } else if self.straight_pixel_quad.is_some() { + // Prefix analysis proves converged FI=1 axis moves with full row/bank masks. + let source = r(&ins.src[0])?; + let axis = if ins.aux.imm == 0xb1 { "X" } else { "Y" }; + self.line(&format!("uint q{i} = QuadReadAcross{axis}({source});")); } else { let source = r(&ins.src[0])?; if ins.op == OP_DPP_BINARY { diff --git a/tools/shader-compiler/src/hlsl/emitter/scalar.rs b/tools/shader-compiler/src/hlsl/emitter/scalar.rs index dbf8a874..e50c48f7 100644 --- a/tools/shader-compiler/src/hlsl/emitter/scalar.rs +++ b/tools/shader-compiler/src/hlsl/emitter/scalar.rs @@ -252,7 +252,11 @@ impl<'a> Emitter<'a> { self.tmp += 1; let wide = m.ends_with("_b64"); let lane_mask = is_ps && pixel_quad::saved_exec(&self.insns, idx); - if s[0] == Opnd::ExecLo && lone_lane::on() { + let straight_entry = self.straight_pixel_quad == Some(idx) && !self.dispatched; + if straight_entry { + // Entry WQM activates the complete quad, including helper lanes. + self.line(&format!("uint t{t}l = 1u, t{t}h = 0u;")); + } else if s[0] == Opnd::ExecLo && lone_lane::on() { self.line(&format!("uint t{t}l = exec_lo & 1u, t{t}h = 0u;")); } else if s[0] == Opnd::ExecLo && !self.resolve_wave32 { self.line("#if __SHADER_TARGET_MAJOR >= 6"); @@ -279,7 +283,7 @@ impl<'a> Emitter<'a> { } else { "0u".into() }; self.line(&format!("uint t{t}h = {upper};")); } - if s[0] == Opnd::ExecLo && !self.resolve_wave32 && !lone_lane::on() { + if !straight_entry && s[0] == Opnd::ExecLo && !self.resolve_wave32 && !lone_lane::on() { self.line(&format!("scc = any(t{t}ballot != 0u);")); } else if !lane_mask { self.line(&format!("scc = ((t{t}l | t{t}h) != 0u);")); diff --git a/tools/shader-compiler/src/hlsl/emitter/setup.rs b/tools/shader-compiler/src/hlsl/emitter/setup.rs index a3a45c27..ad5e2e76 100644 --- a/tools/shader-compiler/src/hlsl/emitter/setup.rs +++ b/tools/shader-compiler/src/hlsl/emitter/setup.rs @@ -139,6 +139,7 @@ impl<'a> Emitter<'a> { // in the same register still occupies an attribute slot; d26fd88ff8712f9e). pulled_attrs: BTreeSet::new(), pixel_wave: false, + straight_pixel_quad: None, dispatched: false, pixel_sum: false, flat_attrs: BTreeSet::new(), diff --git a/tools/shader-compiler/src/hlsl/pixel_quad.rs b/tools/shader-compiler/src/hlsl/pixel_quad.rs index 26fd7455..fc386959 100644 --- a/tools/shader-compiler/src/hlsl/pixel_quad.rs +++ b/tools/shader-compiler/src/hlsl/pixel_quad.rs @@ -1,6 +1,72 @@ //! A saved EXEC is represented by one bit per host invocation. WQM on //! that value must exchange bits with the other three pixels of the quad. -use super::{Emitter, Enc, Insn, Opnd, writes_scalar}; +//! +//! Boundaries: this module admits the straight-prefix optimization only when +//! decoded instructions and raw DPP16 fields prove converged axis moves. +use super::{Emitter, Enc, Insn, Opnd, writes_scalar, is_quad_exchange, OP_QUAD_MOVE}; + +/// Return the entry WQM index for converged FI=1 axis swaps in a straight prefix. +/// Raw DPP16 fields and lowered operands must agree before bypassing wave lane reads. +/// After the final swap, branches may target only instruction boundaries beyond that +/// swap (or the program end); no tail backedge may re-enter the converged prefix. +pub(super) fn straight_prefix(code: &[Insn]) -> Option { + let last = code.iter().rposition(is_quad_exchange)?; + let mut entry = None; + for (at, ins) in code.iter().enumerate() { + let m = ins.mnemonic.as_str(); + if is_quad_exchange(ins) && !straight_axis_move(ins) { + return None; + } + // Only resolved relative scalar branches have a known destination. + let branch = ins.enc == Enc::Sopp && Emitter::branch_cond(ins.op).is_some(); + if m.contains("branch") && !branch + || matches!(m, "s_setpc_b64" | "s_swappc_b64" | "s_rfe_b64" | "s_call_b64") { + return None; + } + if branch { + let target = ins.offset as i64 + 4 + 4 * ins.aux.imm; + let end = code.last().map(|i| (i.offset + i.dwords * 4) as i64)?; + if at <= last || target <= code[last].offset as i64 + || !(target == end || code.binary_search_by_key(&target, |i| i.offset as i64).is_ok()) { + return None; + } + } + if at > last { continue; } + if m.starts_with("s_endpgm") || matches!(m, "s_sendmsghalt" | "s_trap" | "s_sethalt") + || m.starts_with("v_cmpx") || m.contains("_saveexec_") || m.contains("_wrexec_") { + return None; + } + let writes_exec = ins.dst.iter().any(|o| matches!(o, Opnd::ExecLo | Opnd::ExecHi)); + if writes_exec { + if entry.is_some() || m != "s_wqm_b64" || ins.dst != [Opnd::ExecLo] + || ins.src != [Opnd::ExecLo] { + return None; + } + entry = Some(at); + } + // Entry setup may save EXEC or load scalar constants, but vector work + // must see the whole quad from its first instruction onward. + if entry.is_none() && !(m.starts_with("s_") || m == "v_nop") { + return None; + } + } + entry +} + +/// Admit only native VOP1 DPP16 axis moves with FI=1 and every destination enabled. +/// The raw opcode, registers and selector must match their lowered representation. +fn straight_axis_move(ins: &Insn) -> bool { + let [word, control] = ins.raw.as_slice() else { return false }; + ins.enc == Enc::Vop1 && ins.op == OP_QUAD_MOVE && ins.mnemonic == "v_mov_b32" + && ins.dwords == 2 && word & 0xfe01_ffff == 0x7e00_02fa + && control >> 24 == 0xff && control & (1 << 18) != 0 + // Bit 17 is reserved; source modifiers are outside this integer-move proof. + && control & 0x00f2_0000 == 0 && ins.aux.sdwa.is_none() + && matches!(ins.aux.imm, 0xb1 | 0x4e) + && ins.aux.imm == i64::from((control >> 8) & 0x1ff) + && ins.src == [Opnd::Vgpr(*control as u8)] + && ins.dst == [Opnd::Vgpr((word >> 17) as u8)] +} pub(super) fn saved_exec(code: &[Insn], at: usize) -> bool { let op = &code[at]; diff --git a/tools/shader-compiler/src/tests/hlsl/pixel_quad.rs b/tools/shader-compiler/src/tests/hlsl/pixel_quad.rs index 75e9125a..facafe49 100644 --- a/tools/shader-compiler/src/tests/hlsl/pixel_quad.rs +++ b/tools/shader-compiler/src/tests/hlsl/pixel_quad.rs @@ -1,6 +1,178 @@ use super::*; use crate::rdna2::disassemble; +/// Assemble a pixel program with saved coverage, WQM, X/Y swaps, and a masked export. +fn axis_words() -> Vec { + vec![ + 0xbe88047e, 0xbefe0a7e, 0x7e040f02, 0x7e060f03, + 0x34060685, 0x4a080702, 0x4a0808ff, 99, + 0x7e0a02fa, 0xff0cb104, 0x4a0c0905, 0x7e0e02fa, + 0xff0c4e06, 0x4a140f06, 0x87fe087e, 0xf800180f, + 0x040a0705, 0xbf810000, + ] +} + +/// Build a nonheap pixel extraction whose ISA is supplied as instruction words. +fn pixel(words: &[u32]) -> crate::ShaderExtract { + let isa: Vec<_> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + crate::ShaderExtract { + stage: crate::Stage::Pixel, shader_model: (5, 0), required_features: None, + bitcode_stripped: true, fspx_config: None, ps09_pixel_inputs: None, + fssm: Vec::new(), entry: Some("main".into()), isa_data: isa.clone(), isa, + isa_offset_in_fssm: 0, psv_threads: None, flat_inputs: Vec::new(), + flat_outputs: Vec::new(), isa_preamble: [0, 64, 1, 1], has_input_sig: false, + has_output_sig: false, has_psv0: false, has_root_sig: false, + input_sig: Vec::new(), output_sig: vec![super::super::SigElement { + name: "SV_Target".into(), index: 0, sysval: 64, comp_type: 1, + register: 0, mask: 15, rw_mask: 15, + }], resources: Vec::new(), + gs_info: None, mesh_info: None, primitive_sig: Vec::new(), root_sig: None, + } +} + +/// Decode test words and apply the DPP lowering used by shader translation. +fn lowered(words: &[u32]) -> Vec { + let mut code = disassemble(&pixel(words).isa); + super::super::lower_wave_reductions(&mut code).unwrap(); + code +} + +/// Axis swaps in a proven straight prefix lower to quad reads without a fixed wave width. +#[test] +fn straight_nonheap_axis_swaps_translate_without_wave_width() { + let translated = super::super::translate(&pixel(&axis_words())).unwrap(); + assert_eq!(translated.profile, "ps_6_6"); + assert_eq!(translated.required_wave_size, None); + let h = &translated.hlsl; + assert!(h.contains("QuadReadAcrossX(v4)"), "{h}"); + assert!(h.contains("QuadReadAcrossY(v6)"), "{h}"); + assert!(!h.contains("WaveReadLaneAt("), "{h}"); + assert!(!h.contains("QuadReadAcrossDiagonal("), "{h}"); + assert!(!h.contains("WaveActiveBallot("), "{h}"); + assert!(h.contains("l = 1u, t"), "{h}"); + assert!(h.contains("scc = ((t"), "{h}"); +} + +/// NOP setup and a forward branch over the masked export retain prefix eligibility. +#[test] +fn straight_prefix_accepts_nop_setup_and_forward_masked_tail() { + let mut words = axis_words(); + words.insert(0, 0x7e000000); // v_nop padding before entry setup. + // The branch after the last swap skips only the masked export. + words.insert(16, 0xbf880002); + assert_eq!(straight_prefix(&lowered(&words)), Some(2)); + let translated = super::super::translate(&pixel(&words)).unwrap(); + assert_eq!(translated.required_wave_size, None); + assert_eq!(translated.profile, "ps_6_6"); + assert!(translated.hlsl.contains("QuadReadAcrossX(v4)")); + assert!(translated.hlsl.contains("QuadReadAcrossY(v6)")); +} + +/// Prefix analysis rejects unsafe control flow, EXEC changes, and other quad exchanges. +#[test] +fn straight_prefix_refuses_unsafe_nonheap_translation() { + for replacement in [ + 0xbf840002, // SCC branch guarding part of the prefix. + 0xbf810000, // Early end before either exchange. + 0x87fe087e, // Mask EXEC with saved coverage before either exchange. + ] { + let mut words = axis_words(); + words[2] = replacement; + assert_eq!(straight_prefix(&lowered(&words)), None); + assert!(super::super::translate(&pixel(&words)).is_err()); + } + let mut words = axis_words(); + words[9] = 0xff0c0004; // Broadcast is outside the admitted axis permutations. + assert_eq!(straight_prefix(&lowered(&words)), None); + assert!(super::super::translate(&pixel(&words)).is_err()); + let mut words = axis_words(); + words.insert(17, 0xbf82fff0); // Backedge into the prefix at byte offset 8. + assert_eq!(straight_prefix(&lowered(&words)), None); + assert!(super::super::translate(&pixel(&words)).is_err()); +} + +/// FI, bank and row masks, and selectors determine axis-prefix eligibility. +#[test] +fn straight_prefix_requires_fi_full_masks_and_axis_controls() { + for control in [ + 0xff08_b104, // FI=0; bound control remains enabled. + 0xff04_b104, // FI=1 also works with bound control disabled. + 0xfe0c_b104, // One bank disabled. + 0xef0c_b104, // One row disabled. + 0xff0c_e404, // Identity permutation. + 0xff0c_1b04, // Diagonal permutation. + 0xff0c_4e04, // Y is admitted independently of X. + ] { + let mut words = axis_words(); + words[9] = control; + let admitted = matches!(control, 0xff04_b104 | 0xff0c_4e04); + assert_eq!(straight_prefix(&lowered(&words)).is_some(), admitted, "{control:08x}"); + let translated = super::super::translate(&pixel(&words)); + if admitted { + assert_eq!(translated.unwrap().required_wave_size, None); + } else { + assert!(translated.is_err(), "neighboring pixel DPP remains refused: {control:08x}"); + } + } +} + +/// Raw instruction fields and lowered operands must agree for prefix eligibility. +#[test] +fn straight_prefix_checks_raw_and_lowered_move_provenance() { + let code = lowered(&axis_words()); + let at = code.iter().position(is_quad_exchange).unwrap(); + for (word, mask) in [(0, 1), (0, 1 << 9), (1, 1 << 17), (1, 1 << 20), + (1, 1 << 21), (1, 1 << 22), (1, 1 << 23), + (1, 1), (1, 1 << 8)] { + let mut changed = code.clone(); + changed[at].raw[word] ^= mask; + assert_eq!(straight_prefix(&changed), None, "word={word} mask={mask:x}"); + } + let mut changed = code.clone(); + changed[at].src[0] = Opnd::Vgpr(99); + assert_eq!(straight_prefix(&changed), None); + let mut changed = code.clone(); + changed[at].dst[0] = Opnd::Vgpr(99); + assert_eq!(straight_prefix(&changed), None); + let mut changed = code.clone(); + changed[at].dwords = 1; + assert_eq!(straight_prefix(&changed), None); + let mut changed = code; + changed[at].raw.pop(); + assert_eq!(straight_prefix(&changed), None); +} + +/// An independent bpermute still imposes its wave-width requirement. +#[test] +fn straight_prefix_preserves_independent_wave_width() { + let mut words = axis_words(); + // DS bpermute v11, v0, v4 independently requires a wave32 mapping. + words.splice(14..14, [0xdacc_0000, 0x0b00_0400]); + assert_eq!(straight_prefix(&lowered(&words)), Some(1)); + let error = super::super::translate(&pixel(&words)).err().unwrap(); + assert_eq!(error, "wave operation requires complete 32-lane compute waves"); +} + +/// Prefix eligibility requires entry WQM before vector work and excludes implicit EXEC writes. +#[test] +fn straight_prefix_checks_entry_and_implicit_exec_writes() { + let code = lowered(&axis_words()); + assert_eq!(straight_prefix(&code), Some(1)); + for mnemonic in ["v_cmpx_eq_u32", "s_and_saveexec_b64", "s_and_wrexec_b64"] { + let mut changed = code.clone(); + changed[3].mnemonic = mnemonic.into(); + assert_eq!(straight_prefix(&changed), None); + } + let mut late_entry = code.clone(); + late_entry.swap(1, 2); + assert_eq!(straight_prefix(&late_entry), None); + for mnemonic in ["s_setpc_b64", "s_swappc_b64", "s_rfe_b64", "s_call_b64"] { + let mut indirect = code.clone(); + indirect.last_mut().unwrap().mnemonic = mnemonic.into(); + assert_eq!(straight_prefix(&indirect), None); + } +} + #[test] fn distinguishes_saved_coverage_from_scalar_bits() { // save EXEC, mask it with VCC, subtract it from the saved coverage,