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
124 changes: 124 additions & 0 deletions tools/check_straight_pixel_quads.py
Original file line number Diff line number Diff line change
@@ -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())
1 change: 1 addition & 0 deletions tools/check_translator_gpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
112 changes: 112 additions & 0 deletions tools/reference/straight-pixel-quads/main.cpp
Original file line number Diff line number Diff line change
@@ -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<ID3D12Resource> 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<ID3D12Resource> 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<ID3DBlob> blob;
check(D3D12SerializeVersionedRootSignature(&rd, &blob, nullptr), "serialize root");
ComPtr<ID3D12RootSignature> 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<ID3D12PipelineState> 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<ID3D12DescriptorHeap> rtv;
check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtv)), "RTV heap");
auto rt = rtv->GetCPUDescriptorHandleForHeapStart();
device->CreateRenderTargetView(target.Get(), nullptr, rt);
ComPtr<ID3D12CommandAllocator> allocator;
ComPtr<ID3D12GraphicsCommandList> 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;
}
88 changes: 88 additions & 0 deletions tools/shader-compiler/examples/straight_pixel_quads.rs
Original file line number Diff line number Diff line change
@@ -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<u8> = 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);
}
}
}
2 changes: 2 additions & 0 deletions tools/shader-compiler/src/hlsl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,8 @@ struct Emitter<'a> {
pulled_attrs: BTreeSet<usize>,
/// 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<usize>,
dispatched: bool,
/// The reduction being emitted adds.
pixel_sum: bool,
Expand Down
6 changes: 4 additions & 2 deletions tools/shader-compiler/src/hlsl/driver/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
Expand Down Expand Up @@ -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"
Expand Down
5 changes: 5 additions & 0 deletions tools/shader-compiler/src/hlsl/emitter/control_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading