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
87 changes: 87 additions & 0 deletions tools/check_pixel_code_offset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Read back a translated pixel shader's bounded embedded-table accesses."""
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

TABLE = (101, 217, 333, 449)
GUARD = (17, 29, 43, 71)


def instrument(hlsl, axis):
# Only provide a varying input for the entry-live scalar s12. Leave the
# translated mask, address arithmetic, table, load and export untouched.
marker = " // 0x0000 s_getpc_b64"
if hlsl.count(marker) != 1 or hlsl.count("struct SIn {") != 1:
raise ValueError("unexpected pixel fixture")
return hlsl.replace("struct SIn {", "struct SIn { float4 position : SV_Position;").replace(
marker, f" s12 = (uint)i.position.{axis};\n" + marker)


def expected(axis, clipped):
out = bytearray()
for y in range(16):
for x in range(16):
val = TABLE[(x if axis == "x" else y) & 3]
color = (val,) * 4
if clipped and not (3 <= x < 11 and 3 <= y < 11):
color = GUARD
out.extend(struct.pack("<4I", *color))
return bytes(out)


def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ("hlsl", "dxc", "dxv", "provider", "proton", "prefix", "compiler-dir", "work", "output"):
parser.add_argument("--" + name, type=Path, required=True)
parser.add_argument("--adapter", required=True)
a = parser.parse_args()
if a.work.exists() or a.output.exists():
parser.error("fresh work and output required")
a.work.mkdir(parents=True)
rows = []
with TemporaryDirectory(dir=a.work) as tmp:
trial = Path(tmp)
hlsl = a.hlsl.read_text()
sources = {"vertex": ("vs_6_0", "float4 main(uint id:SV_VertexID):SV_Position { return float4(id==2?3:-1,id==1?3:-1,0.5,1); }"),
"copy": ("ps_6_0", instrument(hlsl, "x")), "inplace": ("ps_6_0", instrument(hlsl, "y"))}
for name, (profile, source) in sources.items():
src = trial / (name + ".hlsl")
dst = trial / (name + ".cso")
src.write_text(source)
subprocess.run([a.dxc, "-T", profile, "-E", "main", "-O3", "-Fo", dst, src], check=True, timeout=30)
subprocess.run([a.dxv, dst], check=True, timeout=30)
# Reuse the integer render-target fixture; its two filenames identify
# the two test axes here, not DPP operations.
exe, status, fields = run_gpu_guest(ROOT / "tools/reference/straight-pixel-quads/main.cpp",
"pixel-code-offset.exe", trial, a.work, a.proton, a.prefix, a.provider, a.compiler_dir,
extra_env={"TUXBOX_NULL_PIPELINES": "0"})
for name, axis in (("copy", "x"), ("inplace", "y")):
for clipped in (False, True):
case = name + ("_clipped" if clipped else "_full")
path = trial / (case + ".bin")
rows.append(dict(case=case, matched=path.is_file() and path.read_bytes() == expected(axis, clipped)))
result = dict(passed=status == 0 and fields.get("adapter") == a.adapter and all(r["matched"] for r in rows),
scope="Synthetic pixel code-table loads, entry-live scalar input instrumented",
adapter=fields.get("adapter"), cases=len(rows), pixels=256*len(rows),
compared_words=1024*len(rows), rows=rows,
hlsl_sha256=hashlib.sha256(a.hlsl.read_bytes()).hexdigest(),
provider_sha256=hashlib.sha256(a.provider.read_bytes()).hexdigest())
with a.output.open("x") as out:
json.dump(result, out, indent=2)
out.write("\n")
print(result)
return int(not result["passed"])


if __name__ == "__main__":
raise SystemExit(main())
2 changes: 2 additions & 0 deletions tools/check_translator_gpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ def assembled(tool, *extra):
"pixel-link-slot86": Check("check_slot86_portable_link", emitter="xshader", dxc=True),
"raw-index": Check("check_raw_index",
capture=("proven_byte_index_emits_addresses_without_widening_loads", "--hlsl")),
"pixel-code-offset": Check("check_pixel_code_offset",
capture=("pixel_embedded_table_offset_is_bounded_and_aligned", "--hlsl"), dxc=True),
"dynamic-cbv": Check("check_dynamic_cbv", capture=("bounded_dynamic_cbv", "--hlsl"), dxc=True),
"dynamic-code-offset": Check("check_dynamic_code_offset",
capture=("bounded_runtime_code_offset", "--hlsl")),
Expand Down
7 changes: 6 additions & 1 deletion tools/shader-compiler/src/hlsl/emitter/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,12 @@ impl<'a> Emitter<'a> {
}

pub(in crate::hlsl) fn dynamic_code_offset(&self, idx: usize) -> Option<u8> {
if self.ex.stage != Stage::Compute || self.packed.is_some() || self.mesh_bindings.is_some() {
// Embedded code data is immutable and addressed by the same GETPC
// and scalar byte-offset instructions in compute and pixel programs.
// The proof checks the full possible address interval, not a lane
// value or the host wave width.
if !matches!(self.ex.stage, Stage::Compute | Stage::Pixel)
|| self.packed.is_some() || self.mesh_bindings.is_some() {
return None;
}
code_offset::prove(&self.insns, idx, self.ex.isa.len(), self.ex.isa_data.len())
Expand Down
20 changes: 20 additions & 0 deletions tools/shader-compiler/src/tests/hlsl/pixel_quad.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,23 @@ fn distinguishes_saved_coverage_from_scalar_bits() {
assert!(!guards_expansion(&code, 2));
assert!(!saved_exec(&code, 4));
}

#[test]
fn pixel_embedded_table_offset_is_bounded_and_aligned() {
// gfx1030: getpc; mask and scale a scalar offset; load; export uint.
let words = [0xbe881f00, 0x870a830c, 0x8f0a820a, 0xf4000404,
0x14000020, 0x7e080210, 0xf800080f, 0x04040404, 0xbf810000];
let mut ex = pixel(&words);
ex.isa_data.extend([101u32, 217, 333, 449].iter().flat_map(|x| x.to_le_bytes()));
let translated = super::super::translate(&ex).unwrap();
assert!(translated.hlsl.contains("tb_code["));
assert!(translated.hlsl.contains("s8 + s10 + 0x20u - 36u"));
println!("BEGIN_HLSL\n{}\nEND_HLSL", translated.hlsl);
let mut bad = ex.clone();
bad.isa_data.truncate(48);
assert!(super::super::translate(&bad).is_err());
let mut bad = ex.clone();
bad.isa[8..12].copy_from_slice(&0x8f0a810au32.to_le_bytes()); // scale by 2, not 4
bad.isa_data[..36].copy_from_slice(&bad.isa);
assert!(super::super::translate(&bad).is_err());
}
Loading