diff --git a/runtime/d3d12/src/device/shader_cache.rs b/runtime/d3d12/src/device/shader_cache.rs index 28fffb70..499a822a 100644 --- a/runtime/d3d12/src/device/shader_cache.rs +++ b/runtime/d3d12/src/device/shader_cache.rs @@ -344,6 +344,64 @@ fn with_root(shader: &[u8], root: &[u8]) -> Option> { Some(input) } +fn replace_mesh_root( + shader: &[u8], + root: &[u8], + dxbc: &tuxbox_dxbc::Dxbc, + embedded: &tuxbox_dxbc::Chunk, +) -> Option> { + // Shift subsequent parts by a multiple of four, even for unaligned payload lengths. + let padding = (embedded.size % 4 + 4 - root.len() % 4) % 4; + let span = root.len().checked_add(padding)?; + let size = (shader.len() - embedded.size).checked_add(span)?; + if size > MAX_BYTES || root.is_empty() { return None; } + let mut input = Vec::with_capacity(size); + input.extend_from_slice(&shader[..embedded.offset - 4]); + input[4..20].fill(0); + input[24..28].copy_from_slice(&(size as u32).to_le_bytes()); + for (index, part) in dxbc.chunks.iter().enumerate() { + if part.offset > embedded.offset { + let offset = part.offset - 8 - embedded.size + span; + input[32 + 4 * index..36 + 4 * index].copy_from_slice(&(offset as u32).to_le_bytes()); + } + } + input.extend_from_slice(&(root.len() as u32).to_le_bytes()); + input.extend_from_slice(root); + input.resize(embedded.offset + span, 0); + input.extend_from_slice(&shader[embedded.offset + embedded.size..]); + Some(input) +} + +#[cfg(test)] +#[test] +fn replacing_a_mesh_root_preserves_the_other_parts_and_the_directory_order() { + use tuxbox_dxbc::Dxbc; + fn words(values: &[u32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() + } + let empty = words(&[1, 0, 0, 0, 0, 0]); + let constants = words(&[1, 1, 24, 0, 0, 0, 1, 7, 36, 1, 0, 4]); + // The root is first on disk and last in the directory. + let mut shader = Vec::from(*b"DXBC"); + shader.extend_from_slice(&[1; 16]); + shader.extend(words(&[1, 84, 2, 72, 40])); + shader.extend_from_slice(b"RTS0"); + shader.extend(words(&[24])); + shader.extend_from_slice(&empty); + shader.extend_from_slice(b"DXIL"); + shader.extend(words(&[4, 0xd0065])); + for expected in [&constants, &empty] { + let dxbc = Dxbc::parse(&shader).unwrap(); + shader = replace_mesh_root(&shader, expected, &dxbc, dxbc.chunk(b"RTS0").unwrap()).unwrap(); + let parsed = Dxbc::parse(&shader).unwrap(); + assert_eq!(parsed.digest, [0; 16]); + let [code, root] = parsed.chunks.as_slice() else { panic!("expected two parts") }; + assert_eq!((code.fourcc, root.fourcc), (*b"DXIL", *b"RTS0")); + assert_eq!(&shader[code.offset..code.offset + code.size], 0xd0065u32.to_le_bytes()); + assert_eq!(&shader[root.offset..root.offset + root.size], expected); + } +} + /// Console mesh stages always use a DXIL container. Resolve stripped programs /// before the host call and require portable replacements to match the stage. pub(super) fn mesh_stage( @@ -354,10 +412,19 @@ pub(super) fn mesh_stage( match shader_code(shader) { Some((stage, ShaderCode::Portable)) if stage == expected => Ok(None), Some((stage, ShaderCode::Xbox)) if stage == expected => { - let rooted = root.and_then(|root| with_root(shader, root)); - let Some(rooted) = rooted else { + let Some(root) = root else { return translate(shader, stage).map(Some).ok_or(E_NOTIMPL); }; + let dxbc = tuxbox_dxbc::Dxbc::parse(shader).map_err(|_| E_INVALIDARG)?; + if let Some(embedded) = dxbc.chunk(b"RTS0") { + if &shader[embedded.offset..embedded.offset + embedded.size] == root { + return translate(shader, stage).map(Some).ok_or(E_NOTIMPL); + } + // A PSO root overrides the embedded layout. A replacement keyed only + // by the original shader would resolve registers against the wrong root. + let variant = replace_mesh_root(shader, root, &dxbc, embedded).ok_or(E_INVALIDARG)?; + return translate(&variant, stage).map(Some).ok_or(E_NOTIMPL); + } // Preserve explicit precompiled replacements indexed by the // original bytecode. On-demand answers include the pipeline root. if let Some(source) = source_digest(shader) @@ -366,6 +433,7 @@ pub(super) fn mesh_stage( stage.report(&source, true); return Ok(Some(compiled)); } + let rooted = with_root(shader, root).ok_or(E_INVALIDARG)?; translate(&rooted, stage).map(Some).ok_or(E_NOTIMPL) } _ => Err(E_INVALIDARG), diff --git a/tests/test_float_to_integer.py b/tests/test_float_to_integer.py new file mode 100644 index 00000000..b7a07194 --- /dev/null +++ b/tests/test_float_to_integer.py @@ -0,0 +1,73 @@ +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess +from tempfile import TemporaryDirectory +import unittest + +from tools.reference.scarlett_worker_fixture import container, pack + + +def native_shader(code): + shader = container(code, resources=[(7, 0, 0, 0)]) + # Extend the fixture's two-chunk directory with a root table for UAV u0. + root = b"RTS0" + pack([64, 1, 1, 24, 0, 0, 0, 0, 0, 36, 1, 44, 1, 1, 0, 0, 0]) + first, second = struct.unpack_from(" observed : register(u0);\n" + + body + "\n" + "\n".join(stores) + "\n}\n") + subprocess.run([dxc, "-E", "main", "-T", "cs_6_0", "-Fc", listing, + "-Fo", directory / "shader.cso", hlsl], check=True, timeout=30) + self.assertEqual(parse_stores(listing.read_text(), len(cases)), expected) diff --git a/tests/test_fract_f32.py b/tests/test_fract_f32.py new file mode 100644 index 00000000..33cee724 --- /dev/null +++ b/tests/test_fract_f32.py @@ -0,0 +1,40 @@ +import os +from pathlib import Path +import re +import shutil +import subprocess +from tempfile import TemporaryDirectory +import unittest + + +class FractF32Tests(unittest.TestCase): + def test_tiny_inputs_and_guest_denormal_modes(self): + dxc = os.environ.get("DXC") or shutil.which("dxc") + if not dxc: + self.skipTest("DXC is required for the HLSL numerical regression") + cases = [ + # Input bits, MODE register, expected result bits. + (0xb3000000, 0, 0x3f7fffff), (0xb2ffffff, 0, 0x3f7fffff), + (0xb4000000, 0, 0x3f7ffffe), (0x33000000, 0, 0x33000000), + (0xbfa00000, 0, 0x3f400000), (0x80000000, 0, 0), + (0x80000001, 0, 0), (0x80000001, 0x10, 0x3f7fffff), + (0x80000001, 0x20, 0), (0x80000001, 0x30, 0x3f7fffff), + (1, 0x10, 0), (1, 0x20, 0), (1, 0x30, 1), + ] + helpers = Path(__file__).resolve().parents[1] / "tools/shader-compiler/src" + with TemporaryDirectory() as directory: + shader = Path(directory) / "test.hlsl" + code = ['#include "fract_f32.hlsl"', 'uint main() : SV_Target { uint result = 0u;'] + for i, (bits, mode, expected) in enumerate(cases): + code.append(f"result |= uint(asuint(tb_fract_f32(asfloat({bits:#x}u), {mode}u))" + f" == {expected:#x}u) << {i};") + shader.write_text("\n".join([*code, "return result; }"])) + ir = shader.with_suffix(".ll") + process = subprocess.run([dxc, "-T", "ps_6_0", "-E", "main", "-I", helpers, + "-Fo", shader.with_suffix(".cso"), "-Fc", ir, shader], + capture_output=True, text=True, timeout=30) + self.assertEqual(process.returncode, 0, process.stderr) + output = re.search(r"call void @dx\.op\.storeOutput\.i32\([^\n]+i32 (\d+)\)", ir.read_text()) + self.assertIsNotNone(output, "expected one constant pixel output") + mask = int(output.group(1)) + self.assertEqual([case for i, case in enumerate(cases) if not mask & (1 << i)], []) diff --git a/tests/test_half_rounding.py b/tests/test_half_rounding.py new file mode 100644 index 00000000..69680785 --- /dev/null +++ b/tests/test_half_rounding.py @@ -0,0 +1,144 @@ +import os +from pathlib import Path +import re +import shutil +import subprocess +from tempfile import TemporaryDirectory +import unittest + +from tools.reference.scarlett_worker_fixture import container + + +class HalfRoundingTests(unittest.TestCase): + def check_inline_results(self, cases): + self.check_register_results((words, 0xa5a50000 | low) for words, low in cases) + + def check_register_results(self, cases): + xshader = os.environ.get("TUXBOX_XSHADER") or shutil.which("xshader") + dxc = os.environ.get("DXC") or shutil.which("dxc") + if not (xshader and dxc): + self.skipTest("set TUXBOX_XSHADER and DXC for native half-rounding tests") + + with TemporaryDirectory() as directory: + trial = Path(directory) + native, hlsl, ir = (trial / name for name in ("shader.dxbc", "shader.hlsl", "shader.ll")) + for instructions, expected in cases: + words = [instructions] if isinstance(instructions, int) else instructions + with self.subTest(words=[hex(word) for word in words]): + code = [0x7e0802ff, 0xa5a5abcd, *words, 0xbf810000] + native.write_bytes(container(code)) + subprocess.run([xshader, native, "--hlsl-out", hlsl], check=True, + capture_output=True, timeout=30) + # Expose only the final register; DXC folds the translated instructions. + body = hlsl.read_text().rstrip().removesuffix("}") + hlsl.write_text("RWByteAddressBuffer observed : register(u0);\n" + + body + "\nobserved.Store(gtid.x * 4u, v4);\n}\n") + result = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fc", ir, + "-Fo", trial / "shader.cso", hlsl], + text=True, capture_output=True, timeout=30) + self.assertEqual(result.returncode, 0, result.stderr) + stores = re.findall(r"call void @dx\.op\.bufferStore\.i32\([^\n]+?, i32 undef, i32 (-?\d+),", ir.read_text()) + self.assertEqual([int(v) & 0xffffffff for v in stores], [expected]) + + def test_inline_fraction_keeps_other_half(self): + # gfx1030 v_fract_f16 v4 with inline half constants -0.5, +0.5, -1, +1. + cases = [(0x7e08bef1, 0x3800), (0x7e08bef0, 0x3800), + (0x7e08bef3, 0), (0x7e08bef2, 0)] + # With round-down active, FRACT must use the already-rounded FP16 + # inline ROM entry for 1/(2*pi). + cases.append(([0xbfa40008, 0x7e08bef8], 0x3118)) + self.check_inline_results(cases) + + def test_round_to_integer_keeps_other_half_and_signed_zero(self): + # gfx1030 VOP1 with v4 as destination. Include both ties to even at zero. + self.check_inline_results([ + (0x7e08b6f1, 0xbc00), # floor(-0.5) = -1 + (0x7e08b8f0, 0x3c00), # ceil(+0.5) = 1 + (0x7e08baf1, 0x8000), # trunc(-0.5) = -0 + (0x7e08bcf1, 0x8000), # roundEven(-0.5) = -0 + (0x7e08bcf0, 0x0000), # roundEven(+0.5) = +0 + ]) + + def test_half_rounding_retains_nan_payload_and_obeys_mode(self): + ieee = [0xba800241, 1] # set MODE.IEEE + dx10 = [0xba800201, 1] # set MODE.DX10_CLAMP + cases = [] + for opcode in (0xb6, 0xb8, 0xba, 0xbc, 0xbe): + literal = [0x7e0800ff | (opcode << 8), 0xfc35] + cases.extend([(literal, 0xfc35), (ieee + literal, 0xfe35)]) + # v_floor_f16_e64 v4, literal clamp; v_fract_f16 v4, -infinity. + clamp = [0xd5db8004, 0xff, 0xfe35] + # A register source with -abs changes sign before quieting. mul:2 + # is enabled with MODE=0 and still preserves the NaN payload. + negabs_mul = [0x7e0202ff, 0x7c35, 0xd5dc0104, 0x28000101] + cases.extend([(clamp, 0xfe35), (dx10 + clamp, 0), + ([0xbfa50000] + negabs_mul, 0xfc35), + (ieee + negabs_mul, 0xfe35), + ([0x7e08beff, 0xfc00], 0xfe00)]) + self.check_inline_results(cases) + + def test_half_output_multiplier_obeys_mode(self): + # v_fract_f16 v4, 0.5 mul:2 and v_floor_f16 v4, 1.0 mul:2. + # MODE initially preserves FP16 output denormals. Setting IEEE also + # disables scaling, even after s_denorm_mode has disabled denormals. + fraction = [0xd5df0004, 0x080000f0] + floor = [0xd5db0004, 0x080000f2] + ieee = [0xbfa50000, 0xba800241, 1] + negative_zero = [0xd5de0004, 0x080000f1] # roundEven(-0.5) mul:2 + self.check_inline_results([ + ([0xbfa50000] + negative_zero, 0x0000), + (ieee + negative_zero, 0x8000), + (fraction, 0x3800), (floor, 0x3c00), + (ieee + fraction, 0x3800), (ieee + floor, 0x3c00), + # s_mov_b32 s8,1; s_setreg_b32 hwreg(MODE,9,1),s8 + ([0xbfa50000, 0xbe880381, 0xb9880241] + floor, 0x3c00), + # A full MODE write sets IEEE and clears output denormal enable. + ([0xba80f801, 0x200] + floor, 0x3c00), + ]) + + def test_integer_to_half_obeys_signedness_rounding_and_inline_bits(self): + self.check_inline_results([ + (0x7e08a2c1, 0xbc00), # signed -1 + (0x7e08a0c1, 0x7c00), # unsigned 65535, nearest-even + ([0xbfa4000c, 0x7e08a0c1], 0x7bff), # same integer, toward zero + ([0xd5d00004, 0xf0], 0x7300), # inline 0.5 supplies bits 0x3800 + ]) + + def test_half_to_integer_preserves_high_half(self): + self.check_inline_results([ + (0x7e08a6f5, 0xfffe), # signed -2 + (0x7e08a4f5, 0), # unsigned -2 saturates to zero + ([0x7e08a6ff, 0x7e11], 0), # positive NaN + ([0x7e08a4ff, 0xfe11], 0), # negative NaN + ]) + + def test_half_to_integer_sdwa_selects_source_and_destination(self): + # v1 contains a NaN in WORD_1 and +2 in WORD_0. The destination + # initially contains 0xa5a5abcd, so a misplaced write is observable. + seed = [0x7e0202ff, 0x7e114000] + self.check_register_results([ + (seed + [0x7e08a6f9, 0x51501], 0x0000abcd), # high word, preserve low + (seed + [0x7e08a4f9, 0x50401], 0x00000000), # low word, pad high + ]) + + def test_normalized_half_to_integer_rounds_once(self): + # 0x3801 is the next binary16 above 0.5. A binary32 product can + # round it onto a tie before the final integer rounding. + self.check_inline_results([ + ([0x7e08c6ff, 0x3801], 0x400f), + ([0x7e08c8ff, 0x3801], 0x801f), + (0x7e08c6f0, 0x4000), # exact tie at +0.5 + (0x7e08c6f3, 0x8001), # SNORM(-1) = -32767 + ([0x7e08c6ff, 0xfe11], 0), # negative NaN + ([0x7e08c8ff, 0x03ff], 4), # largest half subnormal + ([0xbfa50000, 0x7e08c8ff, 0x03ff], 0), # flush input subnormals + ]) + + def test_sdwa_dword_zero_extends_the_result(self): + # v1.h is NaN. Converting it writes a full zero word even though + # the instruction encodes DST_UNUSED=PRESERVE. + seed = [0x7e0202ff, 0x7e114000] + self.check_register_results([ + (seed + [0x7e08c6f9, 0x51601], 0), # normalized signed + (seed + [0x7e08a4f9, 0x51601], 0), # ordinary unsigned + ]) diff --git a/tests/test_rpi_rounding.py b/tests/test_rpi_rounding.py new file mode 100644 index 00000000..f152bc94 --- /dev/null +++ b/tests/test_rpi_rounding.py @@ -0,0 +1,52 @@ +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess +from tempfile import TemporaryDirectory +import unittest + +from tools.reference.scarlett_worker_fixture import container, pack + + +def native_shader(code): + shader = container(code, resources=[(7, 0, 0, 0)]) + # Extend the fixture's two-chunk directory with a root table for UAV u0. + root = b"RTS0" + pack([64, 1, 1, 24, 0, 0, 0, 0, 0, 36, 1, 44, 1, 1, 0, 0, 0]) + first, second = struct.unpack_from(" 0x7f800000u; } +uint tb_cvt_u32_f32(float x) { + if (!(x > 0.0) || tb_nan_bits(asuint(x))) return 0u; + if (x >= 4294967296.0) return 0xffffffffu; + return uint(x); +} +uint tb_cvt_i32_f32(float x) { + if (tb_nan_bits(asuint(x))) return 0u; + if (x >= 2147483648.0) return 0x7fffffffu; + if (x <= -2147483648.0) return 0x80000000u; + return asuint(int(x)); +} diff --git a/tools/shader-compiler/src/fract_f32.hlsl b/tools/shader-compiler/src/fract_f32.hlsl new file mode 100644 index 00000000..59769a73 --- /dev/null +++ b/tools/shader-compiler/src/fract_f32.hlsl @@ -0,0 +1,14 @@ +float tb_fract_f32(float x, uint mode) { + uint bits = asuint(x); + uint magnitude = bits & 0x7fffffffu; + if (magnitude < 0x00800000u) { + if (magnitude == 0u || (mode & 0x10u) == 0u) return 0.0; + if (bits == magnitude) return (mode & 0x20u) != 0u ? x : 0.0; + } + // For -2^-25 <= x < 0, rounding x - floor(x) to nearest can give 1.0. + // RDNA returns the largest binary32 below 1, before any output modifier. + if (bits > 0x80000000u && bits <= 0xb3000000u) return asfloat(0x3f7fffffu); + // DXC can fold frac(x) to the fractional magnitude for a negative constant. + precise float result = x - floor(x); + return result; +} diff --git a/tools/shader-compiler/src/half_unary.hlsl b/tools/shader-compiler/src/half_unary.hlsl new file mode 100644 index 00000000..3320bb71 --- /dev/null +++ b/tools/shader-compiler/src/half_unary.hlsl @@ -0,0 +1,23 @@ + +uint tb_finite_unary_f16(float x, uint mode, uint op) { + // op is a compile-time constant for each guest instruction. + if (op == 0u) return tb_f16_rne(floor(x)); + if (op == 1u) return tb_f16_rne(ceil(x)); + if (op == 2u) return tb_f16_rne(trunc(x)); + if (op == 3u) return tb_f16_rne(round(x)); + precise float fraction = x - floor(x); + uint halfBits = tb_mode_half(fraction, mode); + // FRACT bounds its result below 1 before the output multiplier. + return halfBits == 0x3c00u ? 0x3bffu : halfBits; +} + +uint tb_unary_f16(uint bits, uint mode, uint op) { + bits &= 0xffffu; + uint magnitude = bits & 0x7fffu; + // The host's float conversion can canonicalize NaNs. RDNA2 retains the + // sign and payload, and quiets a signaling NaN only when IEEE mode is set. + if (magnitude > 0x7c00u) return bits | (mode & 0x200u); + if (magnitude == 0x7c00u) return op == 4u ? 0xfe00u : bits; + if (magnitude < 0x400u && (mode & 0x40u) == 0u) bits &= 0x8000u; + return tb_finite_unary_f16(f16tof32(bits), mode, op); +} diff --git a/tools/shader-compiler/src/hlsl.rs b/tools/shader-compiler/src/hlsl.rs index 425827d6..a09dc8a5 100644 --- a/tools/shader-compiler/src/hlsl.rs +++ b/tools/shader-compiler/src/hlsl.rs @@ -26,6 +26,7 @@ mod compare; mod uniform_texel; mod pixel_quad; mod mubuf_offsets; +mod scalar_values; mod code_offset; mod scalar_bits; #[cfg(test)] @@ -45,6 +46,7 @@ mod micropoly; mod mesh; mod mesh_exports; mod exec_group; +mod exec_snapshot; mod hair_cluster; mod hair_cluster_export; mod instance_cull; @@ -232,6 +234,25 @@ float3 tb_cube_dir(float s, float t, float face) { float u = (s - 1.5) * 2.0, v float tb_mull(float a, float b) { return (a == 0.0 || b == 0.0) ? 0.0 : a * b; } uint tb_f16_cvt(float x, bool rtz) { uint u = asuint(x); uint s = (u >> 16) & 0x8000u; uint a = u & 0x7fffffffu; if (a > 0x7f800000u) return s | 0x7e00u | ((a >> 13) & 0x3ffu); if (a == 0x7f800000u) return s | 0x7c00u; if (rtz) { if (a >= 0x477fe000u) return s | 0x7bffu; } else { if (a >= 0x477ff000u) return s | 0x7c00u; } if (a >= 0x38800000u) { uint r = (a >> 13) - 0x1c000u; uint rem = a & 0x1fffu; if (!rtz && (rem > 0x1000u || (rem == 0x1000u && (r & 1u) != 0u))) r += 1u; return s | r; } if (a < 0x33000000u) return s; uint e = a >> 23; uint mant = (a & 0x7fffffu) | 0x800000u; uint sh = 126u - e; uint q = mant >> sh; uint rem = mant & ((1u << sh) - 1u); uint half = 1u << (sh - 1u); if (!rtz && (rem > half || (rem == half && (q & 1u) != 0u))) q += 1u; return s | q; } "#; +fn clamped_product24(ins: &Insn) -> bool { + matches!(ins.mnemonic.as_str(), "v_mul_u32_u24" | "v_mul_i32_i24" | "v_mad_u32_u24" | "v_mad_i32_i24") + && (ins.aux.imm != 0 || ins.aux.sdwa.is_some_and(|ext| ext & (1 << 13) != 0)) +} + +const MAD24_SAT: &str = r#" +uint tb_mad24_sat(uint a, uint b, uint acc, bool isSigned) { + a = isSigned ? asuint(asint(a << 8) >> 8) : (a & 0xffffffu); + b = isSigned ? asuint(asint(b << 8) >> 8) : (b & 0xffffffu); + uint product = a * b; + uint low = product + acc; + uint carry = uint(low < product); + if (!isSigned) return tb_mulhi_u32(a, b) + carry == 0u ? low : 0xffffffffu; + // Add the sign-extended accumulator before testing the full sum for overflow. + int high = asint(tb_mulhi_i32(a, b)) + (asint(acc) >> 31) + int(carry); + if (high == (asint(low) >> 31)) return low; + return high < 0 ? 0x80000000u : 0x7fffffffu; +} +"#; const HALF_RNE: &str = "uint tb_f16_rne(float x) { return tb_f16_cvt(x, false); }\n"; // The branch-free implementation keeps the driver control-flow graph small // when a filter applies the conversion hundreds of times per invocation. @@ -335,6 +356,19 @@ fn name(o: &Opnd) -> Result { }) } +// Return the bits of this encoded field that can be read back or updated, +// relative to its starting offset. MODE has a gap before FP16_OVFL (bit 23). +fn modeled_hwreg_mask(word: u32) -> u32 { + let known = match word & 63 { + 1 => 0x0080_03ff, + 20 | 21 => u32::MAX, // FLAT_SCRATCH_LO/HI + _ => 0, + }; + let shift = (word >> 6) & 31; + let encoded_width = (word >> 11) & 31; + (known >> shift) & (u32::MAX >> (31 - encoded_width)) +} + /// Operand as a `uint` rvalue expression. fn r(o: &Opnd) -> Result { Ok(match o { @@ -350,6 +384,56 @@ fn f(o: &Opnd) -> Result { Ok(format!("asfloat({})", r(o)?)) } +// Selector for tb_unary_f16, constant at each translated instruction. +fn half_unary_op(mnemonic: &str) -> Option { + match mnemonic { + "v_floor_f16" => Some(0), + "v_ceil_f16" => Some(1), + "v_trunc_f16" => Some(2), + "v_rndne_f16" => Some(3), + "v_fract_f16" => Some(4), + _ => None, + } +} + +fn integer_to_half(mnemonic: &str) -> bool { + matches!(mnemonic, "v_cvt_f16_u16" | "v_cvt_f16_i16") +} + +fn normalized_half_to_integer(mnemonic: &str) -> bool { + matches!(mnemonic, "v_cvt_norm_u16_f16" | "v_cvt_norm_i16_f16") +} + +fn half_round_or_conversion(m: &str) -> bool { + half_unary_op(m).is_some() || integer_to_half(m) || half_to_integer(m) +} + +// Selector 248 is the only inline float whose binary16 value differs from its binary32 value. +fn inline_half_value(value: f32) -> f32 { + if value.to_bits() == 0x3e22_f983 { f32::from_bits(0x3e23_0000) } else { value } +} + +fn half_operand_bits(o: &Opnd) -> Result { + match o { + Opnd::ConstF32(_) => Ok(format!("tb_f16_rne({})", f(o)?)), + _ => r(o), + } +} + +fn half_to_integer(mnemonic: &str) -> bool { + matches!(mnemonic, "v_cvt_u16_f16" | "v_cvt_i16_f16") || normalized_half_to_integer(mnemonic) +} + +fn mul24_expr(op: &str, a: &str, b: &str) -> Option { + Some(match op { + "v_mul_u32_u24" => format!("(({a} & 0xffffffu) * ({b} & 0xffffffu))"), + "v_mul_i32_i24" => format!("asuint((asint({a} << 8) >> 8) * (asint({b} << 8) >> 8))"), + "v_mul_hi_u32_u24" => format!("tb_mulhi_u32({a} & 0xffffffu, {b} & 0xffffffu)"), + "v_mul_hi_i32_i24" => format!("tb_mulhi_i32(asuint(asint({a} << 8) >> 8), asuint(asint({b} << 8) >> 8))"), + _ => return None, + }) +} + /// Low `width` bits set, saturated to one word. Keep full-width shifts out of the generated code. fn low_mask(width: &str) -> String { format!("(({width}) >= 32u ? 0xffffffffu : ((1u << (({width}) & 31u)) - 1u))") @@ -574,6 +658,7 @@ struct Emitter<'a> { compute_swizzle: bool, vote_defs: BTreeSet, vote_uses: BTreeMap, + exec_snapshots: exec_snapshot::Snapshots, reflected_lds_words: Option, hoisted_swizzle: Option, indexed_lane: bool, @@ -687,20 +772,95 @@ impl HeapView { const SPACE_ALIAS: u32 = 1 << 16; /// Synthetic opcode of the wave-reduction instruction produced by `lower_wave_reductions`. const OP_WAVE_REDUCE: u32 = 0x7ff0; -const OP_QUAD_BINARY: u32 = 0x7ff5; +const OP_DPP_BINARY: u32 = 0x7ff5; +const OP_LOCAL_EXTREMA: u32 = 0x7fe3; const OP_QUAD_MOVE: u32 = 0x7fe1; -const OP_ROW_MIRROR: u32 = 0x7fe2; +const OP_ROW_XOR_MOVE: u32 = 0x7fe2; +const OP_ROW_SHARE_MOVE: u32 = 0x7fe3; +const OP_ROW_ROR_MOVE: u32 = 0x7fe4; +const OP_ROW_SHIFT_MOVE: u32 = 0x7fe5; + +fn is_row_move(i: &Insn) -> bool { + i.enc == Enc::Vop1 && matches!(i.op, OP_ROW_XOR_MOVE | OP_ROW_SHARE_MOVE | OP_ROW_ROR_MOVE | OP_ROW_SHIFT_MOVE) +} fn is_quad_exchange(i: &Insn) -> bool { - (i.enc == Enc::Vop2 && i.op == OP_QUAD_BINARY) - || (i.enc == Enc::Vop1 && (i.op == OP_QUAD_MOVE || i.op == OP_ROW_MIRROR)) + (i.enc == Enc::Vop2 && i.op == OP_DPP_BINARY) + || (i.enc == Enc::Vop1 && i.op == OP_QUAD_MOVE) + || is_row_move(i) } -fn is_bitwise_quad_exchange(i: &Insn) -> bool { - i.enc == Enc::Vop2 && matches!(i.mnemonic.as_str(), "v_or_b32" | "v_and_b32" | "v_xor_b32") - && i.src.first() == Some(&Opnd::Raw(250)) - // Full destination masks, no source modifiers, selector within a quad. - && i.raw.get(1).is_some_and(|ctrl| ctrl & 0xfff3_0000 == 0xff00_0000) +fn lower_dpp_binary(ins: &mut Insn) { + let control = ins.raw[1]; + let selector = if group_extrema::is_dpp8(ins) { control >> 8 } else { (control >> 8) & 0x1ff }; + ins.op = OP_DPP_BINARY; + ins.aux.imm = i64::from(selector); + ins.src[0] = Opnd::Vgpr(control as u8); +} + +fn dpp_fp32_sources(ins: &Insn, first: String) -> Result<(String, String), String> { + // DPP8 encodes lane selectors in the same bits, and ordinary VOP2 + // instructions can have a literal extension instead of a DPP control. + let flags = if ins.raw.first().is_some_and(|word| word & 0x1ff == 250) { + *ins.raw.get(1).ok_or("missing DPP16 controls")? >> 20 + } else { + 0 + }; + let modified = |bits, flags: u32| { + compare::sign_modifiers(bits, 0x8000_0000, flags & 2 != 0, flags & 1 != 0) + }; + Ok((modified(first, flags), modified(r(&ins.src[1])?, flags >> 2))) +} + +fn is_binary_quad_perm(i: &Insn) -> bool { + if i.enc != Enc::Vop2 || i.src.first() != Some(&Opnd::Raw(250)) { + return false; + } + let Some(control) = i.raw.get(1) else { return false }; + // A quad selector uses eight bits. Row and bank masks govern the write. + if control & 0x0003_0000 != 0 { + return false; + } + match i.mnemonic.as_str() { + "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32" + | "v_cvt_pkrtz_f16_f32" | "v_min_f32" | "v_max_f32" => true, + "v_or_b32" | "v_and_b32" | "v_xor_b32" | "v_xnor_b32" + | "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" + | "v_add_nc_u32" | "v_sub_nc_u32" | "v_subrev_nc_u32" + | "v_min_i32" | "v_max_i32" | "v_min_u32" | "v_max_u32" + | "v_mul_i32_i24" | "v_mul_hi_i32_i24" | "v_mul_u32_u24" | "v_mul_hi_u32_u24" + | "v_cndmask_b32" => control & 0x00f0_0000 == 0, // No FP source modifiers. + _ => false, + } +} + +// VOP2 CNDMASK reads the destination lane's VCC. A vector compare writes a +// per-invocation predicate here, while a scalar write can hold a packed mask. +fn quad_cndmasks_with_lane_vcc(insns: &[Insn]) -> BTreeSet { + let targets = branch_targets(insns); + let mut selects = BTreeSet::new(); + let mut lane_vcc = false; + for (index, ins) in insns.iter().enumerate() { + if targets.contains(&(ins.offset as i64)) { lane_vcc = false; } + if lane_vcc && ins.mnemonic == "v_cndmask_b32" && is_binary_quad_perm(ins) { + selects.insert(index); + } + if ins.mnemonic.starts_with("v_cmpx_") { continue; } // RDNA2 CMPX writes EXEC. + if ins.dst.first() == Some(&Opnd::VccLo) { + lane_vcc = ins.mnemonic.starts_with("v_cmp_") + || (ins.mnemonic == "s_mov_b64" && matches!(ins.src[..], [Opnd::ConstInt(0 | -1)])); + } else { + lane_vcc &= match ins.enc { + Enc::Vop1 | Enc::Vop2 => matches!(ins.dst[..], [Opnd::Vgpr(_)]) + && !ins.mnemonic.contains("_co_"), + Enc::Sop1 => matches!(ins.mnemonic.as_str(), "s_mov_b32" | "s_mov_b64" | "s_wqm_b32" | "s_wqm_b64") + && !ins.dst.contains(&Opnd::VccHi), + Enc::Sopp => matches!(ins.mnemonic.as_str(), "s_nop" | "s_waitcnt"), + _ => false, + }; + } + } + selects } /// Whole-wave reductions (HLSL `WaveActiveMin` / `WaveActiveMax`; observed in @@ -728,51 +888,58 @@ fn is_bitwise_quad_exchange(i: &Insn) -> bool { fn lower_wave_reductions(insns: &mut [Insn]) -> Result, String> { for op in insns.iter_mut().filter(|op| op.enc == Enc::Vop1 && op.mnemonic == "v_mov_b32" && op.src == [Opnd::Raw(250)]) { let ctrl = *op.raw.get(1).ok_or("missing DPP16 move controls")?; - // DPP16 control word: [src0_reg:8][ctrl:9][neg0:1][abs0:1][bc:1][fi:1][bank_m:4][row_m:4] - // (see Leonida rdna2_decode.py). Accept the exact shape the GPU emits for the two - // moves we lower: quad_perm with FI=1 and row_mirror with FI=0. let src0_reg = ctrl & 0xff; - let ctrl_field = (ctrl >> 8) & 0x1ff; - let fi = (ctrl >> 18) & 1; - let bc = (ctrl >> 19) & 1; + let ctrl_field = i64::from((ctrl >> 8) & 0x1ff); let neg0 = (ctrl >> 20) & 1; let abs0 = (ctrl >> 21) & 1; - let bank_m = (ctrl >> 24) & 0xf; - let row_m = (ctrl >> 28) & 0xf; - if ctrl_field <= 0xff && fi == 1 && bc == 1 && neg0 == 0 && abs0 == 0 && bank_m == 0xf && row_m == 0xf { - op.op = OP_QUAD_MOVE; - op.src[0] = Opnd::Vgpr(src0_reg as u8); - op.aux.imm = ((ctrl >> 8) & 255) as i64; - continue; - } - if ctrl_field == 0x140 && fi == 0 && bc == 1 && neg0 == 0 && abs0 == 0 && bank_m == 0xf && row_m == 0xf { - op.op = OP_ROW_MIRROR; - op.src[0] = Opnd::Vgpr(src0_reg as u8); - op.aux.imm = 0; - continue; - } - return Err(format!("unsupported DPP16 move at {:#x}", op.offset)); + let unsupported = || format!("unsupported DPP16 move at {:#x}", op.offset); + if neg0 != 0 || abs0 != 0 { + return Err(unsupported()); + } + let (opcode, selector) = match ctrl_field { + 0..=0xff => (OP_QUAD_MOVE, ctrl_field), + 0x101..=0x10f => (OP_ROW_SHIFT_MOVE, ctrl_field - 0x100), // row_shl + 0x111..=0x11f => (OP_ROW_SHIFT_MOVE, 0x110 - ctrl_field), // row_shr + 0x121..=0x12f => (OP_ROW_ROR_MOVE, ctrl_field - 0x120), + 0x140 => (OP_ROW_XOR_MOVE, 15), // row_mirror + 0x141 => (OP_ROW_XOR_MOVE, 7), // row_half_mirror + 0x150..=0x15f => (OP_ROW_SHARE_MOVE, ctrl_field - 0x150), // row_share + 0x160..=0x16f => (OP_ROW_XOR_MOVE, ctrl_field - 0x160), // row_xmask + _ => return Err(unsupported()), + }; + op.op = opcode; + op.src[0] = Opnd::Vgpr(src0_reg as u8); + op.aux.imm = selector; } let mut width = None; + let mut proven_cndmasks = None; let is_dpp = |i: &Insn| i.enc == Enc::Vop2 && matches!(i.src.first(), Some(Opnd::Raw(233 | 234 | 250))); let mut at = 0; while let Some(first) = (at..insns.len()).find(|&i| is_dpp(&insns[i])) { let off = insns[first].offset; let bad = |what: &str| format!("wave reduction at {off:#x}: {what}"); let red = insns[first].mnemonic.clone(); - let bitwise_quad = is_bitwise_quad_exchange(&insns[first]); - if bitwise_quad || (red == "v_add_f32" && insns[first].src.first() == Some(&Opnd::Raw(250))) { - let ctrl = *insns[first].raw.get(1).ok_or_else(|| bad("missing DPP16 control word"))?; - // Keep the existing FP32 add subset at FI=1 and BC=1. - if !bitwise_quad && ctrl & 0xffff0000 != 0xff0c0000 { - return Err(bad("unsupported DPP16 FP32 add controls")); - } - insns[first].op = OP_QUAD_BINARY; - insns[first].src[0] = Opnd::Vgpr(ctrl as u8); - insns[first].aux.imm = ((ctrl >> 8) & 255) as i64; + // A full saved-EXEC extrema reduction can begin with quad shuffles, + // then combine different quads. A quad followed solely by a lane read + // still selects within its quad and must not become a whole-wave min/max. + let starts_wave_extrema = matches!(red.as_str(), "v_min_f32" | "v_max_f32") + && first >= 3 && (insns[first - 3].enc, insns[first - 3].op) == (Enc::Sop1, 0x29) + && insns[first - 2].mnemonic == "v_mov_b32" && insns[first - 1].mnemonic == "v_cndmask_b32" + && insns[first + 1..].iter() + .take_while(|i| is_dpp(i) && i.mnemonic == red && i.dst == insns[first].dst) + .any(|i| !is_binary_quad_perm(i)); + if is_binary_quad_perm(&insns[first]) && !starts_wave_extrema { + if red == "v_cndmask_b32" && !proven_cndmasks + .get_or_insert_with(|| quad_cndmasks_with_lane_vcc(insns)).contains(&first) { + return Err(bad("quad CNDMASK requires a known per-lane VCC predicate")); + } + lower_dpp_binary(&mut insns[first]); at = first + 1; continue; } + if red == "v_add_f32" && insns[first].src.first() == Some(&Opnd::Raw(250)) { + return Err(bad("unsupported DPP16 FP32 add controls")); + } let saved_extrema = matches!(red.as_str(), "v_min_f32" | "v_max_f32") && (first.checked_sub(3).is_some_and(|p| matches!(insns[p].mnemonic.as_str(), "s_or_saveexec_b32" | "s_or_saveexec_b64")) || wave_sum::masked_floating(insns, first)); @@ -1103,7 +1270,7 @@ fn lower_local_pc_transfers(insns: &mut [Insn]) -> Result<(), String> { // range, restore EXEC, broadcast the atomic result and add a per-lane prefix. // The two register allocations differ. Match the complete regions before changing // a saved EXEC mask from its usual per-invocation predicate into wave-uniform data. -fn mark_wave_allocations(insns: &mut [Insn], wave32_mask: bool) -> Result { +fn mark_wave_allocations(insns: &mut [Insn], wave32_mask: bool, election: Option) -> Result { const REGIONS: [&[u32]; 2] = [ &[ 0xd7650007, 0x000100c1, 0xbe8e147e, 0xbe8c047e, 0xd7660007, 0x00020ec1, @@ -1119,13 +1286,14 @@ fn mark_wave_allocations(insns: &mut [Insn], wave32_mask: bool) -> Result { trial[i].mnemonic = "tb_first_active_lane".into(); insns.clone_from_slice(&trial); @@ -1139,7 +1307,10 @@ fn mark_wave_allocations(insns: &mut [Insn], wave32_mask: bool) -> Result Result Option { + if ex.stage != Stage::Compute || ex.fspx_config.is_some() { return None; } + let threads = compute_group(ex).into_iter().fold(1u32, u32::saturating_mul); + if threads == 0 || threads > 1024 { return None; } + let first = insns.iter().find(|i| matches!(i.mnemonic.as_str(), "s_ff1_i32_b32" | "s_ff1_i32_b64")); + // A small group fits one wave of either guest width, even without FF1. + if first.is_none() && (threads > 32 || !insns.iter().any(exec_snapshot::captures_exec)) { return None; } + let (end, body) = insns.split_last()?; + if end.mnemonic != "s_endpgm" || !body.iter().all(|i| match i.mnemonic.as_str() { + "s_ff1_i32_b32" | "s_ff1_i32_b64" => first.is_some_and(|f| f.mnemonic == i.mnemonic) && i.src == [Opnd::ExecLo], + "s_load_dwordx4" | "s_waitcnt" | "s_nop" | "s_mov_b32" | "s_mov_b64" + | "s_and_saveexec_b32" | "s_and_saveexec_b64" | "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" + | "v_mov_b32" | "v_and_b32" | "v_lshlrev_b32" | "v_lshrrev_b32" + | "v_add_nc_u32" | "v_cndmask_b32" | "buffer_store_dword" => true, + m => m.starts_with("v_cmp_") || m.starts_with("v_cmpx_"), + }) { return None; } + Some(if threads <= 32 || first.is_some_and(|f| f.mnemonic == "s_ff1_i32_b32") { + ElectionLowering::Native32 + } else { + ElectionLowering::Shared64 + }) +} + +/// In a straight-line compute shader, a compare/save/FF1/restore sequence +/// produces a uniform scalar value. Recognize every mask access before allowing +/// uses other than the usual comparison against the lane index. +fn predicate_snapshots(mut code: &[Insn]) -> bool { + let mask = |o: &Opnd| matches!(o, Opnd::ExecLo | Opnd::ExecHi | Opnd::VccLo | Opnd::VccHi); + // Numeric vector operands can read the ballot captured at SAVEEXEC. Other + // consumers still require proof about the representation they expect. + let mut saved_words = BTreeMap::new(); + let count = code.len(); + while let [op, rest @ ..] = code { + if exec_snapshot::copy_scalar_words(op, &mut saved_words) { + code = rest; + continue; + } + let numeric = exec_snapshot::numeric_sources(op) != 0; + if let ("v_cndmask_b32", Some(Opnd::Sgpr(lo))) = (op.mnemonic.as_str(), op.src.get(2)) { + let pair = [saved_words.get(lo), saved_words.get(&(lo + 1))]; + if pair.iter().any(|w| matches!(w, Some(exec_snapshot::Word::Saved(..)))) + && (op.enc != Enc::Vop3 || op.aux.sdwa.is_some() || pair.contains(&None)) + { + return false; + } + } + if !numeric && saved_words.iter().any(|(®, word)| matches!(word, exec_snapshot::Word::Saved(..)) + && (reads_sgpr(op, reg) || op.mnemonic.ends_with("64") && op.src.iter().any(|o| may_touch_sgpr(o, reg)))) + { + return false; + } + let i = count - code.len(); + if op.mnemonic.starts_with("v_cmp_") && op.dst == [Opnd::VccLo] { + let [save, search, restore, tail @ ..] = rest else { return false }; + let [Opnd::Sgpr(saved)] = save.dst.as_slice() else { return false }; + let [Opnd::Sgpr(result)] = search.dst.as_slice() else { return false }; + if op.src.iter().any(mask) || save.mnemonic != "s_and_saveexec_b64" || save.src != [Opnd::VccLo] + || search.mnemonic != "s_ff1_i32_b64" || search.src != [Opnd::ExecLo] + || result == saved || u16::from(*result) == u16::from(*saved) + 1 + || restore.mnemonic != "s_mov_b64" || restore.dst != [Opnd::ExecLo] + || restore.src != [Opnd::Sgpr(*saved)] + { + return false; + } + exec_snapshot::record_scalar_write(save, i + 1, &mut saved_words); + exec_snapshot::record_scalar_write(search, i + 2, &mut saved_words); + code = tail; + } else { + if op.src.iter().chain(&op.dst).any(mask) || op.mnemonic.starts_with("v_cmpx_") { + return false; + } + exec_snapshot::record_scalar_write(op, i, &mut saved_words); + code = rest; + } + } + true +} + /// True when `o` may name SGPR `n` as part of a 32- or 64-bit operand. fn may_touch_sgpr(o: &Opnd, n: u8) -> bool { matches!(*o, Opnd::Sgpr(k) if u16::from(k) + 1 >= u16::from(n) && u16::from(k) <= u16::from(n) + 1) @@ -1202,7 +1460,7 @@ fn vgpr_def(insns: &[Insn], targets: &BTreeSet, at: usize, v: u8) -> Option /// `s_ff1_i32_b64 s, exec` (or `_b32`) compared with the full-mask `v_mbcnt` lane index. The /// elected lane usually adds the number of active lanes to a counter; that count /// reads an EXEC copy as a wave mask, so capture the copy as a ballot. -fn verify_lane_election(insns: &mut [Insn], ff1: usize) -> Result<(), String> { +fn verify_lane_election(insns: &mut [Insn], ff1: usize, straight_compute: bool) -> Result<(), String> { let at = insns[ff1].offset; let bad = |what: &str| format!("unverified EXEC election at {at:#x}: {what}"); let Some(&Opnd::Sgpr(lane)) = insns[ff1].dst.first() else { return Err(bad("no scalar destination")) }; @@ -1213,7 +1471,13 @@ fn verify_lane_election(insns: &mut [Insn], ff1: usize) -> Result<(), String> { ins.src.iter().take(if two { 2 } else { usize::MAX }).cloned().collect::>() }; let cmp = (ff1 + 1..insns.len()) - .find(|&j| sources(&insns[j]).iter().chain(&insns[j].dst).any(|o| may_touch_sgpr(o, lane))) + .find(|&j| { + let ins = &insns[j]; + if straight_compute && ins.mnemonic == "s_mov_b32" { + return ins.src.iter().chain(&ins.dst).any(|o| *o == Opnd::Sgpr(lane)); + } + sources(ins).iter().chain(&ins.dst).any(|o| may_touch_sgpr(o, lane)) + }) .ok_or_else(|| bad("unused lane"))?; if (ff1 + 1..=cmp).any(|j| targets.contains(&(insns[j].offset as i64))) { return Err(bad("branch enters the election")); @@ -1254,6 +1518,13 @@ fn verify_lane_election(insns: &mut [Insn], ff1: usize) -> Result<(), String> { (cmp, restore) } else { let Some(save) = (cmp + 1..insns.len()).find(|&j| insns[j].mnemonic == format!("s_and_saveexec_{bits}")) else { return Ok(()) }; + // A different comparison replaced VCC before SAVEEXEC. In straight-line + // code that save starts an independent masked region. + if straight_compute && c.dst == [Opnd::VccLo] && insns[save].src == [Opnd::VccLo] + && insns[cmp + 1..save].iter().any(|i| i.mnemonic.starts_with("v_cmp_") && i.dst == [Opnd::VccLo]) + { + return Ok(()); + } let Some(&Opnd::Sgpr(saved)) = insns[save].dst.first() else { return Ok(()) }; let restore = (save + 1..insns.len()) .find(|&j| insns[j].mnemonic == format!("s_mov_{bits}") && insns[j].dst.first() == Some(&Opnd::ExecLo) @@ -1364,7 +1635,7 @@ fn translate_outputs(ex: &ShaderExtract, feeds_ps: Option<&InputInterp>, output_ // Once this exact exchange subset is recognized, a later binding or // emitter error must not silently replace its collectives with copies. let mut original = disassemble(&ex.isa); - if original.iter().any(is_bitwise_quad_exchange) { + if original.iter().any(is_binary_quad_perm) || group_extrema::prepare_exchanges(ex, &mut original).unwrap_or(true) { // This standalone exchange observes its source lane even if the exact // translation failed elsewhere. A per-lane retry would drop that operand. return first; @@ -1456,9 +1727,12 @@ fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Option<&InputInterp>, ou let fspx_wave = fspx_wave::width(ex, &insns); let wave_cull = fspx_wave.is_some() || hair_multisample || wave_cull::recognize(ex); let page_waves = page_waves::recognize(ex); - let allocation_wave64 = !lone_lane::on() && !wave_cull && !page_waves && mark_wave_allocations(&mut insns, resolve_wave32)?; + let generic_waves = !lone_lane::on() && !wave_cull && !page_waves; + let election = if generic_waves && !resolve_wave32 { straight_election(ex, &insns) } else { None }; + let allocation_wave64 = generic_waves && mark_wave_allocations(&mut insns, resolve_wave32, election)?; if ex.stage == Stage::Pixel { wave_alloc::prepare(&mut insns); } let reflection = reflection_compact::prepare(ex, &mut insns); + group_extrema::prepare_exchanges(ex, &mut insns)?; let group_extrema = group_extrema::prepare(ex, &mut insns); let straight_exchange = ex.stage == Stage::Compute && !lone_lane::on() && !wave_cull && !page_waves && !resolve_wave32 && !allocation_wave64 @@ -1481,8 +1755,10 @@ fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Option<&InputInterp>, ou let uses_quad_add = insns.iter().any(is_quad_exchange); let scan = if wave_cull { None } else { wave_scan::prepare(ex, &mut insns)? }; let scan_width = scan.as_ref().map(|s| s.width); - let indexed_lane = !resolve_wave32 && (group_extrema || ex.stage == Stage::Compute && (indexed_lane::constant_reads(compute_group(ex), &mut insns) - || indexed_lane::prepare(compute_group(ex), &mut insns))); + let ordinary_wave = !wave_cull && !page_waves && !lone_lane::on(); + let indexed_lane = !resolve_wave32 && (election == Some(ElectionLowering::Shared64) || group_extrema || ex.stage == Stage::Compute + && (indexed_lane::constant_reads(compute_group(ex), &mut insns, ordinary_wave) + || indexed_lane::prepare(compute_group(ex), &mut insns))); // A uniform Sgpr lane operand is only expressible through the whole-wave // group read, which needs shared-memory exchange like a swizzle does. let has_dynamic_lane_read = insns.iter().any(|i| i.enc == Enc::Vop3 @@ -1503,6 +1779,12 @@ fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Option<&InputInterp>, ou lower_lane_spills(&mut insns, resolve_wave32, group_reads)?; } } let mut em = Emitter::new(ex, insns); + if let Some(mode) = election { + if compute_group(ex).into_iter().product::() <= 32 || em.insns.iter().any(|i| matches!(i.mnemonic.as_str(), "tb_first_exec_lane" | "s_ff1_i32_b64") && i.src == [Opnd::ExecLo]) { + em.exec_snapshots = exec_snapshot::analyze(&em.insns, mode); + } + } + let shared_mask = em.exec_snapshots.sites.values().any(|site| matches!(site, exec_snapshot::Site::Capture(ElectionLowering::Shared64))); em.page_waves = page_waves; em.wave_cull = wave_cull; em.fspx_wave = fspx_wave; @@ -1580,7 +1862,26 @@ fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Option<&InputInterp>, ou && 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")); 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)).or((uses_quad_add && !(em.pixel_wave && em.insns.iter().all(|i| i.op != OP_ROW_MIRROR || i.enc != Enc::Vop1)) || uses_bpermute || group_extrema).then_some(32)); + 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 + // a second wave. The fallback host width cannot resolve an asymmetric guest mask. + if uses_quad_add && required_wave_size.is_none() && !em.one_word_vector_mask() + && compute_group(ex).into_iter().fold(1u32, u32::saturating_mul) > 32 + && em.insns.iter().filter(|i| is_quad_exchange(i) && i.enc == Enc::Vop1).any(|i| { + let rows = i.raw[1] >> 28; + i.raw[1] & 0x0f00_0000 != 0 && rows & 3 != rows >> 2 + }) + { + 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)); + // 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); + let required_wave_size = required_wave_size.or_else(|| { + (election == Some(ElectionLowering::Native32) && (!em.exec_snapshots.sites.is_empty() || em.insns.iter().any(|i| + i.mnemonic == "tb_first_active_lane" || i.mnemonic == "s_ff1_i32_b64"))).then_some(32) + }); em.required_wave_size = required_wave_size; // DS bit-mask mode operates on the low five lane bits in wave32 and wave64. // Map guest lanes by workgroup index, independently of the Vulkan subgroup layout. @@ -1622,7 +1923,7 @@ fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Option<&InputInterp>, ou Err(reason) => return Err(reason), } let [x, y, z] = compute_group(ex); - if ex.stage != Stage::Compute || !x.checked_mul(y).and_then(|n| n.checked_mul(z)).is_some_and(|n| n % width == 0) { + if ex.stage != Stage::Compute || !x.checked_mul(y).and_then(|n| n.checked_mul(z)).is_some_and(|n| n % width == 0 || partial_election && n > 0 && n < width) { return Err(format!("wave operation requires complete {width}-lane compute waves")); } } @@ -1748,6 +2049,9 @@ fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Option<&InputInterp>, ou } if light_grid { hlsl.insert_str(0, light_grid::DECLARATIONS); } if em.portable_wave64 { hlsl.insert_str(0, wave_sum::PORTABLE_DECLARATIONS); } + if shared_mask { + hlsl.insert_str(0, &page_waves::ballot_declarations(compute_group(ex).into_iter().product())); + } if page_waves || wave_cull { if fspx_wave == Some(32) { hlsl.insert_str(0, fspx_wave::WAVE32); @@ -2152,6 +2456,7 @@ impl<'a> Emitter<'a> { compute_swizzle: false, vote_defs: BTreeSet::new(), vote_uses: BTreeMap::new(), + exec_snapshots: Default::default(), reflected_lds_words: None, hoisted_swizzle: None, indexed_lane: false, @@ -2292,6 +2597,13 @@ impl<'a> Emitter<'a> { // Existing FSSM single-range layouts may address beyond the declared range. if let [range] = ranges { if range.base_register == 0 && range.space == 0 && matches!(range.offset_in_table, 0 | u32::MAX) { + // The runtime can append a reflected descriptor beyond a finite 1.1 + // table. Use that binding before extrapolating the single range. + if index >= range.num && stride == 32 && self.ex.root_sig.as_ref().is_some_and(|r| r.version == 2) { + if let Some((kind, register, space)) = self.uncovered_fssm_descriptor(sgpr, offset) { + return Ok((Some(kind), register, space)); + } + } return Ok((Some(range.range_type), index, 0)); } } @@ -3254,13 +3566,13 @@ impl<'a> Emitter<'a> { fn direct_raw_descriptor(&mut self, instructions: &[Insn], written: &BTreeSet) -> Option<(u16, u32)> { let [format, size, low, high] = instructions else { return None; }; if [format, size, low].iter().any(|op| op.mnemonic != "s_mov_b32") - || high.mnemonic != "s_or_b32" || format.src != [Opnd::Literal(0x11014fac)] + || format.src != [Opnd::Literal(0x11014fac)] || size.src != [Opnd::ConstInt(-1)] { return None; } let [Opnd::Sgpr(base)] = low.dst[..] else { return None; }; let [Opnd::Sgpr(root)] = low.src[..] else { return None; }; if base > 124 || root > 126 || written.contains(&u16::from(root)) || written.contains(&(u16::from(root)+1)) || format.dst != [Opnd::Sgpr(base+3)] || size.dst != [Opnd::Sgpr(base+2)] - || high.dst != [Opnd::Sgpr(base+1)] || high.src != [Opnd::Sgpr(root+1), Opnd::Literal(65536)] { return None; } + || high.dst != [Opnd::Sgpr(base+1)] || !raw_index::sets_byte_stride(high, root+1) { return None; } let [binding] = &self.ex.resources[..] else { return None; }; if binding.res_type != 4 || binding.lower != binding.upper { return None; } let slot = binding.lower; @@ -4011,12 +4323,16 @@ impl<'a> Emitter<'a> { let mut written: BTreeSet = BTreeSet::new(); let mut live: BTreeSet<(u8, u32)> = BTreeSet::new(); for ins in &self.insns { - if ins.mnemonic == "v_nop" { + if matches!(ins.mnemonic.as_str(), "v_nop" | "s_setreg_imm32_b32") { continue; } - // Packed FMAC accumulates in its destination. A subword FMA also - // reads that register to preserve the half outside its write mask. - let old_dst = (matches!(ins.mnemonic.as_str(), "v_pk_fmac_f16" | "v_fma_f16" | "v_rcp_f16") || int16::new_half(ins)) + // Accumulators and partial writes implicitly read the old destination. + let keep_other_bits = ins.aux.sdwa.is_none_or(|sd| (sd >> 8) & 7 != 6 && (sd >> 11) & 3 == 2); + let setreg = ins.mnemonic == "s_setreg_b32"; + let old_dst = ((setreg && modeled_hwreg_mask(ins.raw[0]) != 0) + || matches!(ins.mnemonic.as_str(), "v_pk_fmac_f16" | "v_fma_f16" | "v_rcp_f16") + || ((half_round_or_conversion(&ins.mnemonic) || ins.mnemonic == "v_cvt_f16_f32") && keep_other_bits) + || int16::new_half(ins)) .then(|| ins.dst.first()).flatten(); for o in ins.src.iter().chain(old_dst) { if let Opnd::Sgpr(n) | Opnd::Vgpr(n) = o { @@ -4026,6 +4342,9 @@ impl<'a> Emitter<'a> { } } } + if setreg { + continue; + } if let Some(high) = float64::pair_source_highs(ins) { if !written.contains(&format!("v{high}")) { live.insert((1, high)); @@ -4160,10 +4479,44 @@ impl<'a> Emitter<'a> { out } + fn fp32_extrema(&self, ins: &Insn, first: String) -> Result { + let maximum = ins.mnemonic == "v_max_f32"; + let mode = if self.regs.contains("tb_fp_mode") { "tb_fp_mode" } else { "0xc0u" }; + let (first, second) = dpp_fp32_sources(ins, first)?; + Ok(format!("tb_quad_extrema({first}, {second}, {maximum}, {mode})")) + } + fn push_helpers(&self, h: &mut String) { h.push_str(CUBE_HELPERS); + if self.insns.iter().any(clamped_product24) { + h.push_str(MAD24_SAT); + } h.push_str(if self.single_wave32 { HALF_RNE_STRAIGHT_LINE } else { HALF_RNE }); h.push_str(HALF_HELPERS); + if self.insns.iter().any(|ins| matches!(ins.mnemonic.as_str(), "v_cvt_u32_f32" | "v_cvt_i32_f32")) { + h.push_str(include_str!("float_to_integer.hlsl")); + } + if self.insns.iter().any(|ins| ins.mnemonic == "v_fract_f32") { + h.push_str(include_str!("fract_f32.hlsl")); + } + if self.insns.iter().any(|i| i.op == OP_DPP_BINARY && matches!(i.mnemonic.as_str(), "v_min_f32" | "v_max_f32")) { + h.push_str(r#" +uint tb_quad_extrema(uint a, uint b, bool maximum, uint mode) { + if ((mode & 0x10u) == 0u) { + if ((a & 0x7fffffffu) < 0x00800000u) a &= 0x80000000u; + if ((b & 0x7fffffffu) < 0x00800000u) b &= 0x80000000u; + } + // Order -0 below +0. Keep operands as bits for the non-IEEE NaN selection rule. + uint keyA = (a & 0x80000000u) != 0u ? ~a : a ^ 0x80000000u; + uint keyB = (b & 0x80000000u) != 0u ? ~b : b ^ 0x80000000u; + uint result = (maximum ? keyA > keyB : keyA < keyB) ? a : b; + if ((a & 0x7fffffffu) > 0x7f800000u) result = b; + else if ((b & 0x7fffffffu) > 0x7f800000u) result = a; + if ((mode & 0x20u) == 0u && (result & 0x7fffffffu) < 0x00800000u) result &= 0x80000000u; + return result; +} +"#); + } if self.insns.iter().any(|i| i.mnemonic.starts_with("v_cmp") && (i.mnemonic.ends_with("_f64") || i.mnemonic.ends_with("_f32") || i.mnemonic.ends_with("_f16"))) { h.push_str(compare::FLOAT_HELPERS); } @@ -4192,7 +4545,17 @@ uint2 tb_field64(uint lo, uint hi, uint control, bool sign) { } "#); } - if self.regs.contains("tb_fp_mode") { + if self.insns.iter().any(|i| normalized_half_to_integer(&i.mnemonic)) { + h.push_str(include_str!("normalized_half.hlsl")); + } + let uses_half_unary = self.insns.iter().any(|i| half_unary_op(&i.mnemonic).is_some()); + let uses_half_output = self.insns.iter().any(|i| { + let modified = (i.enc == Enc::Vop3 && (i.aux.imm != 0 || i.aux.imm2 != 0)) + || i.aux.sdwa.is_some_and(|sd| sd & 0xe000 != 0); + modified && (half_unary_op(&i.mnemonic).is_some() + || integer_to_half(&i.mnemonic) || i.mnemonic == "v_cvt_f16_f32") + }); + if self.regs.contains("tb_fp_mode") || uses_half_unary || uses_half_output { h.push_str(r#" // V_CVT_F16_F32 uses the destination round mode. Work with magnitudes // so tiny directed results survive the host's single-precision FTZ mode. @@ -4200,12 +4563,34 @@ uint tb_mode_half(float value, uint mode) { uint bits = asuint(value), magnitude = bits & 0x7fffffffu; if (magnitude < 0x00800000u && (mode & 0x10u) == 0u) return (bits >> 16) & 0x8000u; + // FP16_OVFL saturates finite overflow, preserving true infinities. + if ((mode & 0x800000u) != 0u && magnitude > 0x477fe000u && magnitude < 0x7f800000u) + return ((bits >> 16) & 0x8000u) | 0x7bffu; uint rounding = (mode >> 2) & 3u; uint h = tb_f16_cvt(value, rounding != 0u); bool away = rounding == ((bits >> 31) != 0u ? 2u : 1u); if (away && magnitude < 0x7f800000u && asuint(f16tof32(h & 0x7fffu)) < magnitude) h++; return (h & 0x7fffu) < 0x400u && (mode & 0x80u) == 0u ? h & 0x8000u : h; } +"#); + } + if uses_half_unary { + h.push_str(include_str!("half_unary.hlsl")); + } + if uses_half_output { + h.push_str(r#" +uint tb_half_output(uint bits, uint mode, float scale, bool clampResult) { + // Scaling preserves NaN payloads. CLAMP clears them only in DX10 mode. + if ((bits & 0x7fffu) > 0x7c00u) + return clampResult && (mode & 0x100u) != 0u ? 0u : bits; + // On RDNA2, OMOD is disabled with output denormals or IEEE mode. + if (scale != 1.0 && (mode & 0x280u) == 0u) { + float x = (bits & 0x7fffu) == 0u ? 0.0 : f16tof32(bits); + bits = tb_mode_half(x * scale, mode); + } + if (!clampResult) return bits; + return (bits & 0x8000u) != 0u ? 0u : min(bits, 0x3c00u); +} "#); } if self.insns.iter().any(|i| matches!(i.mnemonic.as_str(), "v_fma_f16" | "v_pk_fmac_f16" | "v_fmaak_f16" | "v_fmamk_f16")) { @@ -4450,7 +4835,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { self.emit_compute_swizzle(i, ins, &active)?; self.hoisted_swizzle = Some(i); } - if ins.mnemonic == "tb_first_exec_lane" { + if ins.mnemonic == "tb_first_exec_lane" && !self.exec_snapshots.sites.contains_key(&i) { self.end_guard(&mut open); cur.clear(); let mut condition=String::from("(exec_lo & 1u) != 0u"); @@ -4477,37 +4862,75 @@ uint tb_fmac_half(uint a, uint b, uint c) { return Ok(()); } if is_quad_exchange(ins) { - if self.loop_depth != 0 && !(self.pixel_wave && ins.op != OP_ROW_MIRROR) { + if self.loop_depth != 0 && (!self.pixel_wave || is_row_move(ins)) { return Err("DPP16 exchange inside backward control flow".into()); } if open { self.end_guard(&mut open); cur.clear(); } - if self.pixel_wave && ins.op != OP_ROW_MIRROR { + if self.pixel_wave && !is_row_move(ins) { self.emit_pixel_quad_exchange(i, ins)?; - } else if ins.op == OP_ROW_MIRROR { - let source = r(&ins.src[0])?; - // FI=0: a source lane inactive in EXEC contributes 0. row_mirror - // mirrors local lanes within a 16-lane row. - self.line(&format!("uint q{i}lane = WaveGetLaneIndex();")); - self.line(&format!("uint q{i}src = (q{i}lane & ~15u) | (15u - (q{i}lane & 15u));")); - self.line(&format!("uint q{i}act = q{i}src < 32u ? (exec_lo >> q{i}src) & 1u : (exec_hi >> (q{i}src - 32u)) & 1u;")); - self.line(&format!("uint q{i} = q{i}act != 0u ? WaveReadLaneAt({source}, q{i}src) : 0u;")); } else { let source = r(&ins.src[0])?; - // All host lanes participate before the guest destination guards. - let perm = ins.aux.imm; - self.line(&format!("uint q{i}lane = WaveGetLaneIndex();")); - let lane = format!("(q{i}lane & ~3u) | (({perm}u >> (2u * (q{i}lane & 3u))) & 3u)"); - if ins.raw[1] & (1 << 18) != 0 { - self.line(&format!("uint q{i} = WaveReadLaneAt({source}, {lane});")); - } else if ins.raw[1] & (1 << 19) != 0 { - self.line(&format!("uint q{i} = WaveReadLaneAt((exec_lo & 1u) != 0u ? {source} : 0u, {lane});")); + if ins.op == OP_DPP_BINARY { + // All host lanes participate before the guest destination guards. + let perm = ins.aux.imm; + self.line(&format!("uint q{i}lane = WaveGetLaneIndex();")); + let dpp8 = group_extrema::is_dpp8(ins); + let lane = if dpp8 { + format!("(q{i}lane & ~7u) | (({perm}u >> (3u * (q{i}lane & 7u))) & 7u)") + } else if perm == 0x140 { + format!("q{i}lane ^ 15u") + } else if (0x121..=0x12f).contains(&perm) { + format!("(q{i}lane & ~15u) | ((q{i}lane - {}u) & 15u)", perm & 15) + } else { format!("(q{i}lane & ~3u) | (({perm}u >> (2u * (q{i}lane & 3u))) & 3u)") }; + if dpp8 || ins.raw[1] & (1 << 18) != 0 { + self.line(&format!("uint q{i} = WaveReadLaneAt({source}, {lane});")); + } else if ins.raw[1] & (1 << 19) != 0 { + self.line(&format!("uint q{i} = WaveReadLaneAt((exec_lo & 1u) != 0u ? {source} : 0u, {lane});")); + } else { + self.line(&format!("uint2 q{i}pair = WaveReadLaneAt(uint2({source}, exec_lo & 1u), {lane});")); + self.line(&format!("uint q{i} = q{i}pair.x;")); + self.line(&format!("bool q{i}active = q{i}pair.y != 0u;")); + } } else { - self.line(&format!("uint2 q{i}pair = WaveReadLaneAt(uint2({source}, exec_lo & 1u), {lane});")); - self.line(&format!("uint q{i} = q{i}pair.x;")); - self.line(&format!("bool q{i}active = q{i}pair.y != 0u;")); + let selector = ins.aux.imm; + let lane = match ins.op { + OP_QUAD_MOVE => { + self.line(&format!("uint q{i}lane = WaveGetLaneIndex();")); + format!("(q{i}lane & ~3u) | (({selector}u >> (2u * (q{i}lane & 3u))) & 3u)") + } + OP_ROW_SHARE_MOVE => format!("(WaveGetLaneIndex() & ~15u) | {selector}u"), + OP_ROW_ROR_MOVE => format!("(WaveGetLaneIndex() & ~15u) | ((WaveGetLaneIndex() - {selector}u) & 15u)"), + OP_ROW_SHIFT_MOVE => { + let sign = if selector < 0 { "-" } else { "+" }; + self.line(&format!("uint q{i}offset = (WaveGetLaneIndex() & 15u) {sign} {}u;", selector.abs())); + // Keep the wave read in range even for lanes that will discard its value. + format!("(WaveGetLaneIndex() & ~15u) | (q{i}offset & 15u)") + } + _ => format!("WaveGetLaneIndex() ^ {selector}u"), + }; + let fetch_inactive = ins.raw[1] & (1 << 18) != 0; + let bound_ctrl = ins.raw[1] & (1 << 19) != 0; + let lane = if is_row_move(ins) || !fetch_inactive { + self.line(&format!("uint q{i}src = {lane};")); + format!("q{i}src") + } else { lane }; + if fetch_inactive { + self.line(&format!("uint q{i} = WaveReadLaneAt({source}, {lane});")); + } else if bound_ctrl { + self.line(&format!("uint q{i} = WaveReadLaneAt((exec_lo & 1u) != 0u ? {source} : 0u, {lane});")); + } else { + // An inactive source suppresses the write to this lane's destination. + let dst = r(&ins.dst[0])?; + self.line(&format!("uint2 q{i}pair = WaveReadLaneAt(uint2({source}, exec_lo & 1u), {lane});")); + self.line(&format!("uint q{i} = q{i}pair.y != 0u ? q{i}pair.x : {dst};")); + } + if ins.op == OP_ROW_SHIFT_MOVE { + let fallback = if bound_ctrl { "0u".to_string() } else { r(&ins.dst[0])? }; + self.line(&format!("if (q{i}offset >= 16u) q{i} = {fallback};")); + } } } } @@ -4627,7 +5050,12 @@ uint tb_fmac_half(uint a, uint b, uint c) { let selected = if preserve { format!("q{i}pair") } else { format!("q{i}") }; self.line(&format!("{ty} {selected} = q{i}src == 0u ? {source} : q{i}src == 1u ? q{i}x : q{i}src == 2u ? q{i}y : q{i}d;")); if preserve { - self.line(&format!("uint q{i} = q{i}pair.x; bool q{i}active = q{i}pair.y != 0u;")); + if ins.op == OP_QUAD_MOVE { + let dst = r(&ins.dst[0])?; + self.line(&format!("uint q{i} = q{i}pair.y != 0u ? q{i}pair.x : {dst};")); + } else { + self.line(&format!("uint q{i} = q{i}pair.x; bool q{i}active = q{i}pair.y != 0u;")); + } } Ok(()) } @@ -4691,7 +5119,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { for o in ins.src.iter().chain(ins.dst.iter()) { self.touch(o); } - if is_quad_exchange(ins) && self.pixel_wave && ins.op != OP_ROW_MIRROR { + if is_quad_exchange(ins) && self.pixel_wave && !is_row_move(ins) { self.emit_pixel_quad_exchange(i, ins)?; } let is_ctl = ins.enc == Enc::Sopp && (Self::branch_cond(ins.op).is_some() || ins.op == 1); @@ -4747,9 +5175,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { expr } - /// Wrap a float result with VOP3 omod/clamp and convert to uint bits. - fn fres(&self, ins: &Insn, e: String) -> String { - let mut e = e; + fn float_result(ins: &Insn, mut e: String) -> String { if ins.enc == Enc::Vop3 { e = match ins.aux.imm2 { 1 => format!("(({e}) * 2.0)"), @@ -4761,7 +5187,11 @@ uint tb_fmac_half(uint a, uint b, uint c) { e = format!("saturate({e})"); } } - format!("asuint({e})") + e + } + + fn fres(&self, ins: &Insn, e: String) -> String { + format!("asuint({})", Self::float_result(ins, e)) } fn pair_high(&mut self, operand: &Opnd) -> Result { @@ -4771,10 +5201,17 @@ uint tb_fmac_half(uint a, uint b, uint c) { _ => return Err("unsupported 64-bit operand pair".into()), }; self.touch(&high); - r(&high) + self.numeric_input(&high) + } + + fn numeric_input(&self, operand: &Opnd) -> Result { + match self.exec_snapshots.word(self.cur_idx, operand) { + Some(word) => Ok(word), + None => r(operand), + } } - fn int_compare(m: &str, a: &Opnd, b: &Opnd) -> Result { + fn int_compare(&self, m: &str, a: &Opnd, b: &Opnd) -> Result { let mut parts = m.rsplit('_'); let ty = parts.next().unwrap_or(""); let cc = parts.next().unwrap_or(""); @@ -4784,7 +5221,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { if matches!(o, Opnd::ConstF32(_)) { return Err("inline float constant in a 16-bit integer compare".into()); } - let bits = r(o)?; + let bits = self.numeric_input(o)?; Ok(if ty == "i16" { format!("(asint({bits} << 16) >> 16)") } else { @@ -4793,8 +5230,8 @@ uint tb_fmac_half(uint a, uint b, uint c) { }; (half(a)?, half(b)?) } - "i32" => (format!("asint({})", r(a)?), format!("asint({})", r(b)?)), - "u32" => (r(a)?, r(b)?), + "i32" => (format!("asint({})", self.numeric_input(a)?), format!("asint({})", self.numeric_input(b)?)), + "u32" => (self.numeric_input(a)?, self.numeric_input(b)?), other => return Err(format!("compare type {other} unsupported")), }; Ok(match cc { @@ -4825,6 +5262,9 @@ uint tb_fmac_half(uint a, uint b, uint c) { let d = ins.dst.first().cloned(); self.line(&format!("// {:#06x} {m}", ins.offset)); self.cur_idx = idx; + if let Some(&site) = self.exec_snapshots.sites.get(&idx) { + if site.emit(self, idx, ins)? { return Ok(()); } + } if m == "tb_reflection_far_query" { reflection_far::emit(self, ins); return Ok(()); @@ -5388,20 +5828,24 @@ uint tb_fmac_half(uint a, uint b, uint c) { Enc::Sopk => { let d = d.ok_or("no dst")?; let imm = format!("{:#x}u", ins.aux.imm as i32 as u32); + let mask = modeled_hwreg_mask(ins.raw[0]); match m { "s_version" => Ok(()), "s_movk_i32" => self.ws(&d, &imm), "s_cmovk_i32" => self.ws(&d, &format!("((scc != 0u) ? {imm} : {})", name(&d)?)), "s_setreg_imm32_b32" | "s_setreg_b32" | "s_getreg_b32" - if matches!(ins.raw[0] & 63, 20 | 21) || (ins.raw[0] & 63 == 1 && ((ins.raw[0] >> 6) & 31) + ((ins.raw[0] >> 11) & 31) < 8) => { - // The retail setup writes FLAT_SCRATCH_LO/HI. Model the - // two register words and the encoded bit slice independently. - let reg = if ins.raw[0] & 63 == 1 { "tb_fp_mode".to_string() } else { format!("tb_flat_scratch{}", ins.raw[0] & 1) }; - self.regs.insert(reg.clone()); + if mask != 0 => { + let id = ins.raw[0] & 63; let shift = (ins.raw[0] >> 6) & 31; let width = ((ins.raw[0] >> 11) & 31) + 1; if shift + width > 32 { return Err("hardware register field exceeds word".into()); } - let mask = u32::MAX >> (32 - width); + // Reads must be known in full. Writes need only update the + // intersection with the modeled register. + if m == "s_getreg_b32" && mask != u32::MAX >> (32 - width) { + return Err("unmodeled MODE read field".into()); + } + let reg = if id == 1 { "tb_fp_mode".to_string() } else { format!("tb_flat_scratch{}", id & 1) }; + self.regs.insert(reg.clone()); if m == "s_getreg_b32" { return self.ws(&d, &format!("(({reg} >> {shift}) & {mask:#x}u)")); } @@ -5414,8 +5858,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { self.line(&format!("{reg} = ({reg} & ~{:#x}u) | (({value} & {mask:#x}u) << {shift});", mask << shift)); Ok(()) } - // Hardware mode-register writes (rounding / denormal control) and the - // counter waits have no HLSL-visible effect. + // Other hardware-register writes and counter waits do not change the modeled state. "s_setreg_imm32_b32" | "s_setreg_b32" | "s_waitcnt_vscnt" | "s_waitcnt_vmcnt" | "s_waitcnt_expcnt" | "s_waitcnt_lgkmcnt" => Ok(()), "s_addk_i32" => { @@ -5429,7 +5872,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { "s_mulk_i32" => self.ws(&d, &format!("({} * {imm})", name(&d)?)), _ if m.starts_with("s_cmpk_") => { let fake = m.replace("s_cmpk_", "s_cmp_"); - let c = Self::int_compare(&fake, &d, &Opnd::ConstInt(ins.aux.imm))?; + let c = self.int_compare(&fake, &d, &Opnd::ConstInt(ins.aux.imm))?; self.line(&format!("scc = {c} ? 1u : 0u;")); Ok(()) } @@ -5454,7 +5897,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { r(&hi(&s[0]))?, r(&hi(&s[1]))? ), - _ => Self::int_compare(m, &s[0], &s[1])?, + _ => self.int_compare(m, &s[0], &s[1])?, }; self.line(&format!("scc = {c} ? 1u : 0u;")); Ok(()) @@ -6265,24 +6708,83 @@ uint tb_fmac_half(uint a, uint b, uint c) { } else { format!("WaveReadLaneAt({value}, {lane})") }; return self.ws(&d, &read); } + if ins.enc == Enc::Vop2 && ins.op == OP_LOCAL_EXTREMA { + let value = self.fp32_extrema(ins, r(&s[0])?)?; + return self.wv(&d, &value); + } if is_quad_exchange(ins) { - if self.dispatched && !(self.pixel_wave && ins.op != OP_ROW_MIRROR) { + if self.dispatched && (!self.pixel_wave || is_row_move(ins)) { return Err("quad exchange in a block-dispatched program".into()); } + if ins.op != OP_DPP_BINARY { + let value = format!("q{}", self.cur_idx); + let control = ins.raw[1]; + if control >> 24 != 0xff { + if self.ex.stage != Stage::Compute { + return Err("masked DPP16 move requires a known compute wave width".into()); + } + // Destination masks do not affect which lanes can supply the source. + let rows = control >> 28; + let banks = (control >> 24) & 15; + let row = format!("({rows:#x}u >> (WaveGetLaneIndex() >> 4u))"); + let bank = format!("({banks:#x}u >> ((WaveGetLaneIndex() >> 2u) & 3u))"); + return self.wv(&d, &format!("(({row} & {bank} & 1u) != 0u) ? {value} : {}", r(&d)?)); + } + return self.wv(&d, &value); + } let peer = format!("q{}", self.cur_idx); - if ins.op != OP_QUAD_BINARY { return self.wv(&d, &peer); } let value = match ins.mnemonic.as_str() { - "v_add_f32" => format!("asuint(asfloat({peer}) + {})", f(&s[1])?), + op @ ("v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32") => { + let (a, b) = dpp_fp32_sources(ins, peer.clone())?; + match op { + "v_add_f32" => format!("asuint(asfloat({a}) + asfloat({b}))"), + "v_sub_f32" => format!("asuint(asfloat({a}) - asfloat({b}))"), + "v_subrev_f32" => format!("asuint(asfloat({b}) - asfloat({a}))"), + "v_mul_f32" => format!("asuint(asfloat({a}) * asfloat({b}))"), + _ => format!("asuint(tb_mull(asfloat({a}), asfloat({b})))"), + } + } + "v_min_f32" | "v_max_f32" => self.fp32_extrema(ins, peer.clone())?, + "v_cvt_pkrtz_f16_f32" => { + let (lo, hi) = dpp_fp32_sources(ins, peer.clone())?; + format!("(tb_f16_rtz(asfloat({lo})) | (tb_f16_rtz(asfloat({hi})) << 16))") + } "v_or_b32" => format!("{peer} | {}", r(&s[1])?), "v_and_b32" => format!("{peer} & {}", r(&s[1])?), "v_xor_b32" => format!("{peer} ^ {}", r(&s[1])?), - _ => return Err("unknown quad binary operation".into()), + "v_xnor_b32" => format!("~({peer} ^ {})", r(&s[1])?), + "v_cndmask_b32" => format!("(vcc_lo & 1u) != 0u ? {} : {peer}", r(&s[1])?), + "v_add_nc_u32" => format!("{peer} + {}", r(&s[1])?), + "v_sub_nc_u32" => format!("{peer} - {}", r(&s[1])?), + "v_subrev_nc_u32" => format!("{} - {peer}", r(&s[1])?), + "v_lshlrev_b32" => format!("{} << ({peer} & 31u)", r(&s[1])?), + "v_lshrrev_b32" => format!("{} >> ({peer} & 31u)", r(&s[1])?), + "v_ashrrev_i32" => format!("asuint(asint({}) >> ({peer} & 31u))", r(&s[1])?), + "v_min_i32" => format!("asuint(min(asint({peer}), asint({})))", r(&s[1])?), + "v_max_i32" => format!("asuint(max(asint({peer}), asint({})))", r(&s[1])?), + "v_min_u32" => format!("min({peer}, {})", r(&s[1])?), + "v_max_u32" => format!("max({peer}, {})", r(&s[1])?), + op => mul24_expr(op, &peer, &r(&s[1])?).ok_or("unknown quad binary operation")?, }; - // FI=0 and BOUND_CTRL=0 suppress the entire write on an inactive source. - if ins.raw[1] & (3 << 18) == 0 { - return self.wv(&d, &format!("{peer}active ? ({value}) : {}", r(&d)?)); + // The source exchange precedes both the destination mask and EXEC. + let mut guards = Vec::new(); + if let Some(mask) = group_extrema::destination_mask(ins) { + if self.ex.stage != Stage::Compute { + return Err("DPP16 destination masks require a logical compute lane index".into()); + } + let rows = mask >> 4; + let banks = mask & 15; + if rows != 15 { + let row_bits = group_extrema::row_index_mask(self, rows, banks)?; + guards.push(format!("(({rows:#x}u >> ((tb_lane >> 4u) & {row_bits}u)) & 1u) != 0u")); + } + if banks != 15 { guards.push(format!("(({banks:#x}u >> ((tb_lane >> 2u) & 3u)) & 1u) != 0u")); } } - return self.wv(&d, &value); + if !group_extrema::is_dpp8(ins) && ins.raw[1] & (3 << 18) == 0 { + guards.push(format!("{peer}active")); + } + if guards.is_empty() { return self.wv(&d, &value); } + return self.wv(&d, &format!("{} ? ({value}) : {}", guards.join(" && "), r(&d)?)); } if ins.op == OP_WAVE_REDUCE && ins.enc == Enc::Vop3 { // See `lower_wave_reductions`. Every invocation computes the same value; lanes @@ -6302,7 +6804,8 @@ uint tb_fmac_half(uint a, uint b, uint c) { // exactly as for f32 (see `fm` / `fres`). let h16 = |o: &Opnd| -> Result { let mut e = match o { - Opnd::ConstF32(_) => f(o)?, + // Inline selector 248 has distinct binary16 and binary32 values. + Opnd::ConstF32(value) => f(&Opnd::ConstF32(inline_half_value(*value)))?, _ => format!("f16tof32(({}) & 0xffffu)", r(o)?), }; if ins.enc == Enc::Vop3 { @@ -6317,21 +6820,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { } Ok(e) }; - let hres = |e: String| -> String { - let mut e = e; - if ins.enc == Enc::Vop3 { - e = match ins.aux.imm2 { - 1 => format!("(({e}) * 2.0)"), - 2 => format!("(({e}) * 4.0)"), - 3 => format!("(({e}) * 0.5)"), - _ => e, - }; - if ins.aux.imm != 0 { - e = format!("saturate({e})"); - } - } - format!("tb_f16_rne({e})") - }; + let hres = |e| format!("tb_f16_rne({})", Self::float_result(ins, e)); let half_binary = matches!(m.as_str(), "v_add_f16" | "v_sub_f16" | "v_subrev_f16" | "v_mul_f16" | "v_max_f16" | "v_min_f16"); if ins.aux.sdwa.is_none() && half_binary { let (a, b) = (h16(&s[0])?, h16(&s[1])?); @@ -6353,27 +6842,62 @@ uint tb_fmac_half(uint a, uint b, uint c) { let lo = format!("tb_trig_f16({bits}, {})", m == "v_cos_f16"); return self.wv(&d, &format!("(({} & 0xffff0000u) | {lo})", r(&d)?)); } - if ins.aux.sdwa.is_none() && matches!(m.as_str(), "v_rcp_f16" | "v_sqrt_f16" | "v_rsq_f16" | "v_exp_f16" | "v_floor_f16" | "v_ceil_f16" | "v_trunc_f16" | "v_rndne_f16" | "v_fract_f16") { + let unary_op = half_unary_op(&m); + let modified_half_bits = || -> Result { + let mut bits = half_operand_bits(&s[0])?; + if ins.enc == Enc::Vop3 { + if ins.aux.mask & 1 != 0 { bits = format!("(({bits}) & 0x7fffu)"); } + if ins.aux.mask & 8 != 0 { bits = format!("(({bits}) ^ 0x8000u)"); } + } + Ok(bits) + }; + let half_int_src = integer_to_half(&m); + if ins.aux.sdwa.is_none() && (unary_op.is_some() || half_int_src) { + let has_mode = self.regs.contains("tb_fp_mode"); + let mode = if has_mode { "tb_fp_mode" } else { "0xc0u" }; + let narrow = |value| if has_mode { + format!("tb_mode_half({value}, {mode})") + } else { + format!("tb_f16_rne({value})") + }; + let mut bits = if let Some(op) = unary_op { + if let Opnd::ConstF32(value) = s[0] { + // Inline floats are finite normal halves. Only 1/(2*pi) + // has a distinct rounded value in the half-precision ROM. + let mut value = inline_half_value(value); + if ins.enc == Enc::Vop3 { + if ins.aux.mask & 1 != 0 { value = value.abs(); } + if ins.aux.mask & 8 != 0 { value = -value; } + } + let x = f(&Opnd::ConstF32(value))?; + format!("tb_finite_unary_f16({x}, {mode}, {op}u)") + } else { + format!("tb_unary_f16({}, {mode}, {op}u)", modified_half_bits()?) + } + } else { + let raw = half_operand_bits(&s[0])?; + let integer = if m == "v_cvt_f16_i16" { + format!("(asint(({raw}) << 16) >> 16)") + } else { + format!("(({raw}) & 0xffffu)") + }; + narrow(format!("(float){integer}")) + }; + if ins.enc == Enc::Vop3 && (ins.aux.imm2 != 0 || ins.aux.imm != 0) { + let scale = ["1.0", "2.0", "4.0", "0.5"][ins.aux.imm2 as usize]; + let clamp = ins.aux.imm != 0; + bits = format!("tb_half_output({bits}, {mode}, {scale}, {clamp})"); + } + return self.wv(&d, &format!("(({} & 0xffff0000u) | {bits})", r(&d)?)); + } + if ins.aux.sdwa.is_none() && matches!(m.as_str(), "v_rcp_f16" | "v_sqrt_f16" | "v_rsq_f16" | "v_exp_f16") { let a = h16(&s[0])?; let e = match m.as_str() { "v_rcp_f16" => format!("1.0 / {a}"), "v_sqrt_f16" => format!("sqrt({a})"), "v_rsq_f16" => format!("rsqrt({a})"), - "v_exp_f16" => format!("exp2({a})"), - "v_floor_f16" => format!("floor({a})"), - "v_ceil_f16" => format!("ceil({a})"), - "v_trunc_f16" => format!("trunc({a})"), - "v_rndne_f16" => format!("round({a})"), - _ => format!("frac({a})"), + _ => format!("exp2({a})"), }; - if m == "v_fract_f16" { - // The result stays below 1.0: a fraction that rounds up to 1.0 in half - // precision gives the largest half below 1 (0x3bff), as for D3D frc. - let t = self.tmp; - self.tmp += 1; - self.line(&format!("uint t{t} = {};", hres(e))); - return self.wv(&d, &format!("(t{t} == 0x3c00u ? 0x3bffu : t{t})")); - } // The compact reciprocal updates the low half. The FSPX shader first // writes the high reciprocal via SDWA, then fills the low half here. if m == "v_rcp_f16" && ins.enc == Enc::Vop1 && matches!(d, Opnd::Vgpr(_)) { @@ -6381,21 +6905,27 @@ uint tb_fmac_half(uint a, uint b, uint c) { } return self.wv(&d, &hres(e)); } - if m == "v_cvt_f16_u16" { - return self.wv(&d, &format!("tb_f16_rne((float)(({}) & 0xffffu))", r(&s[0])?)); - } - if m == "v_cvt_f16_i16" { - return self.wv(&d, &format!("tb_f16_rne((float)(asint(({}) << 16) >> 16))", r(&s[0])?)); - } - if m == "v_cvt_u16_f16" { - // Truncating, saturating; NaN converts to 0 (tested on the 16-bit pattern: the - // compiler may assume float values are never NaN). - let x = r(&s[0])?; - return self.wv(&d, &format!("((({x}) & 0x7fffu) > 0x7c00u ? 0u : (uint)clamp({}, 0.0, 65535.0))", h16(&s[0])?)); - } - if m == "v_cvt_i16_f16" { - let x = r(&s[0])?; - return self.wv(&d, &format!("((({x}) & 0x7fffu) > 0x7c00u ? 0u : (asuint((int)clamp({}, -32768.0, 32767.0)) & 0xffffu))", h16(&s[0])?)); + let half_int_result = half_to_integer(&m); + if normalized_half_to_integer(&m) && ins.aux.sdwa.is_none() { + let bits = modified_half_bits()?; + let mode = if self.regs.contains("tb_fp_mode") { "tb_fp_mode" } else { "0xc0u" }; + let signed = m == "v_cvt_norm_i16_f16"; + return self.wv(&d, &format!("(({} & 0xffff0000u) | tb_norm_f16({bits}, {mode}, {signed}))", r(&d)?)); + } + if half_int_result && ins.aux.sdwa.is_none() { + let x = h16(&s[0])?; + // Truncate after saturating. CLAMP controls the inexact exception, + // independently of the integer value produced by the conversion. + let mut value = if m == "v_cvt_u16_f16" { + format!("(uint)clamp({x}, 0.0, 65535.0)") + } else { + format!("(asuint((int)clamp({x}, -32768.0, 32767.0)) & 0xffffu)") + }; + if !matches!(s[0], Opnd::ConstF32(_)) { + // Test NaN on its stored bits before DXC can assume a finite float. + value = format!("((({}) & 0x7fffu) > 0x7c00u ? 0u : {value})", r(&s[0])?); + } + return self.wv(&d, &format!("(({} & 0xffff0000u) | {value})", r(&d)?)); } if matches!(m.as_str(), "v_fmaak_f16" | "v_fmamk_f16") { // The trailing literal dword carries the half-float constant K in its low bits. @@ -6708,6 +7238,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { match (ins.raw[0] >> 8) & 0x7f { c @ 0..=105 => Opnd::Sgpr(c as u8), 106 => Opnd::VccLo, + 125 if ins.raw[1] >> 27 == 0 => Opnd::Null, c => return Err(format!("carry-out register code {c} unsupported")), } } else { @@ -6730,7 +7261,8 @@ uint tb_fmac_half(uint a, uint b, uint c) { } let t = self.tmp; self.tmp += 1; - if m.starts_with("v_add") { + let add = m.starts_with("v_add"); + if add { self.line(&format!( "uint t{t}c = ({cin}) & 1u; uint t{t}a = {a} + {b}; uint t{t} = t{t}a + t{t}c; uint t{t}o = ((t{t}a < {a}) || (t{t} < t{t}a)) ? 1u : 0u;" )); @@ -6739,7 +7271,14 @@ uint tb_fmac_half(uint a, uint b, uint c) { "uint t{t}c = ({cin}) & 1u; uint t{t}a = {a} - {b}; uint t{t} = t{t}a - t{t}c; uint t{t}o = (({b} > {a}) || (t{t}c > t{t}a)) ? 1u : 0u;" )); } + if vop3f && ins.raw[0] & 0x8000 != 0 { + // Clamp the vector result only. SDST reports the original carry or borrow. + let limit = if add { "0xffffffffu" } else { "0u" }; + self.line(&format!("if (t{t}o != 0u) t{t} = {limit};")); + } self.wv(&d, &format!("t{t}"))?; + // A null SDST discards the outgoing flag after the incoming mask has been read. + if cout == Opnd::Null { return Ok(()); } self.touch(&cout); if self.persistent_queue { self.line(&format!("uint2 carry{t} = tb_ballot((exec_lo & t{t}o) != 0u);")); @@ -6766,16 +7305,30 @@ uint tb_fmac_half(uint a, uint b, uint c) { } let mut c = ins.clone(); c.aux.sdwa = None; - // The selected half operands now occupy the low word. Apply the - // floating modifiers through the ordinary VOP3 half-float path. - let half_alu = half_binary || matches!(m.as_str(), "v_rcp_f16" | "v_exp_f16"); - if half_alu { + if clamped_product24(ins) { + if sd & 0xc000 != 0 || (sd >> 11) & 3 == 3 { + return Err("unsupported SDWA destination control for 24-bit multiply".into()); + } + c.aux.imm = 1; // Saturate the full result before packing the destination. + } + // Reuse VOP3 floating modifiers after source selection and before destination packing. + let half_alu = half_binary || half_int_result || unary_op.is_some() || matches!(m.as_str(), "v_rcp_f16" | "v_exp_f16" | "v_cvt_f32_f16"); + let float_alu = half_alu || matches!(m.as_str(), + "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32" + | "v_min_f32" | "v_max_f32" | "v_fract_f32" | "v_trunc_f32" | "v_ceil_f32" + | "v_rndne_f32" | "v_floor_f32"); + // Integer conversions accept floating output modifiers but keep integer source rules. + let int_to_float = matches!(m.as_str(), + "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_off_f32_i4" | "v_cvt_f32_ubyte0" + | "v_cvt_f32_ubyte1" | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3"); + let float_source_modifiers = float_alu || m == "v_cvt_f16_f32"; + if float_source_modifiers || int_to_float || half_int_src { c.enc = Enc::Vop3; c.aux.imm = i64::from((sd >> 13) & 1); c.aux.imm2 = i64::from((sd >> 14) & 3); } if sd & 0x3030_0000 != 0 { - if !(half_alu || (is_cmp && (m.ends_with("_f16") || m.ends_with("_f32")))) + if !(float_source_modifiers || (is_cmp && (m.ends_with("_f16") || m.ends_with("_f32")))) || (m.contains("_class_") && sd & 0x3000_0000 != 0) { return Err("unsupported SDWA neg/abs for this operand type".into()); @@ -6797,8 +7350,9 @@ uint tb_fmac_half(uint a, uint b, uint c) { continue; } let mut x = r(&c.src[i])?; - if (is_cmp || half_alu) && m.ends_with("_f16") && (i == 0 || !m.contains("_class_")) - && matches!(c.src[i], Opnd::ConstF32(_)) + let half_constant = half_int_src || ((is_cmp || half_alu) && m.ends_with("_f16") + && (i == 0 || !m.contains("_class_"))); + if half_constant && matches!(c.src[i], Opnd::ConstF32(_)) { // The inline constant ROM supplies binary16 before byte/word selection. x = format!("tb_f16_rne(asfloat({x}))"); @@ -6818,19 +7372,23 @@ uint tb_fmac_half(uint a, uint b, uint c) { self.line(&format!("uint tb_s{t} = {e};")); c.src[i] = Opnd::Temp(t as u16); } - if dst_sel == 6 { + if dst_sel == 6 && !half_round_or_conversion(&m) && m != "v_cvt_f16_f32" { return self.emit_vec(&c); } // Partial destination: compute into a temporary, then place the selected // byte/word into the register. DST_UNUSED (bits 12:11): 0 = pad with zeros, // 1 = sign-extend upwards, 2 = keep the other bits of the destination. - let (bits, lsb) = if dst_sel <= 3 { (8u32, dst_sel * 8) } else { (16, (dst_sel - 4) * 16) }; - let mask = (1u32 << bits) - 1; let t = self.tmp; self.tmp += 1; self.line(&format!("uint tb_s{t} = 0u;")); c.dst = vec![Opnd::Temp(t as u16)]; self.emit_vec(&c)?; + if dst_sel == 6 { + // SDWA DWORD writes the entire zero-extended 16-bit result. + return self.wv(&d, &format!("tb_s{t}")); + } + let (bits, lsb) = if dst_sel <= 3 { (8u32, dst_sel * 8) } else { (16, (dst_sel - 4) * 16) }; + let mask = (1u32 << bits) - 1; let val = format!("(tb_s{t} & {mask:#x}u)"); let e = match (sd >> 11) & 3 { 0 => format!("({val} << {lsb})"), @@ -6853,7 +7411,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { } else if m.ends_with("_f64") || m.ends_with("_f32") || m.ends_with("_f16") { self.compare_float(ins, mask)? } else { - Self::int_compare(&m, &s[0], &s[1])? + self.int_compare(&m, &s[0], &s[1])? }; if self.resolve_wave32 { let vote = format!("WaveActiveBallot((exec_lo & tb_lane_bit) != 0u && {c}).x"); @@ -6979,8 +7537,17 @@ uint tb_fmac_half(uint a, uint b, uint c) { let fa = || self.fm(ins, 0); let fb = || self.fm(ins, 1); let fc = || self.fm(ins, 2); - let (a, b) = (r(&s[0])?, s.get(1).map(r).transpose()?.unwrap_or_default()); + let a = self.numeric_input(&s[0])?; + let b = s.get(1).map(|operand| self.numeric_input(operand)).transpose()?.unwrap_or_default(); let c = s.get(2).map(|o| r(o)).transpose().unwrap_or(None).unwrap_or_default(); + if clamped_product24(ins) { + if vop3 && (ins.raw[0] & 0x7800 != 0 || ins.aux.mask != 0 || ins.aux.imm2 != 0) { + return Err("unsupported modifiers for clamped 24-bit multiply".into()); + } + let acc = if m.starts_with("v_mad_") { c.as_str() } else { "0u" }; + let signed = m.ends_with("_i24"); + return self.wv(&d, &format!("tb_mad24_sat({a}, {b}, {acc}, {signed})")); + } // `v_mul_legacy_f32` / `v_mad_legacy_f32`: DX9 multiply rules — the product is 0 when // either operand is 0, even against infinity or NaN (`tb_mull`). A plain multiply // only matched under fast-math; with exact arithmetic it produced NaN positions. @@ -7017,8 +7584,11 @@ uint tb_fmac_half(uint a, uint b, uint c) { "v_cvt_f32_ubyte1" => Some(format!("(float)(({a} >> 8) & 0xffu)")), "v_cvt_f32_ubyte2" => Some(format!("(float)(({a} >> 16) & 0xffu)")), "v_cvt_f32_ubyte3" => Some(format!("(float)(({a} >> 24) & 0xffu)")), - "v_cvt_f32_f16" => Some(format!("f16tof32({a})")), - "v_fract_f32" => Some(format!("frac({})", fa()?)), + "v_cvt_f32_f16" => Some(h16(&s[0])?), + "v_fract_f32" => { + let mode = if self.regs.contains("tb_fp_mode") { "tb_fp_mode" } else { "0u" }; + Some(format!("tb_fract_f32({}, {mode})", fa()?)) + } "v_trunc_f32" => Some(format!("trunc({})", fa()?)), "v_ceil_f32" => Some(format!("ceil({})", fa()?)), "v_rndne_f32" => Some(format!("round({})", fa()?)), @@ -7040,7 +7610,9 @@ uint tb_fmac_half(uint a, uint b, uint c) { let e = self.fres(ins, e); return self.wv(&d, &e); } - let mask = if self.packed.as_ref().is_some_and(|p| p.lane_masks.contains(&self.cur_idx)) { + let mask = if matches!(self.exec_snapshots.sites.get(&self.cur_idx), Some(exec_snapshot::Site::LaneMask(..))) { + format!("select_mask{}", self.cur_idx) + } else if self.packed.as_ref().is_some_and(|p| p.lane_masks.contains(&self.cur_idx)) { let upper = if self.required_wave_size == Some(64) { r(&hi(&s[2]))? } else { "0u".into() }; @@ -7066,6 +7638,10 @@ uint tb_fmac_half(uint a, uint b, uint c) { "v_lshrrev_b32" => format!("({b} >> ({a} & 31u))"), "v_lshlrev_b32" => format!("({b} << ({a} & 31u))"), "v_ashrrev_i32" => format!("asuint(asint({b}) >> ({a} & 31u))"), + // Unsigned VOP3 clamp limits the operand before the operation can wrap. + "v_add_nc_u32" if vop3 && ins.aux.imm != 0 => format!("(min({a}, ~{b}) + {b})"), + "v_sub_nc_u32" if vop3 && ins.aux.imm != 0 => format!("(max({a}, {b}) - {b})"), + "v_subrev_nc_u32" if vop3 && ins.aux.imm != 0 => format!("(max({b}, {a}) - {a})"), "v_add_nc_u32" => format!("({a} + {b})"), "v_sub_nc_u32" => format!("({a} - {b})"), "v_subrev_nc_u32" => format!("({b} - {a})"), @@ -7073,8 +7649,6 @@ uint tb_fmac_half(uint a, uint b, uint c) { "v_max_u32" => format!("max({a}, {b})"), "v_min_i32" => format!("asuint(min(asint({a}), asint({b})))"), "v_max_i32" => format!("asuint(max(asint({a}), asint({b})))"), - "v_mul_u32_u24" => format!("(({a} & 0xffffffu) * ({b} & 0xffffffu))"), - "v_mul_i32_i24" => format!("asuint((asint({a} << 8) >> 8) * (asint({b} << 8) >> 8))"), "v_mul_lo_u32" => format!("({a} * {b})"), // Count the mask bits below this lane in the selected 32-bit word. "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => { @@ -7110,8 +7684,6 @@ uint tb_fmac_half(uint a, uint b, uint c) { format!("({b} + t{t})") } "v_mul_hi_u32" => format!("tb_mulhi_u32({a}, {b})"), - "v_mul_hi_u32_u24" => format!("tb_mulhi_u32({a} & 0xffffffu, {b} & 0xffffffu)"), - "v_mul_hi_i32_i24" => format!("tb_mulhi_i32(asuint(asint({a} << 8) >> 8), asuint(asint({b} << 8) >> 8))"), // Leading bits equal to the sign bit, from the MSB; -1 when all bits are equal. "v_ffbh_i32" => format!("(((asint({a}) < 0) ? ~({a}) : ({a})) == 0u ? 0xffffffffu : (31u - firstbithigh((asint({a}) < 0) ? ~({a}) : ({a}))))"), // {S0:S1} >> (8 * S2[1:0]), low 32 bits. @@ -7152,14 +7724,33 @@ uint tb_fmac_half(uint a, uint b, uint c) { "v_alignbit_b32" => format!( "((({c}) & 31u) == 0u ? {b} : (({b} >> (({c}) & 31u)) | ({a} << (32u - (({c}) & 31u)))))" ), - "v_cvt_u32_f32" => format!("(uint)max({}, 0.0)", fa()?), - "v_cvt_i32_f32" => format!("asuint((int){})", fa()?), + "v_cvt_u32_f32" => format!("tb_cvt_u32_f32({})", fa()?), + "v_cvt_i32_f32" => format!("tb_cvt_i32_f32({})", fa()?), "v_cvt_flr_i32_f32" => format!("asuint((int)floor({}))", fa()?), - "v_cvt_rpi_i32_f32" => format!("asuint((int)floor({} + 0.5))", fa()?), - // Round to nearest even. HLSL f32tof16's rounding is the driver's choice - // (observed: truncation on the development GPU), so it is not used. - "v_cvt_f16_f32" if self.regs.contains("tb_fp_mode") => format!("tb_mode_half({}, tb_fp_mode)", fa()?), - "v_cvt_f16_f32" => format!("tb_f16_rne({})", fa()?), + "v_cvt_rpi_i32_f32" => { + let x = fa()?; + let t = self.tmp; + self.tmp += 1; + // Adding 0.5 first can round an already integral f32 to the next integer. + // Start with nearest-even and raise only the ties that rounded down. + self.line(&format!("float t{t} = round({x});")); + format!("(asuint((int)t{t}) + (uint)(({x} - t{t}) == 0.5))") + } + "v_cvt_f16_f32" => { + let source = Self::select_source(ins, a, 0); + let modified = vop3 && (ins.aux.imm != 0 || ins.aux.imm2 != 0); + let mode = if self.regs.contains("tb_fp_mode") { "tb_fp_mode" } else { "0xc0u" }; + let mut bits = if modified || self.regs.contains("tb_fp_mode") { + format!("tb_mode_half(asfloat({source}), {mode})") + } else { + format!("tb_f16_rne(asfloat({source}))") + }; + if modified { + let scale = ["1.0", "2.0", "4.0", "0.5"][ins.aux.imm2 as usize]; + bits = format!("tb_half_output({bits}, {mode}, {scale}, {})", ins.aux.imm != 0); + } + format!("(({dn} & 0xffff0000u) | {bits})") + } // Round toward zero (ISA: "ignore the current rounding mode"): finite values never // become infinity (|x| >= 65504 gives 65504). "v_cvt_pkrtz_f16_f32" => format!("(tb_f16_rtz({}) | (tb_f16_rtz({}) << 16))", fa()?, fb()?), @@ -7168,7 +7759,7 @@ uint tb_fmac_half(uint a, uint b, uint c) { "v_sat_pk_u8_i16" => format!( "((uint)clamp(asint({a} << 16) >> 16, 0, 255) | ((uint)clamp(asint({a}) >> 16, 0, 255) << 8))" ), - _ => return Err("unsupported vector op".into()), + op => mul24_expr(op, &a, &b).ok_or("unsupported vector op")?, }; self.wv(&d, &e) } @@ -9224,7 +9815,8 @@ void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) {{"); if self.page_waves || self.wave_cull { writeln!(h, " uint tb_wave_tid = gtid.x + {tx}u * (gtid.y + {ty_}u * gtid.z);").unwrap(); } - if self.compute_swizzle || self.indexed_lane || self.single_wave32 { + let masked_dpp = self.insns.iter().any(|i| i.op == OP_DPP_BINARY && group_extrema::destination_mask(i).is_some()); + if self.compute_swizzle || self.indexed_lane || self.single_wave32 || masked_dpp { writeln!(h, " uint tb_lane = gtid.x + {tx}u * (gtid.y + {ty_}u * gtid.z);").unwrap(); } if self.resolve_wave32 { @@ -9682,6 +10274,255 @@ fn compute_heap_base(ex: &ShaderExtract) -> Option { mod tests { use super::*; + #[test] + fn vector_add_sub_can_discard_the_carry_destination() { + use super::float64::tests::translate; + + // gfx1030 VOP3B add, sub and subrev with SDST=null; the _ci_ forms read VCC. + for (opcode, sources) in [ + (0xd70f_7d04, 0x0002_0501), (0xd710_7d04, 0x0002_0501), + (0xd719_7d04, 0x0002_0501), (0xd528_7d04, 0x01aa_0501), + (0xd529_7d04, 0x01aa_0501), (0xd52a_7d04, 0x01aa_0501), + ] { + let hlsl = translate(Stage::Compute, &[opcode, sources]).unwrap(); + assert!(hlsl.contains("v4 = t"), "{hlsl}"); + assert!(!hlsl.lines().any(|line| { + let stmt = line.trim_start(); + stmt.starts_with("vcc_lo =") || stmt.starts_with("vcc_hi =") || stmt.starts_with("nul =") + }), "{hlsl}"); + assert!(translate(Stage::Compute, &[opcode, sources | (1 << 29)]).is_err()); + } + } + + #[test] + fn vector_carry_clamp_saturates_the_result_and_keeps_the_overflow_flag() { + use super::float64::tests::translate; + + for (opcode, limit) in [(0xd70f_ea04, "0xffffffffu"), (0xd710_ea04, "0u")] { + // gfx1030: v_{add,sub}_co_u32 v4, vcc_lo, v1, v2 clamp + let hlsl = translate(Stage::Compute, &[opcode, 0x0002_0501]).unwrap(); + assert!(hlsl.contains(&format!("if (t0o != 0u) t0 = {limit};")), "{hlsl}"); + assert!(hlsl.lines().any(|line| line.trim_start().starts_with("vcc_lo =") && line.contains("t0o"))); + } + + // In e32 the same bit belongs to the source register v66. + let hlsl = translate(Stage::Compute, &[0x5008_8501]).unwrap(); + assert!(!hlsl.contains("if (t0o != 0u)"), "{hlsl}"); + } + + #[test] + fn unsigned_no_carry_clamp_is_specific_to_the_long_encoding() { + use super::float64::tests::translate; + // LLVM gfx1030: v_{add,sub,subrev}_nc_u32_e64 v4, v1, v2 clamp. + for (opcode, saturated, wrapping) in [ + (0xd525_8004, "(min(v1, ~v2) + v2)", "(v1 + v2)"), + (0xd526_8004, "(max(v1, v2) - v2)", "(v1 - v2)"), + (0xd527_8004, "(max(v2, v1) - v1)", "(v2 - v1)"), + ] { + let hlsl = translate(Stage::Compute, &[opcode, 0x0002_0501]).unwrap(); + assert!(hlsl.contains(saturated), "{hlsl}"); + let hlsl = translate(Stage::Compute, &[opcode & !0x8000, 0x0002_0501]).unwrap(); + assert!(hlsl.contains(wrapping), "{hlsl}"); + } + // In e32 the same bit is part of the second source register (v66). + assert!(translate(Stage::Compute, &[0x4a08_8501]).unwrap().contains("(v1 + v66)")); + } + + #[test] + fn mul24_clamps_the_full_product_plus_accumulator_before_packing() { + for (words, args) in [ + ([0xd50b_8004, 0x0002_0501], "v1, v2, 0u, false"), // unsigned MUL + ([0xd542_8004, 0x040e_0501], "v1, v2, v3, true"), // signed MAD + ([0xd543_8004, 0x040e_0501], "v1, v2, v3, false"), // unsigned MAD + ([0x1208_04f9, 0x0606_3201], "v1, v2, 0u, true"), // signed MUL, BYTE_2 + ] { + let shader = translate_valu_probe(&words, 5).unwrap(); + assert!(shader.contains(&format!("= tb_mad24_sat({args});"))); + if words[0] == 0x1208_04f9 { + assert!(shader.contains("0xff00ffffu")); + } + } + let ordinary = translate_valu_probe(&[0xd50b_0004, 0x0002_0501], 5).unwrap(); + assert!(!ordinary.contains("tb_mad24_sat")); + // Integer products have no floating output scale; SDWA DST_UNUSED=3 is reserved. + for words in [ + [0xd50b_8004, 0x0802_0501], + [0x1208_04f9, 0x0606_7201], + [0x1208_04f9, 0x0606_3a01], + ] { + assert!(translate_valu_probe(&words, 5).is_err()); + } + } + + #[test] + fn half_rounding_reads_the_entry_destination_and_obeys_fp_mode() { + // s_denorm_mode 4; v_floor_f16_e64 v6,-|v1| mul:2 + let hlsl = float64::tests::translate( + Stage::Compute, &[0xbfa5_0004, 0xd5db_0106, 0x2800_0101], + ).unwrap(); + assert!(hlsl.lines().next().unwrap().split_whitespace().any(|word| word == "v6")); + let write = hlsl.lines().find(|line| line.contains("v6 & 0xffff0000u")).unwrap(); + assert!(write.contains("tb_unary_f16(") && write.contains("tb_fp_mode, 0u)")); + assert!(write.contains("tb_half_output(tb_unary_f16(") && write.contains("tb_fp_mode, 2.0, false")); + } + + #[test] + fn half_conversion_only_reads_destination_for_partial_writes() { + // Both directions, signed and unsigned: convert v1.h into v6.h. + for opcode in [0x7e0c_a0f9, 0x7e0c_a2f9, 0x7e0c_a4f9, 0x7e0c_a6f9, 0x7e0c_c6f9, 0x7e0c_c8f9] { + for (extension, preserve) in [(0x51501, true), (0x50501, false), (0x50d01, false), (0x51601, false)] { + let hlsl = float64::tests::translate(Stage::Compute, &[opcode, extension]).unwrap(); + let inputs = hlsl.lines().next().unwrap(); + assert_eq!(inputs.split_whitespace().any(|word| word == "v6"), preserve); + } + } + } + + #[test] + fn fract_f16_applies_the_mode_and_modifiers_to_the_low_half() { + // s_denorm_mode 4; v_fract_f16_e64 v4,-|v1| mul:2 (gfx1030). + let hlsl = float64::tests::translate( + Stage::Compute, &[0xbfa5_0004, 0xd5df_0104, 0x2800_0101], + ).unwrap(); + assert!(hlsl.contains("v4 & 0xffff0000u")); + assert!(hlsl.contains("tb_fp_mode, 4u), tb_fp_mode, 2.0, false)")); + // An unwritten v6 supplies the high half through the entry ABI. + let first_write = float64::tests::translate(Stage::Compute, &[0x7e0c_bf04]).unwrap(); + assert!(first_write.lines().next().unwrap().split_whitespace().any(|word| word == "v6")); + } + + #[test] + fn fract_f32_uses_the_guest_denormal_mode() { + // gfx1030: v_fract_f32 v8, v4, optionally preceded by s_denorm_mode 3. + let fract = 0x7e10_4104; + for (code, mode) in [(vec![fract], "0u"), (vec![0xbfa5_0003, fract], "tb_fp_mode")] { + let hlsl = float64::tests::translate(Stage::Compute, &code).unwrap(); + assert!(hlsl.contains(&format!("tb_fract_f32(asfloat(v4), {mode})"))); + assert!(hlsl.contains("float tb_fract_f32(")); + } + } + + #[test] + fn conversion_overflow_bit_can_be_set_cleared_and_read() { + // MODE[23] is FP16_OVFL. Reads including reserved bits remain unsupported. + let get = 0xb91a_05c1; + let hlsl = float64::tests::translate(Stage::Compute, &[ + 0xba80_05c1, 1, get, 0xba80_05c1, 0, get, + ]).unwrap(); + assert!(hlsl.contains("((tb_fp_mode >> 23) & 0x1u)")); + assert!(hlsl.contains("((0x1u & 0x1u) << 23)") && hlsl.contains("((0x0u & 0x1u) << 23)")); + assert!(float64::tests::translate(Stage::Compute, &[get | (1 << 11)]).is_err()); + } + + #[test] + fn single_to_half_reads_the_old_destination_only_for_partial_writes() { + // v_cvt_f16_f32 v6,v1 and SDWA with DWORD source. + for (words, preserves) in [ + (vec![0x7e0c_1501], true), + (vec![0x7e0c_14f9, 0x0006_1501], true), // WORD_1, PRESERVE + (vec![0x7e0c_14f9, 0x0006_0501], false), // WORD_1, PAD + (vec![0x7e0c_14f9, 0x0006_1601], false), // DWORD + ] { + let hlsl = float64::tests::translate(Stage::Compute, &words).unwrap(); + let incoming = hlsl.lines().next().unwrap().split_whitespace().any(|word| word == "v6"); + assert_eq!(incoming, preserves); + } + } + + #[test] + fn reads_all_mode_fields_through_ieee() { + // s_getreg_b32 s26, hwreg(MODE, shift, width). + for shift in 0..10 { + for width in 1..=10 - shift { + let get = 0xb91a_0001 | (shift << 6) | ((width - 1) << 11); + let hlsl = float64::tests::translate(Stage::Compute, &[get]).unwrap(); + let mask = (1u32 << width) - 1; + assert!(hlsl.contains(&format!("((tb_fp_mode >> {shift}) & {mask:#x}u)"))); + } + } + // LOD_CLAMPED (bit 10) is updated by texture instructions. + for get in [0xb91a_0281, 0xb91a_0a41] { + assert!(float64::tests::translate(Stage::Compute, &[get]).is_err()); + } + } + + #[test] + fn wide_mode_writes_update_readable_bits() { + // Write MODE[9:0] from s5, overwrite MODE[10:6] with 9, read bit 8. + let hlsl = float64::tests::translate(Stage::Compute, + &[0xb985_4801, 0xba80_2181, 9, 0xb91a_0201]).unwrap(); + assert!(hlsl.lines().next().unwrap().split_whitespace().any(|reg| reg == "s5")); + assert!(hlsl.contains("((s5 & 0x3ffu) << 0)")); + assert!(hlsl.contains("((0x9u & 0xfu) << 6)")); + // The immediate form's encoding has a zero in the SGPR field, but + // leaves the entry value of s0 available to the following v_mov. + let hlsl = float64::tests::translate(Stage::Compute, + &[0xba80_2181, 9, 0x7e08_0200]).unwrap(); + assert!(hlsl.lines().next().unwrap().split_whitespace().any(|reg| reg == "s0")); + } + + #[test] + fn sdwa_f32_applies_modifiers_before_preserving_unselected_bits() { + use super::float64::tests::translate; + // gfx1030: v_add_f32_sdwa v4, -|v1|, v2 clamp mul:2 dst_sel:WORD_1 + // dst_unused:UNUSED_PRESERVE src0_sel:DWORD src1_sel:DWORD + let hlsl = translate(Stage::Compute, &[0x0608_04f9, 0x0636_7501]).unwrap(); + assert!(hlsl.contains("saturate((((-abs(asfloat(v1))) + asfloat(v2)) * 2.0))"), "{hlsl}"); + assert!(hlsl.contains("(v4) & 0xffffu"), "{hlsl}"); + } + + #[test] + fn sdwa_f32_scales_a_full_word_without_source_modifiers() { + use super::float64::tests::translate; + // gfx1030: v_mul_f32_sdwa v4, v1, v2 div:2 (all selectors DWORD). + let hlsl = translate(Stage::Compute, &[0x1008_04f9, 0x0606_d601]).unwrap(); + assert!(hlsl.contains("v4 = asuint(((asfloat(v1) * asfloat(v2)) * 0.5))"), "{hlsl}"); + } + + #[test] + fn sdwa_f32_rounding_applies_input_and_output_modifiers() { + use super::float64::tests::translate; + // gfx1030: v__f32_sdwa v4, -|v1| mul:2, both selectors DWORD. + for (opcode, intrinsic) in [ + (0x7e08_40f9, "tb_fract_f32"), (0x7e08_42f9, "trunc"), (0x7e08_44f9, "ceil"), + (0x7e08_46f9, "round"), (0x7e08_48f9, "floor"), + ] { + let hlsl = translate(Stage::Compute, &[opcode, 0x0036_5601]).unwrap(); + let mode = if intrinsic == "tb_fract_f32" { ", 0u" } else { "" }; + let result = format!("asuint((({intrinsic}((-abs(asfloat(v1))){mode})) * 2.0))"); + assert!(hlsl.contains(&result), "{hlsl}"); + } + } + + #[test] + fn sdwa_integer_to_float_has_float_output_and_integer_input_modifiers() { + use super::float64::tests::translate; + // gfx1030: signed/unsigned dword, signed nibble offset, then unsigned bytes 0..3. + // Each writes v4 from v1 with clamp mul:4 and both selectors DWORD. + let sdwa = 0x0006_b601; + for opcode in [0x7e08_0af9, 0x7e08_0cf9, 0x7e08_1cf9, 0x7e08_22f9, + 0x7e08_24f9, 0x7e08_26f9, 0x7e08_28f9] { + let hlsl = translate(Stage::Compute, &[opcode, sdwa]).unwrap(); + assert!(hlsl.lines().any(|line| line.contains("v4 = asuint(saturate(") + && line.ends_with(" * 4.0)));")), "{hlsl}"); + // SRC0_NEG is invalid for an integer input. + let error = translate(Stage::Compute, &[opcode, sdwa | (1 << 20)]).unwrap_err(); + assert!(error.contains("unsupported SDWA neg/abs"), "{error}"); + } + } + + #[test] + fn widen_f16_reads_a_half_precision_source_before_applying_modifiers() { + use super::float64::tests::translate; + // gfx1030: v_cvt_f32_f16_e32 v4, 1/(2*pi) (inline selector 248). + let hlsl = translate(Stage::Compute, &[0x7e08_16f8]).unwrap(); + assert!(hlsl.contains("asfloat(0x3e230000u)"), "{hlsl}"); + // v_cvt_f32_f16_sdwa v4, -|v1| clamp mul:2 dst_sel:DWORD src0_sel:WORD_1 + let hlsl = translate(Stage::Compute, &[0x7e08_16f9, 0x0035_7601]).unwrap(); + assert!(hlsl.contains("((v1 >> 16) & 0xffffu)"), "{hlsl}"); + assert!(hlsl.contains("saturate((((-abs(f16tof32("), "{hlsl}"); + } + fn dpp16_word(src0_reg: u32, ctrl: u32, fi: u32, bc: u32, bank_m: u32, row_m: u32) -> u32 { // [src0_reg:8][ctrl:9][fi:1][bc:1][bank_m:4][row_m:4] src0_reg | (ctrl << 8) | (fi << 18) | (bc << 19) | (bank_m << 24) | (row_m << 28) @@ -9702,12 +10543,15 @@ mod tests { } #[test] - fn dpp16_row_mirror_fi0_is_accepted_as_row_mirror_move() { - let mut insns = vec![dpp16_move_insn(dpp16_word(2, 0x140, 0, 1, 0xf, 0xf))]; - lower_wave_reductions(&mut insns).expect("row_mirror accepted"); - assert_eq!(insns[0].op, OP_ROW_MIRROR); - assert_eq!(insns[0].src, vec![Opnd::Vgpr(2)]); - assert_eq!(insns[0].aux.imm, 0); + fn dpp16_row_moves_select_the_source_lane_by_xor() { + let mirrors = [(0x141, 7), (0x140, 15)]; + for (ctrl, mask) in mirrors.into_iter().chain((0..16).map(|mask| (0x160 + mask, mask))) { + let mut insns = [dpp16_move_insn(dpp16_word(2, ctrl, 0, 1, 0xf, 0xf))]; + lower_wave_reductions(&mut insns).unwrap(); + assert_eq!(insns[0].op, OP_ROW_XOR_MOVE); + assert_eq!(insns[0].src, [Opnd::Vgpr(2)]); + assert_eq!(insns[0].aux.imm, i64::from(mask)); + } } #[test] @@ -9719,18 +10563,10 @@ mod tests { assert_eq!(insns[0].aux.imm, 0); } - #[test] - fn dpp16_row_mirror_with_fi1_is_refused() { - // row_mirror with FI=1 reads the pre-existing value; not the accepted shape. - let mut insns = vec![dpp16_move_insn(dpp16_word(2, 0x140, 1, 1, 0xf, 0xf))]; - let err = lower_wave_reductions(&mut insns).expect_err("refused"); - assert!(err.contains("unsupported DPP16 move")); - } - #[test] fn dpp16_unimplemented_control_is_refused() { - // row_half_mirror, and quad_perm with a negation modifier. - let mut insns = vec![dpp16_move_insn(dpp16_word(2, 0x141, 0, 1, 0xf, 0xf))]; + // Zero is outside the row_ror range. Quad moves with negation are also unsupported. + let mut insns = vec![dpp16_move_insn(dpp16_word(2, 0x120, 0, 1, 0xf, 0xf))]; assert!(lower_wave_reductions(&mut insns).is_err()); let mut insns = vec![dpp16_move_insn(dpp16_word(2, 0x0, 1, 1, 0xf, 0xf) | (1u32 << 20))]; assert!(lower_wave_reductions(&mut insns).is_err()); @@ -10201,6 +11037,36 @@ mod election_order_regression { fn op(name: &str, enc: Enc, dst: Vec, src: Vec, offset: usize) -> Insn { Insn { offset, dwords: 1, enc, op: 0, raw: vec![0], mnemonic: name.into(), dst, src, aux: Default::default() } } + #[test] + fn election_ignores_independent_single_word_moves() { + let mut ops = vec![ + op("v_mbcnt_lo_u32_b32", Enc::Vop3, vec![Opnd::Vgpr(2)], vec![Opnd::ConstInt(-1), Opnd::ConstInt(0)], 0), + op("s_ff1_i32_b32", Enc::Sop1, vec![Opnd::Sgpr(7)], vec![Opnd::ExecLo], 4), + op("s_mov_b32", Enc::Sop1, vec![Opnd::Sgpr(8)], vec![Opnd::Sgpr(6)], 8), + op("v_cmp_eq_u32", Enc::Vop3, vec![Opnd::VccLo], vec![Opnd::Vgpr(2), Opnd::Sgpr(7)], 12), + ]; + assert!(verify_lane_election(&mut ops, 1, true).is_ok()); + ops[2].mnemonic = "s_mov_b64".into(); // s[6:7] reads the elected lane. + assert!(verify_lane_election(&mut ops, 1, true).is_err()); + ops[2].mnemonic = "s_mov_b32".into(); + ops[2].dst = vec![Opnd::Sgpr(7)]; + assert!(verify_lane_election(&mut ops, 1, true).is_err()); + } + + #[test] + fn later_saveexec_uses_the_redefined_vcc() { + let mut ops = vec![ + op("v_mbcnt_lo_u32_b32", Enc::Vop3, vec![Opnd::Vgpr(2)], vec![Opnd::ConstInt(-1), Opnd::ConstInt(0)], 0), + op("s_ff1_i32_b32", Enc::Sop1, vec![Opnd::Sgpr(7)], vec![Opnd::ExecLo], 4), + op("v_cmp_eq_u32", Enc::Vopc, vec![Opnd::VccLo], vec![Opnd::Sgpr(7), Opnd::Vgpr(2)], 8), + op("v_cmp_eq_u32", Enc::Vopc, vec![Opnd::VccLo], vec![Opnd::ConstInt(0), Opnd::Vgpr(4)], 12), + op("s_and_saveexec_b32", Enc::Sop1, vec![Opnd::Sgpr(20)], vec![Opnd::VccLo], 16), + ]; + assert!(verify_lane_election(&mut ops, 1, true).is_ok()); + ops.remove(3); + assert!(verify_lane_election(&mut ops, 1, true).is_err()); + } + #[test] fn symmetric_equality_still_requires_full_lane_count() { let mut ops = vec![ @@ -10208,14 +11074,14 @@ mod election_order_regression { op("s_ff1_i32_b32", Enc::Sop1, vec![Opnd::Sgpr(7)], vec![Opnd::ExecLo], 4), op("v_cmp_eq_u32", Enc::Vop3, vec![Opnd::VccLo], vec![Opnd::Vgpr(2), Opnd::Sgpr(7)], 8), ]; - assert!(verify_lane_election(&mut ops, 1).is_ok()); + assert!(verify_lane_election(&mut ops, 1, true).is_ok()); ops[2].src.swap(0, 1); - assert!(verify_lane_election(&mut ops, 1).is_ok()); + assert!(verify_lane_election(&mut ops, 1, true).is_ok()); ops[2].mnemonic = "v_cmp_ne_u32".into(); - assert!(verify_lane_election(&mut ops, 1).is_err()); + assert!(verify_lane_election(&mut ops, 1, true).is_err()); ops[2].mnemonic = "v_cmp_eq_u32".into(); ops[0].src[0] = Opnd::ConstInt(0); - assert!(verify_lane_election(&mut ops, 1).is_err()); + assert!(verify_lane_election(&mut ops, 1, true).is_err()); } } diff --git a/tools/shader-compiler/src/hlsl/compare.rs b/tools/shader-compiler/src/hlsl/compare.rs index 9e56dfa7..c76915b3 100644 --- a/tools/shader-compiler/src/hlsl/compare.rs +++ b/tools/shader-compiler/src/hlsl/compare.rs @@ -25,11 +25,11 @@ bool tb_class_f64(uint2 bits, uint mask) { } "#; -fn sign_modifiers(mut bits: String, sign: u32, mask: u8, source: u8) -> String { - if mask & (1 << source) != 0 { +pub(super) fn sign_modifiers(mut bits: String, sign: u32, absolute: bool, negate: bool) -> String { + if absolute { bits = format!("({bits} & {:#x}u)", sign - 1); } - if mask & (8 << source) != 0 { + if negate { bits = format!("({bits} ^ {sign:#x}u)"); } bits @@ -58,7 +58,7 @@ impl Emitter<'_> { format!("{:#x}u", bits >> 32), )); } - Ok((r(operand)?, self.pair_high(operand)?)) + Ok((self.numeric_input(operand)?, self.pair_high(operand)?)) } pub(super) fn compare_float(&mut self, ins: &Insn, mask: u8) -> Result { @@ -78,7 +78,7 @@ impl Emitter<'_> { } else { ("0u".into(), r(operand)?) }; - let high = sign_modifiers(high, sign, mask, i as u8); + let high = sign_modifiers(high, sign, mask & (1 << i) != 0, mask & (8 << i) != 0); Ok(format!("uint2({low}, {high})")) }; let a = source(0)?; diff --git a/tools/shader-compiler/src/hlsl/exec_group.rs b/tools/shader-compiler/src/hlsl/exec_group.rs index 52429d47..0f0b8cdd 100644 --- a/tools/shader-compiler/src/hlsl/exec_group.rs +++ b/tools/shader-compiler/src/hlsl/exec_group.rs @@ -146,6 +146,555 @@ mod tests { } } + #[test] + fn quad_subtractions_permute_only_the_first_operand() { + // gfx1030 quad_perm:[1,0,3,2], full row and bank masks. + for (op, expression) in [(0x4c08_04fa, "q0 - v2"), (0x4e08_04fa, "v2 - q0")] { + for control in [0xff00_b101, 0xff04_b101, 0xff08_b101, 0xff0c_b101] { + let ex = compute_extract(&[op, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("WaveReadLaneAt("), "{hlsl}"); + let write = if control == 0xff00_b101 { + format!("v4 = q0active ? ({expression}) : v4;") + } else { + format!("v4 = {expression};") + }; + assert!(hlsl.contains(&write), "{hlsl}"); + } + } + } + + #[test] + fn quad_shifts_take_the_count_from_the_selected_lane() { + // gfx1030 quad_perm:[1,0,3,2], full row and bank masks. + for (opcode, value) in [ + (0x3408_04fa, "v2 << (q0 & 31u)"), + (0x2c08_04fa, "v2 >> (q0 & 31u)"), + (0x3008_04fa, "asuint(asint(v2) >> (q0 & 31u))"), + ] { + for control in [0xff00_b101, 0xff04_b101, 0xff08_b101, 0xff0c_b101] { + let shader = compute_extract(&[opcode, control, 0xbf81_0000]); + let hlsl = super::super::translate(&shader).unwrap().hlsl; + let expected = if control == 0xff00_b101 { + format!("v4 = q0active ? ({value}) : v4;") + } else { + format!("v4 = {value};") + }; + assert!(hlsl.contains("WaveReadLaneAt(") && hlsl.contains(&expected), "{hlsl}"); + } + } + } + + #[test] + fn quad_min_max_compare_the_peer_with_the_local_operand() { + for (opcode, result) in [ + (0x2208_04fa, "asuint(min(asint(q0), asint(v2)))"), + (0x2408_04fa, "asuint(max(asint(q0), asint(v2)))"), + (0x2608_04fa, "min(q0, v2)"), + (0x2808_04fa, "max(q0, v2)"), + ] { + let shader = compute_extract(&[opcode, 0xff0c_b101, 0xbf81_0000]); + let hlsl = super::super::translate(&shader).unwrap().hlsl; + assert!(hlsl.contains("WaveReadLaneAt(v1,") && hlsl.contains(&format!("v4 = {result};")), "{hlsl}"); + } + } + + #[test] + fn quad_mul24_uses_the_same_product_as_an_ordinary_multiply() { + for opcode in [0x1208_04fa, 0x1408_04fa, 0x1608_04fa, 0x1808_04fa] { + let plain = compute_extract(&[(opcode & !0x1ff) | 0x101, 0xbf81_0000]); + let plain_hlsl = super::super::translate(&plain).unwrap().hlsl; + let expression = plain_hlsl.lines() + .filter_map(|line| line.split_once("v4 = ").map(|(_, rhs)| rhs)) + .find(|rhs| rhs.contains("v1") && rhs.contains("v2")) + .unwrap_or_else(|| panic!("missing multiply in {plain_hlsl}")) + .replace("v1", "q0"); + let quad = compute_extract(&[opcode, 0xff0c_b101, 0xbf81_0000]); + let hlsl = super::super::translate(&quad).unwrap().hlsl; + assert!(hlsl.contains("WaveReadLaneAt(v1,") && hlsl.contains(&format!("v4 = {expression}")), "{hlsl}"); + } + } + + #[test] + fn quad_integer_operations_permute_only_the_first_operand() { + // gfx1030 quad_perm:[1,0,3,2], full row and bank masks. + for (op, expression) in [ + (0x4a08_04fa, "q0 + v2"), + (0x4c08_04fa, "q0 - v2"), + (0x4e08_04fa, "v2 - q0"), + (0x3c08_04fa, "~(q0 ^ v2)"), + ] { + for control in [0xff00_b101, 0xff04_b101, 0xff08_b101, 0xff0c_b101] { + let ex = compute_extract(&[op, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("WaveReadLaneAt("), "{hlsl}"); + let write = if control == 0xff00_b101 { + format!("v4 = q0active ? ({expression}) : v4;") + } else { + format!("v4 = {expression};") + }; + assert!(hlsl.contains(&write), "{hlsl}"); + } + } + } + + #[test] + fn quad_cndmask_selects_with_the_destination_lanes_vcc() { + // v_cmp_ne_u32 vcc_lo, 0, v3; v_cndmask_b32_dpp v4, v1, v2. + let quad = 0x0208_04fa; + let compare = 0x7d8a_0680; + for control in [0xff00_b101, 0xff04_b101, 0xff08_b101, 0xff0c_b101] { + let shader = compute_extract(&[compare, quad, control, 0xbf81_0000]); + let hlsl = super::super::translate(&shader).unwrap().hlsl; + assert!(hlsl.contains("(vcc_lo & 1u) != 0u ? v2 : q1"), "{hlsl}"); + } + // A branch can bypass the compare. A scalar write can also replace + // the per-lane predicate with a full wave mask. + for prefix in [vec![0xbf84_0001, compare], vec![compare, 0xbeea_0381]] { + let mut words = prefix; + words.extend([quad, 0xff0c_b101, 0xbf81_0000]); + let err = super::super::translate(&compute_extract(&words)).err().expect("unproven VCC accepted"); + assert!(err.contains("requires a known per-lane VCC predicate"), "{err}"); + } + // After a scalar mask, a new compare establishes a fresh lane predicate. + let words = [0xbeea_0381, compare, quad, 0xff0c_b101, quad, 0xff0c_b101, 0xbf81_0000]; + let hlsl = super::super::translate(&compute_extract(&words)).unwrap().hlsl; + assert_eq!(hlsl.matches("(vcc_lo & 1u) != 0u ? v2 : q").count(), 2); + } + + #[test] + fn quad_fp32_arithmetic_keeps_operand_order_and_inactive_destinations() { + for (op, expression) in [ + (0x0608_04fa, "asuint(asfloat(q0) + asfloat(v2))"), + (0x0808_04fa, "asuint(asfloat(q0) - asfloat(v2))"), + (0x0a08_04fa, "asuint(asfloat(v2) - asfloat(q0))"), + (0x1008_04fa, "asuint(asfloat(q0) * asfloat(v2))"), + (0x0e08_04fa, "asuint(tb_mull(asfloat(q0), asfloat(v2)))"), + (0x1e08_04fa, "tb_quad_extrema(q0, v2, false, 0xc0u)"), + (0x2008_04fa, "tb_quad_extrema(q0, v2, true, 0xc0u)"), + (0x5e08_04fa, "(tb_f16_rtz(asfloat(q0)) | (tb_f16_rtz(asfloat(v2)) << 16))"), + ] { + for control in [0xff00_b101, 0xff04_b101, 0xff08_b101, 0xff0c_b101] { + let shader = compute_extract(&[op, control, 0xbf81_0000]); + let hlsl = super::super::translate(&shader).unwrap().hlsl; + let value = if control == 0xff00_b101 { + format!("q0active ? ({expression}) : v4") + } else { + expression.to_owned() + }; + assert!(hlsl.contains("WaveReadLaneAt(") && hlsl.contains(&format!("v4 = {value};")), "{hlsl}"); + } + } + } + + #[test] + fn extrema_quad_can_start_a_saved_exec_reduction_or_stand_alone() { + // Save EXEC, materialize +infinity, then select the input for active lanes. + let prologue = [0xbe94_2980, 0x7e0c_02ff, 0x7f80_0000, 0xd501_0004, 0x0052_0306]; + let quad = [0x1e08_08fa, 0xff04_b104]; + let mut words = prologue.to_vec(); + words.extend(quad); + words.extend([0xd760_0017, 0x0001_0104, 0xbefe_0414, 0xbf81_0000]); + let mut insns = crate::rdna2::disassemble(&compute_extract(&words).isa); + super::super::lower_wave_reductions(&mut insns).unwrap(); + assert!(insns.iter().any(super::super::is_quad_exchange)); + + words.truncate(prologue.len() + quad.len()); + // Fold the remaining pairs, octets, rows and the other half-wave. + words.extend([0x1e08_08fa, 0xff04_4e04, 0x1e08_08fa, 0xff05_2404, + 0x1e08_08fa, 0xff05_2804, 0xd778_0005, 0x0201_0104, 0x1e08_0905, + 0xd760_0016, 0x0001_4104, 0x1e08_0816, 0xd760_0017, 0x0001_0104, + 0xbefe_0414, 0xbf81_0000]); + let hlsl = super::super::translate(&compute_extract(&words)).unwrap().hlsl; + assert!(hlsl.contains("tb_swizzle[(tb_lane & ~63u) | (0x20u & 63u)]"), "{hlsl}"); + assert!(hlsl.contains("tb_swizzle[(tb_lane & ~63u) | (0x0u & 63u)]"), "{hlsl}"); + assert!(!hlsl.contains("WaveActiveMin("), "{hlsl}"); + // Rotating right four lanes reads from the previous quartet. + assert!(hlsl.contains("lane - 4u) & 15u)"), "{hlsl}"); + // Only selected destination rows and banks consume the rotated value. + let mut masked = words.clone(); + masked[prologue.len() + 5] = 0xa505_2404; + let hlsl = super::super::translate(&compute_extract(&masked)).unwrap().hlsl; + assert!(hlsl.contains("0xau >> ((tb_lane >> 4u) & 3u)"), "{hlsl}"); + assert!(hlsl.contains("0x5u >> ((tb_lane >> 2u) & 3u)"), "{hlsl}"); + // The same two broadcasts end a tree that starts with DPP8 exchanges. + words.splice(prologue.len()..prologue.len() + 8, [ + 0x1e08_08e9, 0xde54_c104, 0x1e08_08e9, 0xb3e2_1a04, + 0x1e08_08e9, 0x688f_ac04, 0x1e08_08fa, 0xff05_4004]); + let hlsl = super::super::translate(&compute_extract(&words)).unwrap().hlsl; + assert!(hlsl.contains("tb_swizzle[(tb_lane & ~63u) | (0x20u & 63u)]"), "{hlsl}"); + assert!(!hlsl.contains("WaveActiveMin("), "{hlsl}"); + // A branch skipping NAND_SAVEEXEC could leave the DPP8 source inactive. + words.insert(0, 0xbf85_0005); + let error = super::super::translate(&compute_extract(&words)).err().unwrap(); + assert!(error.contains("branch enters a saved-EXEC extrema exchange"), "{error}"); + } + + #[test] + fn quad_fp32_arithmetic_modifies_each_input_before_combining() { + // DPP16 quad_perm:[1,0,3,2], with negative absolute source 0 + // and negated source 1. FI=BC=0 preserves the previous destination. + let peer = "asfloat(((q0 & 0x7fffffffu) ^ 0x80000000u))"; + let local = "asfloat((v2 ^ 0x80000000u))"; + for (opcode, arithmetic) in [ + (0x0608_04fa, format!("{peer} + {local}")), + (0x0808_04fa, format!("{peer} - {local}")), + (0x0a08_04fa, format!("{local} - {peer}")), + (0x1008_04fa, format!("{peer} * {local}")), + (0x0e08_04fa, format!("tb_mull({peer}, {local})")), + ] { + let shader = compute_extract(&[opcode, 0xff70_b101, 0xbf81_0000]); + let hlsl = super::super::translate(&shader).unwrap().hlsl; + assert!(hlsl.contains(&format!("v4 = q0active ? (asuint({arithmetic})) : v4;")), "{hlsl}"); + } + } + + #[test] + fn quad_pack_applies_source_signs_before_rounding_each_half() { + // v_cvt_pkrtz_f16_f32 v4, -|v1|, |v2| quad_perm:[1,0,3,2] fi:1 + let shader = compute_extract(&[0x5e08_04fa, 0xffb4_b101, 0xbf81_0000]); + let hlsl = super::super::translate(&shader).unwrap().hlsl; + let low = "tb_f16_rtz(asfloat(((q0 & 0x7fffffffu) ^ 0x80000000u)))"; + let high = "tb_f16_rtz(asfloat((v2 & 0x7fffffffu)))"; + assert!(hlsl.contains(&format!("v4 = ({low} | ({high} << 16));")), "{hlsl}"); + } + + #[test] + fn dpp16_extrema_apply_each_source_sign_after_selecting_its_lane() { + // v_max_f32 v4, |v8|, -v2 quad_perm:[1,0,3,2] fi:1 + let shader = compute_extract(&[0x2008_04fa, 0xff64_b108, 0xbf81_0000]); + let hlsl = super::super::translate(&shader).unwrap().hlsl; + assert!(hlsl.contains("tb_quad_extrema((q0 & 0x7fffffffu), (v2 ^ 0x80000000u), true"), "{hlsl}"); + } + + #[test] + fn masked_quad_bitwise_writes_only_to_selected_compute_lanes() { + for (op, symbol) in [(0x3808_04fa, "|"), (0x3a08_04fa, "^")] { + let mut shader = compute_extract(&[op, 0x2500_b101, 0xbf81_0000]); + shader.isa_preamble = [0, 4, 4, 2]; + let hlsl = super::super::translate(&shader).unwrap().hlsl; + assert!(hlsl.contains("gtid.x + 4u * (gtid.y + 4u * gtid.z)"), "{hlsl}"); + assert!(hlsl.contains("0x2u >> ((tb_lane >> 4u) & 1u)"), "{hlsl}"); + assert!(hlsl.contains("0x5u >> ((tb_lane >> 2u) & 3u)"), "{hlsl}"); + assert!(hlsl.contains(&format!("&& q0active ? (q0 {symbol} v2) : v4")), "{hlsl}"); + + shader.isa_preamble = [0, 64, 1, 1]; + let error = super::super::translate(&shader).err().unwrap(); + assert!(error.contains("known guest wave width"), "{error}"); + } + } + + #[test] + fn asymmetric_row_masks_require_a_logical_lane_number() { + // An identity select, a masked row rotation and the EXEC restore. + let words = [0xbe94_2980, 0x7e0c_02ff, 0x7f80_0000, 0xd501_0004, 0x0052_0306, + 0x1e08_08fa, 0x8f05_2404, 0xbefe_0414, 0xbf81_0000]; + let mut ex = compute_extract(&words); + ex.isa_preamble = [0, 8, 4, 1]; + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("uint tb_lane = gtid.x + 8u * (gtid.y + 4u * gtid.z)"), "{hlsl}"); + ex.isa_preamble = [0, 8, 8, 1]; + let error = super::super::translate(&ex).err().unwrap(); + assert!(error.contains("known guest wave width"), "{error}"); + } + + #[test] + fn signed_quad_extrema_preserve_both_lane_reads() { + // A single quad maximum of two negative absolute values precedes reads + // from lanes 32 and 0. Other quads cannot contribute to either result. + let shader = compute_extract(&[ + 0xbe94_2980, 0x7e0c_02ff, 0x7f80_0000, 0xd501_0004, 0x0052_0906, + 0x2008_04fa, 0xfff8_9301, 0xd760_0016, 0x0001_4104, 0xd760_0017, + 0x0001_0104, 0xbefe_0414, 0xbf81_0000, + ]); + let hlsl = super::super::translate(&shader).unwrap().hlsl; + assert!(hlsl.contains("tb_swizzle[(tb_lane & ~63u) | (0x20u & 63u)]"), "{hlsl}"); + assert!(hlsl.contains("tb_swizzle[(tb_lane & ~63u) | (0x0u & 63u)]"), "{hlsl}"); + assert!(!hlsl.contains("WaveActiveMax("), "{hlsl}"); + } + + #[test] + fn dpp_row_moves_mask_the_source_value_before_the_lane_read() { + // gfx1030: v_mov_b32_dpp v4, v1 with row_mirror, row_half_mirror, or row_xmask:3. + for (control, mask) in [(0xff09_4001, 15), (0xff09_4101, 7), (0xff09_6301, 3)] { + let ex = compute_extract(&[0x7e08_02fa, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains(&format!("WaveGetLaneIndex() ^ {mask}u")), "{hlsl}"); + assert!(hlsl.contains("WaveReadLaneAt((exec_lo & 1u) != 0u ? v1 : 0u,"), "{hlsl}"); + } + } + + #[test] + fn dpp_row_share_reads_a_fixed_lane_in_each_row() { + // gfx1030: v_mov_b32_dpp v4, v1 row_share:N, FI=0 and BC=1. + for lane in 0..16 { + let control = 0xff09_5001 | (lane << 8); + let ex = compute_extract(&[0x7e08_02fa, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains(&format!("(WaveGetLaneIndex() & ~15u) | {lane}u")), "{hlsl}"); + assert!(hlsl.contains("WaveReadLaneAt((exec_lo & 1u) != 0u ? v1 : 0u,"), "{hlsl}"); + } + } + + #[test] + fn dpp_row_moves_fetch_preexisting_values_when_fi_is_set() { + for op in [0x140, 0x141, 0x150, 0x167] { + for bound in [0, 1] { + let control = 0xff04_0001 | (op << 8) | (bound << 19); + let ex = compute_extract(&[0x7e08_02fa, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("WaveReadLaneAt(v1, q0src)"), "{hlsl}"); + } + } + } + + #[test] + fn dpp_row_moves_keep_the_destination_when_the_source_is_inactive_by_default() { + for control in [0xff01_4001, 0xff01_4101, 0xff01_5001, 0xff01_6701] { + let ex = compute_extract(&[0x7e08_02fa, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("WaveReadLaneAt(uint2(v1, exec_lo & 1u), q0src)"), "{hlsl}"); + assert!(hlsl.contains("q0pair.y != 0u ? q0pair.x : v4"), "{hlsl}"); + } + } + + #[test] + fn dpp_row_ror_wraps_the_source_index_within_its_row() { + // gfx1030: v_mov_b32_dpp v4, v1 row_ror:N, FI=0 and BC=0. + for distance in 1..16 { + let control = 0xff01_2001 | (distance << 8); + let ex = compute_extract(&[0x7e08_02fa, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + let lane = format!("(WaveGetLaneIndex() & ~15u) | ((WaveGetLaneIndex() - {distance}u) & 15u)"); + assert!(hlsl.contains(&lane), "{hlsl}"); + } + } + + #[test] + fn dpp_row_shifts_apply_bound_control_outside_each_row() { + for (control, offset, fallback) in [ + (0xff01_0101, "+ 1u", "v4"), + (0xff09_0f01, "+ 15u", "0u"), + (0xff0d_1101, "- 1u", "0u"), + (0xff05_1f01, "- 15u", "v4"), + ] { + let ex = compute_extract(&[0x7e08_02fa, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains(&format!("(WaveGetLaneIndex() & 15u) {offset}")), "{hlsl}"); + assert!(hlsl.contains(&format!("if (q0offset >= 16u) q0 = {fallback};")), "{hlsl}"); + } + } + + #[test] + fn dpp_masks_select_destinations_after_the_lane_read() { + // Row mask 5, bank mask 9: read v1 even from a masked bank, then update v4. + for control in [0x5909_4001, 0x590c_1b01] { // row_mirror, quad_perm:[3,2,1,0] + let ex = compute_extract(&[0x7e08_02fa, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + let (_, write) = hlsl.split_once("WaveReadLaneAt(").unwrap(); + assert!(write.contains("0x5u >> (WaveGetLaneIndex() >> 4u)"), "{hlsl}"); + assert!(write.contains("0x9u >> ((WaveGetLaneIndex() >> 2u) & 3u)"), "{hlsl}"); + assert!(write.contains("? q0 : v4;"), "{hlsl}"); + } + } + + #[test] + fn asymmetric_row_mask_requires_a_known_guest_width_for_large_groups() { + let mov = [0x7e08_02fa, 0x1f09_4001, 0xbf81_0000]; + let mut ex = compute_extract(&mov); + assert!(matches!(super::super::translate(&ex), Err(msg) if msg.contains("guest wave width"))); + ex.psv_threads = Some([32, 1, 1]); + assert!(super::super::translate(&ex).is_ok()); + + // v_cmp_gt_u32 s3,v0,v1 establishes a single-word comparison result (wave32). + let words = [&[0xd4c4_0003, 0x0202_0300][..], &mov].concat(); + assert!(super::super::translate(&compute_extract(&words)).is_ok()); + } + + #[test] + fn quad_move_with_fi_clear_obeys_bound_control_for_inactive_sources() { + // v_mov_b32_dpp v4, v1 quad_perm:[1,2,3,0], with each BOUND_CTRL setting. + for (control, read) in [ + (0xff00_3901, "WaveReadLaneAt(uint2(v1, exec_lo & 1u), q0src)"), + (0xff08_3901, "WaveReadLaneAt((exec_lo & 1u) != 0u ? v1 : 0u, q0src)"), + ] { + let ex = compute_extract(&[0x7e08_02fa, control, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains(read), "{hlsl}"); + if control == 0xff00_3901 { + assert!(hlsl.contains("q0pair.y != 0u ? q0pair.x : v4"), "{hlsl}"); + } + } + } + + #[test] + fn first_active_election_uses_the_guest_wave_boundary() { + // Full lane index, FF1 of EXEC, independent adjacent move, equality comparison. + let mut ex = compute_extract(&[0xd765_0006, 0x0001_00c1, 0xd766_0006, 0x0002_0cc1, + 0xbe98_147e, 0xbe99_0387, 0x7d84_0c18, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("InterlockedMin(") && hlsl.contains("tb_lane & 63u"), "{hlsl}"); + ex.isa_preamble = [0, 8, 4, 1]; + let translated = super::super::translate(&ex).unwrap(); + assert_eq!(translated.required_wave_size, Some(32)); + assert!(translated.hlsl.contains("WaveActiveMin(") && !translated.hlsl.contains("InterlockedMin(")); + } + + #[test] + fn first_active_lane_survives_restoring_the_predicate() { + // CMP, SAVEEXEC, FF1, restore, broadcast the saved index. + let mut words = [0x7d86_00a3, 0xbe94_246a, 0xbe98_147e, 0xbefe_0414, 0x7e08_0218, 0xbf81_0000]; + let ex = compute_extract(&words); + let shader = super::super::translate(&ex).unwrap(); + assert!(shader.hlsl.contains("InterlockedMin(")); + words[4] = 0x7e08_0214; // exposing the saved mask as scalar data requires a ballot + let scalar_mask = super::super::translate(&compute_extract(&words)).unwrap(); + assert!(scalar_mask.hlsl.contains("tb_page_ballot(tb_lane,") && scalar_mask.hlsl.contains("saved_exec1.x")); + words[4] = 0x7e08_0218; + words[3] = 0xbefe_0416; // restore from s[22:23] instead of the saved s[20:21] + assert!(super::super::translate(&compute_extract(&words)).is_err()); + words[3] = 0xbefe_0414; + words[2] = 0xbe95_147e; // FF1 clobbers the high half of the saved EXEC. + words[4] = 0x7e08_0215; + assert!(super::super::translate(&compute_extract(&words)).is_err()); + } + + #[test] + fn numeric_inputs_and_lane_predicate_keep_their_distinct_exec_views() { + // Save EXEC. Add its two words, use the saved pair as a lane predicate, + // overwrite the upper word and repeat the same addition. + let mut ex = compute_extract(&[0xbe9c_047e, 0xd525_0004, 0x0000_381d, + 0xd501_0005, 0x0072_0880, 0xbe9d_0391, 0xd525_0004, 0x0000_381d, 0xbf81_0000]); + ex.isa_preamble = [0, 21, 1, 1]; + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("(saved_exec0.y + saved_exec0.x)"), "{hlsl}"); + assert!(hlsl.contains("((s28 & 1u) != 0u)"), "{hlsl}"); + assert!(hlsl.contains("(s29 + saved_exec0.x)"), "{hlsl}"); + assert_eq!(hlsl.matches("WaveActiveBallot(").count(), 1); + } + + #[test] + fn vector_comparisons_read_the_saved_word_before_overwriting_the_mask() { + // Save EXEC, compare a signed VGPR against its low word, then write + // an equality predicate to the same pair that holds the saved mask. + let mut ex = compute_extract(&[0xbe9c_047e, 0x7d12_121c, 0xd481_006a, 0x0000_3909, + 0xd4c2_001c, 0x0002_121c, 0xd501_0005, 0x0072_0880, 0xbf81_0000]); + ex.isa_preamble = [0, 21, 1, 1]; + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("(asint(saved_exec0.x << 16) >> 16)"), "{hlsl}"); + assert!(hlsl.contains("(asint(v9) < asint(saved_exec0.x))"), "{hlsl}"); + assert!(hlsl.contains("(saved_exec0.x == v9)"), "{hlsl}"); + assert!(hlsl.contains("((s28 & 1u) != 0u)"), "{hlsl}"); + assert_eq!(hlsl.matches("WaveActiveBallot(").count(), 1); + } + + #[test] + fn pair_comparisons_resolve_each_half_at_its_last_write() { + // Overwrite the first saved pair's low word and the second pair's high + // word. Both comparisons must combine ordinary SGPRs with saved bits. + let mut ex = compute_extract(&[0xbe9c_047e, 0xbe9c_0393, 0xd4a1_006a, 0x0002_141c, + 0xbe9e_047e, 0xbe9f_0391, 0xd4e2_006a, 0x0000_3c1c, 0xbf81_0000]); + ex.isa_preamble = [0, 21, 1, 1]; + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("asint(saved_exec0.y) < asint(v11)"), "{hlsl}"); + assert!(hlsl.contains("saved_exec0.y == v11 && s28 < v10"), "{hlsl}"); + assert!(hlsl.contains("saved_exec0.y == s31 && s28 == saved_exec3.x"), "{hlsl}"); + assert_eq!(hlsl.matches("WaveActiveBallot(").count(), 2); + } + + #[test] + fn restore_uses_the_bits_of_the_reassembled_exec_pair() { + // Swap both halves. A small group's lanes now take their bits from + // the original upper word, which contains no active lanes. + let mut ex = compute_extract(&[0xbe9c_047e, 0xbe9e_031d, 0xbe9f_031c, 0xbefe_041e, + 0x7e08_0281, 0xbf81_0000]); + ex.isa_preamble = [0, 21, 1, 1]; + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("exec_lo = ((saved_exec0.y >> (WaveGetLaneIndex() & 31u)) & 1u)"), "{hlsl}"); + } + + #[test] + fn conditional_select_reads_the_predicate_bit_and_the_full_numeric_operand() { + // Swap the EXEC words and use s30 as both the false value and mask base. + let mut ex = compute_extract(&[0xbe9c_047e, 0xbe9e_031d, 0xbe9f_031c, + 0xd501_0004, 0x007a_121e, 0xbf81_0000]); + ex.isa_preamble = [0, 21, 1, 1]; + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("uint select_mask3 = ((saved_exec0.y >> (WaveGetLaneIndex() & 31u)) & 1u)"), "{hlsl}"); + assert!(hlsl.contains("((select_mask3 & 1u) != 0u) ? v9 : saved_exec0.y"), "{hlsl}"); + } + + #[test] + fn conditional_select_after_election_requires_a_known_saved_mask_pair() { + // Restore EXEC after FF1, keep the saved low word, replace the high word. + let mut words = vec![0x7d86_0087, 0xbe94_246a, 0xbe98_147e, 0xbefe_0414, + 0xbe9e_0414, 0xbe94_0480, 0xbe9f_03ff, 0x8000_0001, 0xd501_0009, + 0x0079_0280, 0x4a08_1218, 0xbf81_0000]; + let hlsl = super::super::translate(&compute_extract(&words)).unwrap().hlsl; + assert!(hlsl.contains("((tb_lane & 32u) == 0u ? saved_lane1 : ((s31 >> (tb_lane & 31u)) & 1u))"), "{hlsl}"); + // Copy the elected lane into the high word. FF1 produces an ordinary + // integer even though its source was the EXEC predicate. + let mut dynamic = words.clone(); + dynamic.splice(6..8, [0xbe9f_0318]); + for group_size in [21, 64] { + let mut ex = compute_extract(&dynamic); + ex.isa_preamble = [0, group_size, 1, 1]; + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("uint select_mask7 = "), "{hlsl}"); + if group_size == 64 { + assert!(hlsl.contains("((s31 >> (tb_lane & 31u)) & 1u)"), "{hlsl}"); + } + } + words.splice(6..8, [0xbe9f_0311]); // copy the unknown s17 instead of the literal + assert!(super::super::translate(&compute_extract(&words)).is_err()); + } + + #[test] + fn aligned_halves_from_different_saves_reuse_each_lanes_predicate() { + let ex = compute_extract(&[0xd765_0006, 0x0001_00c1, 0xd766_0006, 0x0002_0cc1, + 0xbe98_147e, 0x7d84_0c18, 0xbe9c_047e, 0xbe94_246a, 0xbea0_047e, 0xbefe_0414, + 0xbe9d_0321, 0xbefe_041c, 0x7e08_0281, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("exec_lo = ((tb_lane & 32u) == 0u ? saved_lane4 : saved_lane6)"), "{hlsl}"); + assert!(!hlsl.contains("tb_page_ballot(")); + } + + #[test] + fn restored_exec_pair_can_be_copied_and_used_as_numeric_data() { + // Save and restore EXEC around FF1. The copy of the saved pair remains + // live after its original registers are cleared. + let ex = compute_extract(&[0x7d86_0087, 0xbe94_246a, 0xbe98_147e, 0xbefe_0414, + 0xbe9e_0414, 0xbe94_0480, 0xd525_0009, 0x0000_3e1e, 0x4a08_1218, 0xbf81_0000]); + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("(saved_exec1.x + saved_exec1.y)"), "{hlsl}"); + } + + #[test] + fn scalar_copies_retain_the_original_mask_words_until_overwritten() { + // Copy and swap the mask words, clear the source, and copy the pair + // onto itself. Replacing the low word later ends just that alias. + let mut ex = compute_extract(&[0xbe9c_047e, 0xbe9e_041c, 0xbe9f_031e, 0xbe9e_031d, + 0xbe9c_0480, 0xbe9e_041e, 0xd525_0004, 0x0000_3e1e, 0xbe9e_0311, + 0xd525_0004, 0x0000_3e1e, 0xbf81_0000]); + ex.isa_preamble = [0, 21, 1, 1]; + let hlsl = super::super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("(saved_exec0.y + saved_exec0.x)"), "{hlsl}"); + assert!(hlsl.contains("(s30 + saved_exec0.x)"), "{hlsl}"); + assert_eq!(hlsl.matches("WaveActiveBallot(").count(), 1); + } + + #[test] + fn partial_register_write_preserves_only_the_other_snapshot_word() { + // Copy EXEC to s[28:29], overwrite s29, then broadcast both registers. + let mut ex = compute_extract(&[0xbe9c_047e, 0xbe9d_0391, 0x7e08_021c, 0x7e0a_021d, 0xbf81_0000]); + ex.isa_preamble = [0, 7, 3, 1]; + let shader = super::super::translate(&ex).unwrap(); + assert_eq!(shader.required_wave_size, Some(32)); + assert!(shader.hlsl.contains("v4 = saved_exec0.x;")); + assert!(shader.hlsl.contains("v5 = s29;")); + assert!(!shader.hlsl.contains("saved_exec0.y;")); + } + #[test] fn compute_register_writes_share_one_exec_region() { // v_add_nc_u32 v1, v0, v0; v_add_nc_u32 v2, v1, v1; s_endpgm diff --git a/tools/shader-compiler/src/hlsl/exec_snapshot.rs b/tools/shader-compiler/src/hlsl/exec_snapshot.rs new file mode 100644 index 00000000..2f817ec5 --- /dev/null +++ b/tools/shader-compiler/src/hlsl/exec_snapshot.rs @@ -0,0 +1,287 @@ +//! A saved EXEC has two views: per-invocation bits for restoring the predicate, +//! and two uniform words when the shader reads it as integer data. +use super::{ff1_b64_expr, ElectionLowering, Emitter, Enc, Insn, Opnd}; +use std::collections::BTreeMap; + +#[derive(Clone, Copy)] +pub(super) enum Site { + Capture(ElectionLowering), + Predicate, + LaneMask(ElectionLowering, u8, [Word; 2]), + First(usize), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Word { + Saved(usize, bool), + Uniform, +} + +#[derive(Default)] +pub(super) struct Snapshots { + pub(super) sites: BTreeMap, + // Each register word has its own reaching definition, including in a pair. + inputs: BTreeMap<(usize, u8), (usize, bool)>, +} + +impl Snapshots { + pub(super) fn word(&self, instruction: usize, operand: &Opnd) -> Option { + let Opnd::Sgpr(reg) = *operand else { + return None; + }; + let &(def, high) = self.inputs.get(&(instruction, reg))?; + Some(format!("saved_exec{def}.{}", if high { "y" } else { "x" })) + } +} + +pub(super) fn captures_exec(ins: &Insn) -> bool { + (ins.mnemonic == "s_mov_b64" && ins.src == [Opnd::ExecLo]) + || ins.mnemonic == "s_and_saveexec_b64" +} + +/// The verified 64-bit EXEC search broadcasts one integer to its guest wave. +fn first_exec_lane(ins: &Insn) -> bool { + matches!( + ins.mnemonic.as_str(), + "s_ff1_i32_b64" | "tb_first_exec_lane" + ) && ins.src == [Opnd::ExecLo] +} + +/// Only ordinary integer data operands. In particular CNDMASK's third +/// source is the lane predicate and must retain its per-invocation value. +pub(super) fn numeric_sources(ins: &Insn) -> usize { + if ins.aux.sdwa.is_some() { + return 0; + } + match (ins.enc, ins.mnemonic.as_str()) { + (Enc::Vop1 | Enc::Vop3, "v_mov_b32") => 1, + ( + Enc::Vop2 | Enc::Vop3, + "v_add_nc_u32" | "v_and_b32" | "v_lshrrev_b32" | "v_lshlrev_b32" | "v_cndmask_b32", + ) => 2, + (Enc::Vopc | Enc::Vop3, m) + if (m.starts_with("v_cmp_") || m.starts_with("v_cmpx_")) + && matches!( + m.rsplit('_').next(), + Some("u16" | "i16" | "u32" | "i32" | "u64" | "i64") + ) => + { + 2 + } + _ => 0, + } +} + +/// Transfer the reaching definition of each word before updating the destination. +/// A move from an ordinary scalar also ends an old mask definition there. +pub(super) fn copy_scalar_words(ins: &Insn, words: &mut BTreeMap) -> bool { + let ([Opnd::Sgpr(src)], [Opnd::Sgpr(dst)]) = (ins.src.as_slice(), ins.dst.as_slice()) else { + return false; + }; + let width = match ins.mnemonic.as_str() { + "s_mov_b32" => 1, + "s_mov_b64" => 2, + _ => return false, + }; + let sources = [words.get(src).copied(), words.get(&(src + 1)).copied()]; + for (offset, source) in sources.into_iter().take(width).enumerate() { + let dest = dst + offset as u8; + if let Some(def) = source { + words.insert(dest, def); + } else { + words.remove(&dest); + } + } + true +} + +/// Record a scalar destination after its inputs have been consumed. Scalar +/// register copies are transferred separately by `copy_scalar_words`. +pub(super) fn record_scalar_write(ins: &Insn, i: usize, words: &mut BTreeMap) { + let [Opnd::Sgpr(dst)] = ins.dst.as_slice() else { + return; + }; + let width = match ins.mnemonic.as_str() { + "s_load_dwordx4" => 4, + "s_mov_b64" | "s_and_saveexec_b64" => 2, + m if m.starts_with("v_cmp") => 2, + _ => 1, + }; + for word in *dst..dst.saturating_add(width) { + words.remove(&word); + } + if captures_exec(ins) { + words.insert(*dst, Word::Saved(i, false)); + words.insert(*dst + 1, Word::Saved(i, true)); + } else if first_exec_lane(ins) { + words.insert(*dst, Word::Uniform); + } else if matches!(ins.mnemonic.as_str(), "s_mov_b32" | "s_mov_b64") + && matches!(ins.src.as_slice(), [Opnd::ConstInt(_) | Opnd::Literal(_)]) + { + for word in *dst..*dst + width { + words.insert(word, Word::Uniform); + } + } +} + +/// Native EXEC saves already carry the right per-lane bit when an intact +/// pair controls a lane. A reconstructed pair needs the bit from its chosen words. +fn plan_lane_mask(plan: &mut Snapshots, i: usize, mode: ElectionLowering, lo: u8, pair: [Word; 2]) { + if matches!(pair, [Word::Saved(lo, false), Word::Saved(hi, true)] if lo == hi) { + return; + } + let count = if mode == ElectionLowering::Native32 { + 1 + } else { + 2 + }; + for (j, word) in pair.iter().take(count).enumerate() { + if let Word::Saved(def, high) = word { + if *high == (j == 1) { + plan.sites.entry(*def).or_insert(Site::Predicate); + } else { + plan.sites.insert(*def, Site::Capture(mode)); + } + } + } + plan.sites.insert(i, Site::LaneMask(mode, lo, pair)); +} + +/// Only called for straight-line compute with established wave geometry. +pub(super) fn analyze(code: &[Insn], mode: ElectionLowering) -> Snapshots { + let mut words = BTreeMap::new(); + let mut plan = Snapshots::default(); + for (i, ins) in code.iter().enumerate() { + let predicate = match ins.mnemonic.as_str() { + "s_mov_b64" if ins.dst == [Opnd::ExecLo] => ins.src.first(), + "v_cndmask_b32" if ins.enc == Enc::Vop3 && ins.aux.sdwa.is_none() => ins.src.get(2), + _ => None, + }; + if let Some(Opnd::Sgpr(lo)) = predicate { + if let (Some(&low), Some(&high)) = (words.get(lo), words.get(&(lo + 1))) { + plan_lane_mask(&mut plan, i, mode, *lo, [low, high]); + } + } + let pair = ins.mnemonic.ends_with("_u64") || ins.mnemonic.ends_with("_i64"); + for src in ins.src.iter().take(numeric_sources(ins)) { + let Opnd::Sgpr(first) = *src else { continue }; + for reg in first..=first + u8::from(pair) { + if let Some(&Word::Saved(def, high)) = words.get(®) { + plan.sites.insert(def, Site::Capture(mode)); + plan.inputs.insert((i, reg), (def, high)); + } + } + } + if copy_scalar_words(ins, &mut words) { + continue; + } + record_scalar_write(ins, i, &mut words); + } + for (i, pair) in code.windows(2).enumerate() { + if matches!(plan.sites.get(&i), Some(Site::Capture(_))) + && pair[0].mnemonic == "s_mov_b64" + && first_exec_lane(&pair[1]) + { + plan.sites.insert(i + 1, Site::First(i)); + } + } + plan +} + +impl Site { + pub(super) fn emit(self, em: &mut Emitter<'_>, i: usize, ins: &Insn) -> Result { + match self { + Self::Capture(mode) => { + let ballot = match mode { + ElectionLowering::Native32 => "WaveActiveBallot((exec_lo & 1u) != 0u).xy", + ElectionLowering::Shared64 => "tb_page_ballot(tb_lane, (exec_lo & 1u) != 0u)", + }; + em.line(&format!("uint2 saved_exec{i} = {ballot};")); + return Ok(false); // The guest save and its effect on EXEC still run. + } + Self::Predicate => { + em.line(&format!("uint saved_lane{i} = exec_lo & 1u;")); + return Ok(false); + } + Self::LaneMask(mode, lo, words) => { + let lane = if mode == ElectionLowering::Native32 { + "WaveGetLaneIndex()" + } else { + "tb_lane" + }; + let mut bit = |j: usize| -> Result { + let bits = match words[j] { + Word::Saved(def, _) + if matches!( + em.exec_snapshots.sites.get(&def), + Some(Site::Predicate) + ) => + { + return Ok(format!("saved_lane{def}")) + } + Word::Saved(def, high) => { + format!("saved_exec{def}.{}", if high { "y" } else { "x" }) + } + Word::Uniform => { + let reg = Opnd::Sgpr(lo + j as u8); + em.touch(®); + super::r(®)? + } + }; + Ok(format!("(({bits} >> ({lane} & 31u)) & 1u)")) + }; + let low = bit(0)?; + let predicate = if mode == ElectionLowering::Native32 { + low + } else { + format!("(({lane} & 32u) == 0u ? {low} : {})", bit(1)?) + }; + if ins.mnemonic == "v_cndmask_b32" { + em.line(&format!("uint select_mask{i} = {predicate};")); + return Ok(false); // Keep normal VOP3 data modifiers and EXEC predication. + } + em.ws(&Opnd::ExecLo, &predicate)?; + em.ws(&Opnd::ExecHi, "0u")?; + } + Self::First(def) => { + em.ws( + &ins.dst[0], + &ff1_b64_expr(&format!("saved_exec{def}.x"), &format!("saved_exec{def}.y")), + )?; + } + } + Ok(true) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn four_word_load_ends_the_lifetime_of_an_overlapping_saved_pair() { + // Save EXEC in s[30:31], elect a lane, read s31, load s[28:31], then read s30. + let words = [ + 0xbe9e_047eu32, + 0xbe98_147e, + 0x7e04_021f, + 0xf408_0702, + 0xfa00_0000, + 0xbf8c_c07f, + 0x7e08_021e, + ]; + let bytes = words + .into_iter() + .flat_map(u32::to_le_bytes) + .collect::>(); + let code = super::super::disassemble(&bytes); + let plan = analyze(&code, ElectionLowering::Shared64); + assert!(matches!( + plan.sites.get(&0), + Some(Site::Capture(ElectionLowering::Shared64)) + )); + assert!(matches!(plan.sites.get(&1), Some(Site::First(0)))); + assert_eq!(plan.inputs.get(&(2, 31)), Some(&(0, true))); + assert!(!plan.inputs.contains_key(&(5, 30))); + } +} diff --git a/tools/shader-compiler/src/hlsl/group_extrema.rs b/tools/shader-compiler/src/hlsl/group_extrema.rs index f5bb5cbc..1a25bd7d 100644 --- a/tools/shader-compiler/src/hlsl/group_extrema.rs +++ b/tools/shader-compiler/src/hlsl/group_extrema.rs @@ -4,6 +4,149 @@ use super::{compute_group, wave_sum, Emitter, Enc, Insn, Opnd, ShaderExtract, Stage}; use crate::rdna2::clobbers_scalar; +pub(super) fn is_dpp8(ins: &Insn) -> bool { + ins.enc == Enc::Vop2 + && ins + .raw + .first() + .is_some_and(|w| matches!(w & 0x1ff, 233 | 234)) +} + +// DPP8 stores its lane selectors in the same bits that hold DPP16 write masks. +pub(super) fn destination_mask(ins: &Insn) -> Option { + if ins.enc != Enc::Vop2 || ins.raw.first()? & 0x1ff != 250 { + return None; + } + let mask = (ins.raw.get(1)? >> 24) as u8; + (mask != 0xff).then_some(mask) +} + +// Choose the same logical width as the program's lane broadcasts. The physical +// subgroup used to fetch the source operand may contain only half a guest wave. +pub(super) fn row_index_mask(em: &Emitter<'_>, rows: u8, banks: u8) -> Result { + if (rows & 3) == (rows >> 2) || banks == 0 { + return Ok(3); // The effective write mask repeats in both halves. + } + let register_width = em.packed.as_ref().and_then(|p| p.register_wave_size); + let threads = compute_group(em.ex).into_iter().fold(1u32, u32::saturating_mul); + match em.fspx_wave.or(register_width) { + Some(32) => Ok(1), + Some(64) => Ok(3), + _ if threads <= 32 || em.resolve_wave32 || em.single_wave32 => Ok(1), + _ if em.indexed_lane => Ok(3), + _ => Err("asymmetric DPP16 row mask requires a known guest wave width".into()), + } +} + +fn wider_exchange(ins: &Insn) -> bool { + if ins.enc != Enc::Vop2 || !matches!(ins.mnemonic.as_str(), "v_min_f32" | "v_max_f32") { + return false; + } + if is_dpp8(ins) { + return ins.raw.len() == 2; + } + // DPP16 rotation, mirror or quad with destination masks or source modifiers. + ins.src.first() == Some(&Opnd::Raw(250)) + && ins.raw.get(1).is_some_and(|c| { + let control = (c >> 8) & 0x1ff; + c & 0x0002_0000 == 0 + && (matches!(control, 0x121..=0x12f | 0x140) + || (control <= 0xff && (destination_mask(ins).is_some() || c & 0x00f0_0000 != 0))) + }) +} + +fn supported_step(ins: &Insn, op: &str) -> bool { + if matches!( + ins.mnemonic.as_str(), + "v_permlanex16_b32" | "v_readlane_b32" + ) { + return true; // The existing lane exchange emitters validate the operands. + } + ins.enc == Enc::Vop2 + && ins.mnemonic == op + && (wider_exchange(ins) + || super::is_binary_quad_perm(ins) + || matches!( + &ins.src[..], + [ + Opnd::Sgpr(_) + | Opnd::Vgpr(_) + | Opnd::ConstInt(_) + | Opnd::ConstF32(_) + | Opnd::Literal(_), + Opnd::Vgpr(_) + ] + )) +} + +// Keep the native reduction tree and intermediate registers intact. Its READLANE +// instructions must still address the logical wave, including the other 32 lanes. +pub(super) fn prepare_exchanges(ex: &ShaderExtract, code: &mut [Insn]) -> Result { + if ex.stage != Stage::Compute { + return Ok(false); + } + let mut changed = false; + let mut targets = None; + let mut pos = 0; + while pos + 3 < code.len() { + let save = &code[pos]; + pos += 1; + if save.mnemonic != "s_nand_saveexec_b64" || save.src != [Opnd::ConstInt(0)] { + continue; + } + let [Opnd::Sgpr(saved)] = save.dst[..] else { + continue; + }; + let [identity, select, first, ..] = &code[pos..] else { + break; + }; + if identity.mnemonic != "v_mov_b32" + || select.mnemonic != "v_cndmask_b32" + || select.src.get(2) != Some(&Opnd::Sgpr(saved)) + || !matches!(first.mnemonic.as_str(), "v_min_f32" | "v_max_f32") + { + continue; + } + let body = &code[pos + 2..]; + let count = body + .iter() + .take_while(|i| supported_step(i, &first.mnemonic)) + .count(); + let Some(restore) = body.get(count) else { + continue; + }; + if restore.mnemonic != "s_mov_b64" + || restore.dst != [Opnd::ExecLo] + || restore.src != [Opnd::Sgpr(saved)] + || !body[..count].iter().any(wider_exchange) + { + continue; + } + // FI=0 on DPP8 relies on NAND_SAVEEXEC having enabled every source lane. + let targets = targets.get_or_insert_with(|| super::branch_targets(code)); + if targets + .range((save.offset as i64 + 1)..(restore.offset as i64)) + .next() + .is_some() + { + return Err("branch enters a saved-EXEC extrema exchange".into()); + } + pos += 2; + for ins in &mut code[pos..pos + count] { + if ins.enc == Enc::Vop2 { + if matches!(ins.src.first(), Some(Opnd::Raw(233 | 234 | 250))) { + super::lower_dpp_binary(ins); + } else { + ins.op = super::OP_LOCAL_EXTREMA; + } + } + } + pos += count; + changed = true; + } + Ok(changed) +} + pub(super) fn prepare(ex: &ShaderExtract, code: &mut [Insn]) -> bool { if ex.stage != Stage::Compute || !compute_group(ex) diff --git a/tools/shader-compiler/src/hlsl/indexed_lane.rs b/tools/shader-compiler/src/hlsl/indexed_lane.rs index e8c3182a..db09df42 100644 --- a/tools/shader-compiler/src/hlsl/indexed_lane.rs +++ b/tools/shader-compiler/src/hlsl/indexed_lane.rs @@ -60,19 +60,34 @@ pub(super) fn skip_empty_wave_fallback(insns: &mut Vec) -> bool { /// A constant read in a converged group observes another invocation's VGPR, /// including lane 32 on hosts with 32-lane subgroups. Keep SGPR spills separate. -pub(super) fn constant_reads(group: [u32; 3], insns: &mut [Insn]) -> bool { +pub(super) fn constant_reads(group: [u32; 3], insns: &mut [Insn], allow_small_group: bool) -> bool { let count = group.into_iter().fold(1u32, u32::saturating_mul); - if count == 0 || count > 1024 || count % 64 != 0 { return false; } + // Up to 32 threads fit in one guest wave of either width. Only read a + // lane that actually launched, even when its selector comes from an SGPR. + let small = allow_small_group && (1..=32).contains(&count); + if count == 0 || count > 1024 || (!small && count % 64 != 0) { return false; } let Some(last) = insns.iter().rposition(|op| op.mnemonic == "v_readlane_b32") else { return false }; let end = insns[last].offset as i64; + let selectors = if small { + super::scalar_values::at_reads(insns, super::scalar_values::Proof::UpperBound, |op| match (op.mnemonic.as_str(), op.src.get(1)) { + ("v_readlane_b32", Some(Opnd::Sgpr(reg))) => Some(*reg), + _ => None, + }) + } else { Default::default() }; + let upper_lane = |op: &Insn| match op.src.get(1)? { + Opnd::ConstInt(n @ 0..=63) => Some(*n as u32), + Opnd::Sgpr(reg) => selectors.get(&(op.offset, *reg)).copied(), + _ => None, + }; if insns.iter().any(|op| { let name = op.mnemonic.as_str(); let branch = op.enc == Enc::Sopp && Emitter::branch_cond(op.op).is_some(); name == "v_writelane_b32" || matches!(name, "s_setpc_b64" | "s_swappc_b64" | "s_call_b64") || (op.offset as i64 <= end && name == "s_endpgm") || (name.contains("branch") && (!branch || op.aux.imm < 0)) - || (name == "v_readlane_b32" && !matches!((&op.dst[..], &op.src[..]), - ([Opnd::Vgpr(_)], [Opnd::Vgpr(_), Opnd::ConstInt(0..=63), ..]))) + || (name == "v_readlane_b32" && (!matches!((&op.dst[..], op.src.first()), + ([Opnd::Vgpr(_)], Some(Opnd::Vgpr(_)))) + || !upper_lane(op).is_some_and(|n| n < count.min(64)))) }) { return false; } for op in insns.iter_mut().filter(|op| op.mnemonic == "v_readlane_b32") { let Opnd::Vgpr(dst) = op.dst[0] else { unreachable!() }; @@ -188,6 +203,76 @@ mod tests { prepare(group, &mut crate::rdna2::disassemble(&isa)) } + #[test] + fn partial_group_reads_only_proven_launched_lanes() { + // In a 7x3 group, registers and inline operands can select lanes 0..20. + const SET: u32 = 0xbe98_0394; // s_mov_b32 s24,20 + const READ: [u32; 2] = [0xd760_001c, 0x0000_3109]; // s28,v9,s24 + const END: u32 = 0xbf81_0000; + let check = |words: &[u32]| { + let isa: Vec<_> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let mut ops = crate::rdna2::disassemble(&isa); + let before = ops.iter().map(|op| op.mnemonic.clone()).collect::>(); + let accepted = constant_reads([7, 3, 1], &mut ops, true); + if accepted { + assert!(ops.iter().any(|op| op.mnemonic == "tb_indexed_readlane")); + assert!(!ops.iter().any(|op| op.mnemonic == "v_readlane_b32")); + } else { + assert!(ops.iter().map(|op| &op.mnemonic).eq(&before)); + } + accepted + }; + assert!(check(&[SET, READ[0], READ[1], END])); + assert!(!check(&[SET + 1, READ[0], READ[1], END])); + assert!(check(&[READ[0], 0x0001_2909, END])); // inline lane 20 + assert!(!check(&[READ[0], 0x0001_2b09, END])); // inline lane 21 + // Equal incoming values at a forward branch join prove the selector. + assert!(check(&[SET, 0xbf84_0001, SET, READ[0], READ[1], END])); + assert!(!check(&[SET, 0xbf84_0001, SET + 1, READ[0], READ[1], END])); + assert!(check(&[SET, 0xbf84_0001, SET - 1, READ[0], READ[1], END])); + // Keep the runtime selector when both CSELECT operands are in range. + assert!(check(&[0x8518_8a94, 0xbe99_0318, READ[0], 0x0000_3309, END])); + assert!(!check(&[0x8518_9594, READ[0], READ[1], END])); // 20 or 21 + assert!(!check(&[0x8518_0594, READ[0], READ[1], END])); // 20 or unknown + // CMOV keeps the previous destination when SCC is clear. + const CMOV_20: u32 = 0xbe98_0594; // s_cmov_b32 s24,20 + assert!(check(&[SET - 10, CMOV_20, READ[0], READ[1], END])); + assert!(!check(&[CMOV_20, READ[0], READ[1], END])); + assert!(!check(&[SET + 1, CMOV_20, READ[0], READ[1], END])); + assert!(!check(&[SET, CMOV_20 + 1, READ[0], READ[1], END])); + assert!(!check(&[SET, 0xbe98_0505, READ[0], READ[1], END])); // source s5 unknown + assert!(check(&[0x8718_8f05, READ[0], READ[1], END])); // s5 & 15 + assert!(!check(&[0x8718_9f05, READ[0], READ[1], END])); // s5 & 31 + assert!(!check(&[0x8718_8f05, 0x8018_a018, READ[0], READ[1], END])); // add 32 + // The first read overwrites the selector with the selected VGPR value. + assert!(!check(&[SET, 0xd760_0018, READ[1], READ[0], READ[1], END])); + } + + #[test] + fn partial_group_selector_tracks_each_word_of_a_scalar_pair() { + const OLD: u32 = 0xbe99_038a; // s_mov_b32 s25,10 + const NEW: u32 = 0xbe9b_0394; // s_mov_b32 s27,20 + const MOV: u32 = 0xbe98_041a; // s_mov_b64 s[24:25],s[26:27] + const CMOV: u32 = 0xbe98_061a; // conditional copy of the same pair + const SELECT: u32 = 0x8598_181a; // select s[26:27] or s[24:25] + let reads_high = |setup: &[u32]| { + let words = [setup, &[0xd760_001c, 0x0000_3309, 0xbf81_0000]].concat(); + let bytes: Vec<_> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + constant_reads([7, 3, 1], &mut crate::rdna2::disassemble(&bytes), true) + }; + assert!(reads_high(&[NEW, MOV])); + assert!(!reads_high(&[OLD, MOV])); // unknown source overwrites known high word + for op in [CMOV, SELECT] { + assert!(reads_high(&[OLD, NEW, op])); // low words are unknown + assert!(!reads_high(&[NEW, op])); + assert!(!reads_high(&[OLD, op])); + assert!(!reads_high(&[OLD, NEW + 1, op])); + assert!(!reads_high(&[OLD + 11, NEW, op])); + } + assert!(reads_high(&[0xbe98_0487])); // high word of inline 7 is zero + assert!(!reads_high(&[OLD, 0xbe98_04c1])); // high word of -1 is out of range + } + #[test] fn empty_wave_fallback_cannot_be_entered_from_another_edge() { let pruned = |words: &[u32]| { diff --git a/tools/shader-compiler/src/hlsl/int32.rs b/tools/shader-compiler/src/hlsl/int32.rs index 2b178b9d..c5ebefcd 100644 --- a/tools/shader-compiler/src/hlsl/int32.rs +++ b/tools/shader-compiler/src/hlsl/int32.rs @@ -1,14 +1,14 @@ //! Ordinary VOP3 integer forms with a 32-bit result: the signed no-carry -//! add/subtract, the 16x16+32 multiply-add and the sums of absolute -//! differences (SAD) over bytes, halves and words. Sources are VGPRs without -//! modifiers. Add/subtract also accept integer immediates, and byte SAD -//! accepts inline zero as its accumulator. -//! Clamp (signed saturation) is refused. -use super::{int16::half, r, Enc, Insn, Opnd}; +//! add/subtract, 16x16+32 multiply-add, saturating integer packs and sums of +//! absolute differences over bytes, halves and words. Add/subtract and unsigned MAD +//! accept integer immediates, and byte SAD accepts an inline zero accumulator. +//! Signed add/subtract also support saturating arithmetic with clamp. +use super::{int16::half, r, signed_add_overflow, Enc, Insn, Opnd}; pub(super) fn handles(ins: &Insn) -> bool { ins.enc == Enc::Vop3 && matches!(ins.mnemonic.as_str(), "v_add_nc_i32" | "v_sub_nc_i32" | "v_mad_u32_u16" | "v_mad_i32_i16" + | "v_cvt_pk_u16_u32" | "v_cvt_pk_i16_i32" | "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32") } @@ -18,12 +18,14 @@ pub(super) fn expression(ins: &Insn) -> Result, String> { } let mad = ins.mnemonic.starts_with("v_mad_"); let add_sub = matches!(ins.mnemonic.as_str(), "v_add_nc_i32" | "v_sub_nc_i32"); - let arity = if add_sub { 2 } else { 3 }; + let pack = matches!(ins.mnemonic.as_str(), "v_cvt_pk_u16_u32" | "v_cvt_pk_i16_i32"); + let arity = if add_sub || pack { 2 } else { 3 }; if !ins.is_complete() || ins.raw.len() < 2 || ins.src.len() < arity || !ins.src[..arity].iter().enumerate().all(|(index, s)| { matches!(s, Opnd::Vgpr(_)) || (add_sub && matches!(s, Opnd::ConstInt(_) | Opnd::Literal(_))) || (index == 2 && ins.mnemonic == "v_sad_u8" && matches!(s, Opnd::ConstInt(0))) + || (index == 2 && ins.mnemonic == "v_mad_u32_u16" && matches!(s, Opnd::ConstInt(_))) }) { return Err("unsupported ordinary 32-bit integer source or encoding".into()); } @@ -31,10 +33,25 @@ pub(super) fn expression(ins: &Insn) -> Result, String> { // RDNA2 ISA 6.4: op_sel bits 11 and 12 pick the 16-bit half of the two // multiplicands. The 32-bit addend and result take no half selection. let allowed_select = if mad { 0x1800 } else { 0 }; - if w0 & 0x8700 != 0 || w0 & 0x7800 & !allowed_select != 0 || w1 >> 27 != 0 { + let clamped = w0 & 0x8000 != 0; + if (clamped && !add_sub) || w0 & 0x0700 != 0 || w0 & 0x7800 & !allowed_select != 0 || w1 >> 27 != 0 { return Err("unsupported ordinary 32-bit integer modifiers".into()); } let (a, b) = (r(&ins.src[0])?, r(&ins.src[1])?); + if clamped { + // Use uint arithmetic so even overflowing inputs have a defined result. + let (result, overflow) = if ins.mnemonic == "v_add_nc_i32" { + let sum = format!("({a} + {b})"); + let overflow = signed_add_overflow(&a, &b, &sum); + (sum, overflow) + } else { + let diff = format!("({a} - {b})"); + let overflow = format!("((({a} ^ {b}) & ({a} ^ {diff})) >> 31)"); + (diff, overflow) + }; + // On signed overflow the first operand's sign determines which limit to use. + return Ok(Some(format!("({overflow} != 0u ? (0x7fffffffu + ({a} >> 31)) : {result})"))); + } // |x - y| of unsigned fields, then the 32-bit accumulator S2 (modular). let sad = |width: u32| -> String { let mask = (1u64 << width) - 1; @@ -45,6 +62,11 @@ pub(super) fn expression(ins: &Insn) -> Result, String> { }).collect::>().join(" + ") }; Ok(Some(match ins.mnemonic.as_str() { + // Convert both full-width inputs with saturation; S0 occupies the low half. + "v_cvt_pk_u16_u32" => format!("(min({a}, 65535u) | (min({b}, 65535u) << 16))"), + "v_cvt_pk_i16_i32" => format!( + "((asuint(clamp(asint({a}), -32768, 32767)) & 0xffffu) | (asuint(clamp(asint({b}), -32768, 32767)) << 16))" + ), // RDNA2 ISA: SAD_U8 sums four byte differences, SAD_HI_U8 places // that sum in the high half, SAD_U16 sums two half differences. "v_sad_u8" => format!("({} + {})", sad(8), r(&ins.src[2])?), @@ -90,8 +112,9 @@ mod tests { let ins = native(first, second); assert_eq!(ins.mnemonic, name); assert!(expression(&ins).unwrap().unwrap().contains(want), "{name}"); - // clamp, abs, a scalar source and neg remain refused. - assert!(expression(&native(first | 0x8000, second)).is_err(), "{name} clamp"); + if name.starts_with("v_mad_") { + assert!(expression(&native(first | 0x8000, second)).is_err(), "{name} clamp"); + } assert!(expression(&native(first | 0x100, second)).is_err(), "{name} abs"); assert!(expression(&native(first, (second & !511) | 4)).is_err(), "{name} sgpr"); assert!(expression(&native(first, second | 1 << 29)).is_err(), "{name} neg"); @@ -104,6 +127,50 @@ mod tests { assert!(expression(&native(0xd77f_0807, 0x0202_0b04)).is_err()); } + #[test] + fn unsigned_mad_accepts_a_full_width_inline_integer_accumulator() { + // LLVM gfx1030: v_mad_u32_u16 v4, v1, v2, 7 (then -1). + for (sources, addend) in [(0x021e_0501, "0x7u"), (0x0306_0501, "0xffffffffu")] { + let expr = expression(&native(0xd773_0004, sources)).unwrap().unwrap(); + assert_eq!(expr, format!("((v1 & 0xffffu) * (v2 & 0xffffu) + {addend})")); + } + // v_mad_u32_u16 v4, 7, v2, v3 and v_mad_i32_i16 v4, v1, v2, 7 + assert!(expression(&native(0xd773_0004, 0x040e_0487)).is_err()); + assert!(expression(&native(0xd775_0004, 0x021e_0501)).is_err()); + } + + #[test] + fn integer_packs_clamp_each_word_before_combining_halves() { + use crate::hlsl::float64::tests::translate; + use crate::Stage; + + // LLVM gfx1030: v_cvt_pk_{u16_u32,i16_i32} v4, v1, v2 + for (opcode, low, high) in [ + (0xd76a_0004, "min(v1, 65535u)", "min(v2, 65535u)"), + (0xd76b_0004, "(asuint(clamp(asint(v1), -32768, 32767)) & 0xffffu)", + "asuint(clamp(asint(v2), -32768, 32767))"), + ] { + let body = [opcode, 0x0002_0501]; + let hlsl = translate(Stage::Compute, &body).unwrap(); + assert!(hlsl.contains(&format!("({low} | ({high} << 16))")), "{hlsl}"); + assert!(translate(Stage::Compute, &[opcode | 0x0800, body[1]]).is_err()); + assert!(translate(Stage::Compute, &[opcode, body[1] | (1 << 29)]).is_err()); + } + } + + #[test] + fn signed_add_and_subtract_accept_clamp() { + use crate::hlsl::float64::tests::translate; + use crate::Stage; + + // LLVM gfx1030: v_add_nc_i32 / v_sub_nc_i32 v4, v1, v2 clamp + for (opcode, result) in [(0xd77f_8004, "(v1 + v2)"), (0xd776_8004, "(v1 - v2)")] { + let hlsl = translate(Stage::Compute, &[opcode, 0x0002_0501]).unwrap(); + assert!(hlsl.contains(&format!("? (0x7fffffffu + (v1 >> 31)) : {result}")), "{hlsl}"); + assert!(translate(Stage::Compute, &[opcode | 0x0100, 0x0002_0501]).is_err()); + } + } + #[test] fn signed_add_and_subtract_accept_immediate_operands() { use crate::hlsl::float64::tests::translate; diff --git a/tools/shader-compiler/src/hlsl/mubuf_offsets.rs b/tools/shader-compiler/src/hlsl/mubuf_offsets.rs index 04e31848..d248fdc0 100644 --- a/tools/shader-compiler/src/hlsl/mubuf_offsets.rs +++ b/tools/shader-compiler/src/hlsl/mubuf_offsets.rs @@ -144,97 +144,13 @@ pub(super) fn proven_zero(insns: &[Insn]) -> BTreeSet<(usize, u8)> { offsets } -// A bounded forward constant lattice for static scalar table addressing. -// Only exact values agreed on by all reachable predecessors are retained. -// Unknown writes kill facts, including the secondary destinations handled by -// the existing zero-offset analysis. Larger programs retain the old zero proof. pub(super) fn proven_smem_constants(insns: &[Insn]) -> BTreeMap<(usize, u8), u32> { - if insns.is_empty() || insns.len() > 32768 - || !insns.iter().any(|i| i.enc == Enc::Smem && offset_register(i).is_some()) - || insns.iter().any(|i| !i.is_complete() || i.enc == Enc::Unknown - || i.mnemonic.contains('<') || i.mnemonic.starts_with("s_movreld_") - || i.mnemonic.starts_with("s_subvector_loop_") - || (i.mnemonic.starts_with("s_cbranch_") && Emitter::branch_cond(i.op).is_none()) - || matches!(i.mnemonic.as_str(), "s_setpc_b64" | "s_swappc_b64" - | "s_rfe_b64" | "s_call_b64" | "s_movrelsd_2_b32" | "s_trap")) - { return BTreeMap::new(); } - - type State = BTreeMap; - let mut input: Vec> = vec![None; insns.len()]; - input[0] = Some(State::new()); - let mut work = VecDeque::from([0]); - let mut iterations = 0usize; - while let Some(index) = work.pop_front() { - iterations += 1; - if iterations > insns.len() * 128 { return BTreeMap::new(); } - let ins = &insns[index]; - let incoming = input[index].as_ref().expect("reachable"); - let mut out = incoming.clone(); - out.retain(|®, _| !writes_scalar(ins, reg)); - if ins.enc == Enc::Vop3 { - if ins.mnemonic.contains("_co_") - || matches!(ins.mnemonic.as_str(), "v_mad_u64_u32" | "v_mad_i64_i32" | "v_div_scale_f32" | "v_div_scale_f64") - { - let reg = ((ins.raw[0] >> 8) & 127) as u8; - out.remove(®); - out.remove(&(reg + 1)); - } - if ins.mnemonic == "v_readfirstlane_b32" { - out.remove(&((ins.raw[0] & 127) as u8)); - } - } - // Ordinary scalar operations whose emitted uint semantics are exact. - let value = |op: &Opnd| match op { - Opnd::Sgpr(r @ 0..=105) => incoming.get(r).copied(), - Opnd::ConstInt(v) => Some(*v as u32), - Opnd::Literal(v) => Some(*v), - _ => None, - }; - if let [Opnd::Sgpr(dst @ 0..=105)] = ins.dst.as_slice() { - let known = match (ins.mnemonic.as_str(), ins.src.as_slice()) { - ("s_mov_b32", [a]) => value(a), - ("s_add_u32" | "s_add_i32", [a, b]) => value(a).zip(value(b)).map(|(a,b)| a.wrapping_add(b)), - ("s_sub_u32" | "s_sub_i32", [a, b]) => value(a).zip(value(b)).map(|(a,b)| a.wrapping_sub(b)), - ("s_and_b32", [a,b]) => value(a).zip(value(b)).map(|(a,b)| a & b), - ("s_or_b32", [a,b]) => value(a).zip(value(b)).map(|(a,b)| a | b), - ("s_xor_b32", [a,b]) => value(a).zip(value(b)).map(|(a,b)| a ^ b), - ("s_lshl_b32", [a,b]) => value(a).zip(value(b)).map(|(a,b)| a << (b & 31)), - ("s_lshr_b32", [a,b]) => value(a).zip(value(b)).map(|(a,b)| a >> (b & 31)), - _ => None, - }; - if let Some(v) = known { out.insert(*dst, v); } - } - let mut merge = |next: usize| { - let Some(slot) = input.get_mut(next) else { return }; - let mut joined = slot.clone().unwrap_or_else(|| out.clone()); - joined.retain(|r, v| out.get(r) == Some(v)); - if slot.as_ref() != Some(&joined) { - *slot = Some(joined); - work.push_back(next); - } - }; - if ins.enc == Enc::Sopp && Emitter::branch_cond(ins.op).is_some() { - let target = ins.offset as i64 + 4 + 4 * ins.aux.imm; - let Ok(next) = insns.binary_search_by_key(&target, |i| i.offset as i64) - else { return BTreeMap::new(); }; - merge(next); - if ins.op == 2 { continue; } - } - if ins.mnemonic != "s_endpgm" { merge(index + 1); } - } - let mut result = BTreeMap::new(); - for (ins, state) in insns.iter().zip(input) { - if ins.enc == Enc::Smem { - if let Some(reg) = offset_register(ins) { - if let Some(v) = state.and_then(|s| s.get(®).copied()) { - result.insert((ins.offset, reg), v); - } - } - } - } - result + super::scalar_values::at_reads(insns, super::scalar_values::Proof::Exact, |ins| { + if ins.enc == Enc::Smem { offset_register(ins) } else { None } + }) } + #[cfg(test)] mod tests { use super::*; @@ -284,6 +200,17 @@ mod tests { assert!(check(&[thirty_two, 0xd70f4200, 0x02020300, load[0], load[1], END]).is_empty()); } + #[test] + fn an_upper_bound_is_insufficient_for_a_static_table_offset() { + // CSELECT of 20 and 10, or an unknown register masked to four bits. + // Both values have an upper bound but neither is an exact offset. + for producer in [0x8518_8a94, 0x8718_8f05] { + let words = [producer, 0xf408_1000, 24 << 25, END]; + let bytes: Vec<_> = words.iter().flat_map(|v| v.to_le_bytes()).collect(); + assert!(proven_smem_constants(&disassemble(&bytes)).is_empty()); + } + } + #[test] fn copied_offsets_require_proven_sources_on_every_path() { let zero65 = 0xbec10380; // s_mov_b32 s65, 0 diff --git a/tools/shader-compiler/src/hlsl/page_waves.rs b/tools/shader-compiler/src/hlsl/page_waves.rs index bc5ed3ea..ee418b1f 100644 --- a/tools/shader-compiler/src/hlsl/page_waves.rs +++ b/tools/shader-compiler/src/hlsl/page_waves.rs @@ -76,6 +76,27 @@ pub(super) fn emit(em: &mut Emitter<'_>, i: usize, ins: &Insn, target: Option String { + format!(r#"uint2 tb_page_ballot(uint tid, bool vote) {{ + {clear} + GroupMemoryBarrierWithGroupSync(); + {vote} + GroupMemoryBarrierWithGroupSync(); + uint halfWave = (tid >> 6) * 2u; + uint2 bits = uint2(page_bits[halfWave], page_bits[halfWave + 1u]); + GroupMemoryBarrierWithGroupSync(); + return bits; +}}"#) +} + +const SET_BIT: &str = "if (vote) InterlockedOr(page_bits[tid >> 5], 1u << (tid & 31u));"; + +pub(super) fn ballot_declarations(threads: u32) -> String { + let words = threads.div_ceil(64) * 2; + let clear = format!("if (tid < {words}u) page_bits[tid] = 0u;"); + format!("groupshared uint page_bits[{words}];\n{}\n", ballot_function(&clear, SET_BIT)) +} + pub(super) fn declarations(group: [u32; 3], branchless: bool) -> String { let (words, lanes, clear, vote) = if branchless { // Each of the 64 lanes clears a distinct word. Zero votes contribute @@ -84,27 +105,19 @@ pub(super) fn declarations(group: [u32; 3], branchless: bool) -> String { (64, 256, "page_bits[tid] = 0u;", "InterlockedOr(page_bits[tid >> 5], uint(vote) << (tid & 31u));") } else { - let vote = "if (vote) InterlockedOr(page_bits[tid >> 5], 1u << (tid & 31u));"; + let vote = SET_BIT; if group == [1024, 1, 1] { (32, 1024, "if (tid < 32u) page_bits[tid] = 0u;", vote) } else { (8, 256, "if (tid < 8u) page_bits[tid] = 0u;", vote) } }; + let ballot = ballot_function(clear, vote); format!(r#" groupshared uint page_bits[{words}]; groupshared uint page_lane_values[{lanes}]; -uint2 tb_page_ballot(uint tid, bool vote) {{ - {clear} - GroupMemoryBarrierWithGroupSync(); - {vote} - GroupMemoryBarrierWithGroupSync(); - uint halfWave = (tid >> 6) * 2u; - uint2 bits = uint2(page_bits[halfWave], page_bits[halfWave + 1u]); - GroupMemoryBarrierWithGroupSync(); - return bits; -}} +{ballot} uint tb_page_read(uint tid, uint value, uint lane) {{ page_lane_values[tid] = value; diff --git a/tools/shader-compiler/src/hlsl/persistent.rs b/tools/shader-compiler/src/hlsl/persistent.rs index 395a0892..086e00d1 100644 --- a/tools/shader-compiler/src/hlsl/persistent.rs +++ b/tools/shader-compiler/src/hlsl/persistent.rs @@ -210,7 +210,7 @@ fn emit_op(em: &mut Emitter<'_>, idx: usize, op: &Insn) -> Result<(), String> { let condition = if m.ends_with("_f32") { em.compare_float(op, op.aux.mask)? } else if m.ends_with("_i32") || m.ends_with("_u32") { - Emitter::int_compare(m, &op.src[0], &op.src[1])? + em.int_compare(m, &op.src[0], &op.src[1])? } else { return Err("unsupported persistent wave comparison type".into()); }; diff --git a/tools/shader-compiler/src/hlsl/raw_index.rs b/tools/shader-compiler/src/hlsl/raw_index.rs index 8b22bef5..33e10a09 100644 --- a/tools/shader-compiler/src/hlsl/raw_index.rs +++ b/tools/shader-compiler/src/hlsl/raw_index.rs @@ -1,6 +1,12 @@ //! Proof for indexed reads of a locally constructed linear byte descriptor. use crate::rdna2::{Insn, Opnd, clobbers_scalar}; +pub(super) fn sets_byte_stride(ins: &Insn, address_high: u8) -> bool { + ins.mnemonic == "s_or_b32" && matches!(ins.src.as_slice(), + [Opnd::Sgpr(reg), Opnd::Literal(0x10000)] | [Opnd::Literal(0x10000), Opnd::Sgpr(reg)] + if *reg == address_high) +} + /// The existing DirectRaw binding recognizer proves the root SRV. For IDXEN, /// additionally require its complete stride-one construction in the same /// basic block and no intervening overwrite of any of its four words. @@ -24,9 +30,8 @@ pub(super) fn local_byte_descriptor(ops: &[Insn], base: u16) -> bool { && size.src == [Opnd::ConstInt(-1)] && low.mnemonic == "s_mov_b32" && low.dst == [Opnd::Sgpr(base)] - && high.mnemonic == "s_or_b32" && high.dst == [Opnd::Sgpr(base + 1)] - && high.src == [Opnd::Sgpr(root + 1), Opnd::Literal(65536)] + && sets_byte_stride(high, root + 1) && ops[end + 1..].iter().all(|i| { !(base..=base+3).any(|reg| clobbers_scalar(i, reg)) }) diff --git a/tools/shader-compiler/src/hlsl/raw_width.rs b/tools/shader-compiler/src/hlsl/raw_width.rs index 9309b391..36b5a4f8 100644 --- a/tools/shader-compiler/src/hlsl/raw_width.rs +++ b/tools/shader-compiler/src/hlsl/raw_width.rs @@ -62,6 +62,43 @@ fn raw_buffer_transfers_are_emitted_one_dword_at_a_time() { } } +#[test] +fn store_beyond_a_single_srv_range_uses_only_a_corroborated_uav() { + use crate::meta::{RootParam, RootParamKind, RootRange}; + // Load the descriptor at physical slot 1, then store through it. + let words = [0xf408_0402u32, 0xfa00_0020, 0xe070_1000, 0x8004_0405, 0xbf81_0000]; + let isa: Vec = words.into_iter().flat_map(u32::to_le_bytes).collect(); + let mut ex = super::mesh::heap_extract(&[[3, 8, 1, 0, 4]], 0, &isa); + ex.stage = Stage::Compute; + ex.psv_threads = Some([64, 1, 1]); + ex.required_features = None; + // The matching used-resource and PSV rows identify a raw UAV at u0. + let used_at = (ex.fssm.len() - 16) as u64; + ex.fssm[0xf0..0xf8].copy_from_slice(&used_at.to_le_bytes()); + ex.fssm[0xfc..0x100].copy_from_slice(&1u32.to_le_bytes()); + ex.fssm.extend([0x303u32, 8, 0, 1, 0x404].into_iter().flat_map(u32::to_le_bytes)); + let size = (ex.fssm.len() - 16) as u32; + ex.fssm[8..12].copy_from_slice(&size.to_le_bytes()); + ex.resources.push(crate::psv::PsvResource { res_type: 7, space: 0, lower: 0, upper: 0 }); + let root = ex.root_sig.as_mut().unwrap(); + root.version = 2; + root.params.push(RootParam { visibility: 0, kind: RootParamKind::Table(vec![ + RootRange { range_type: 0, num: 1, base_register: 0, space: 0, offset_in_table: 0 }, + ]) }); + let hlsl = super::translate(&ex).unwrap().hlsl; + assert!(hlsl.contains("RWByteAddressBuffer raw_ubuf0 : register(u0)"), "{hlsl}"); + assert!(hlsl.contains("raw_ubuf0.Store("), "{hlsl}"); + + // Removing the independent user-data record leaves no proof for the uncovered slot. + ex.fssm[0xf8..0xfc].fill(0); + assert!(matches!(super::translate(&ex), Err(e) if e.contains("non-UAV table"))); + // An explicit SRV at slot 1 takes precedence even with corroborating metadata. + ex.fssm[0xf8..0xfc].copy_from_slice(&1u32.to_le_bytes()); + let RootParamKind::Table(ranges) = &mut ex.root_sig.as_mut().unwrap().params[0].kind else { unreachable!() }; + ranges[0].num = 2; + assert!(matches!(super::translate(&ex), Err(e) if e.contains("non-UAV table"))); +} + /// Locally constructed linear SRV, followed by both indexed address forms. /// Encodings produced by llvm-mc -mcpu=gfx1030. fn indexed_fixture() -> ShaderExtract { @@ -121,6 +158,20 @@ fn proven_byte_index_emits_addresses_without_widening_loads() { assert!(em.emit_mubuf(4, &ops[4]).unwrap_err().contains("stride")); } +#[test] +fn byte_index_accepts_commuted_stride_one_in_descriptor_high_word() { + let mut ex = indexed_fixture(); + // gfx1030: s_or_b32 s9, 0x10000, s13 + ex.isa[16..20].copy_from_slice(&0x8809_0dffu32.to_le_bytes()); + ex.isa_data.clone_from(&ex.isa); + let translated = super::translate(&ex).unwrap(); + assert_eq!(translated.hlsl.matches("raw_sbuf0.Load(").count(), 8); + println!("BEGIN_HLSL\n{}\nEND_HLSL", translated.hlsl); + ex.isa[20..24].copy_from_slice(&0x40000u32.to_le_bytes()); + ex.isa_data.clone_from(&ex.isa); + assert!(super::translate(&ex).is_err()); +} + #[test] fn indexed_descriptor_proof_does_not_cross_a_basic_block() { let mut ex = indexed_fixture(); diff --git a/tools/shader-compiler/src/hlsl/scalar_values.rs b/tools/shader-compiler/src/hlsl/scalar_values.rs new file mode 100644 index 00000000..d4e32f44 --- /dev/null +++ b/tools/shader-compiler/src/hlsl/scalar_values.rs @@ -0,0 +1,200 @@ +//! Forward SGPR analysis shared by static table offsets and read-lane selectors. +use super::{Emitter, Enc, Insn, Opnd}; +use crate::rdna2::clobbers_scalar; +use std::collections::{BTreeMap, VecDeque}; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Proof { + Exact, + UpperBound, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Value { + Exact(u32), + AtMost(u32), +} + +impl Value { + fn upper(self) -> u32 { + match self { + Self::Exact(n) | Self::AtMost(n) => n, + } + } + + fn exact(self) -> Option { + match self { + Self::Exact(n) => Some(n), + Self::AtMost(_) => None, + } + } + + fn join(self, other: Self, proof: Proof) -> Option { + if self == other { + Some(self) + } else if proof == Proof::UpperBound { + Some(Self::AtMost(self.upper().max(other.upper()))) + } else { + None + } + } +} + +pub(super) fn at_reads( + insns: &[Insn], + proof: Proof, + register_at: impl Fn(&Insn) -> Option, +) -> BTreeMap<(usize, u8), u32> { + if insns.is_empty() + || insns.len() > 32768 + || !insns.iter().any(|i| register_at(i).is_some()) + || insns.iter().any(|i| { + !i.is_complete() + || i.enc == Enc::Unknown + || i.mnemonic.contains('<') + || i.mnemonic.starts_with("s_movreld_") + || i.mnemonic.starts_with("s_subvector_loop_") + || (i.mnemonic.starts_with("s_cbranch_") && Emitter::branch_cond(i.op).is_none()) + || matches!( + i.mnemonic.as_str(), + "s_setpc_b64" + | "s_swappc_b64" + | "s_rfe_b64" + | "s_call_b64" + | "s_movrelsd_2_b32" + | "s_trap" + ) + }) + { + return BTreeMap::new(); + } + + type State = BTreeMap; + let mut input: Vec> = vec![None; insns.len()]; + input[0] = Some(State::new()); + let mut work = VecDeque::from([0]); + let mut iterations = 0usize; + while let Some(index) = work.pop_front() { + iterations += 1; + if iterations > insns.len() * 128 { + return BTreeMap::new(); + } + let ins = &insns[index]; + let incoming = input[index].as_ref().expect("reachable"); + let mut out = incoming.clone(); + out.retain(|®, _| !clobbers_scalar(ins, reg)); + let fact = |op: &Opnd| match op { + Opnd::Sgpr(r @ 0..=105) => incoming.get(r).copied(), + Opnd::ConstInt(v) => Some(Value::Exact(*v as u32)), + Opnd::Literal(v) => Some(Value::Exact(*v)), + _ => None, + }; + let value = |op: &Opnd| fact(op).and_then(Value::exact); + if let [Opnd::Sgpr(dst @ 0..=105)] = ins.dst.as_slice() { + let known = match (ins.mnemonic.as_str(), ins.src.as_slice()) { + ("s_mov_b32", [a]) => value(a), + ("s_add_u32" | "s_add_i32", [a, b]) => { + value(a).zip(value(b)).map(|(a, b)| a.wrapping_add(b)) + } + ("s_sub_u32" | "s_sub_i32", [a, b]) => { + value(a).zip(value(b)).map(|(a, b)| a.wrapping_sub(b)) + } + ("s_and_b32", [a, b]) => value(a).zip(value(b)).map(|(a, b)| a & b), + ("s_or_b32", [a, b]) => value(a).zip(value(b)).map(|(a, b)| a | b), + ("s_xor_b32", [a, b]) => value(a).zip(value(b)).map(|(a, b)| a ^ b), + ("s_lshl_b32", [a, b]) => value(a).zip(value(b)).map(|(a, b)| a << (b & 31)), + ("s_lshr_b32", [a, b]) => value(a).zip(value(b)).map(|(a, b)| a >> (b & 31)), + _ => None, + }; + let result = known.map(Value::Exact).or_else(|| { + if proof == Proof::Exact { + return None; + } + match (ins.mnemonic.as_str(), ins.src.as_slice()) { + ("s_mov_b32", [a]) => fact(a), + ("s_cmov_b32", [a]) => incoming.get(dst)?.join(fact(a)?, proof), + ("s_cselect_b32", [a, b]) => fact(a)?.join(fact(b)?, proof), + // AND can only clear bits, even if one input is unknown. + ("s_and_b32", [a, b]) => [fact(a), fact(b)] + .into_iter() + .flatten() + .map(Value::upper) + .min() + .map(Value::AtMost), + _ => None, + } + }); + if let Some(v) = result { + out.insert(*dst, v); + } + if proof == Proof::UpperBound && *dst <= 104 && *dst % 2 == 0 { + let operands = match (ins.mnemonic.as_str(), ins.src.as_slice()) { + ("s_mov_b64", [a]) => Some((a, None)), + ("s_cmov_b64", [a]) => Some((a, Some(&ins.dst[0]))), + ("s_cselect_b64", [a, b]) => Some((a, Some(b))), + _ => None, + }; + if let Some((source, alternate)) = operands { + // Both words read the incoming state even when a source aliases the destination. + for offset in 0..2 { + let word = |op: &Opnd| match op { + Opnd::Sgpr(r @ 0..=104) if r % 2 == 0 => { + incoming.get(&(r + offset)).copied() + } + Opnd::ConstInt(_) if offset == 0 => fact(op), + Opnd::ConstInt(_) => fact(&super::hi(op)), + _ => None, + }; + let value = word(source).and_then(|a| match alternate { + Some(b) => a.join(word(b)?, proof), + None => Some(a), + }); + if let Some(v) = value { + out.insert(dst + offset, v); + } + } + } + } + } + let mut merge = |next: usize| { + let Some(slot) = input.get_mut(next) else { + return; + }; + let mut joined = slot.clone().unwrap_or_else(|| out.clone()); + joined.retain(|r, v| { + if let Some(merged) = out.get(r).and_then(|&other| v.join(other, proof)) { + *v = merged; + true + } else { + false + } + }); + if slot.as_ref() != Some(&joined) { + *slot = Some(joined); + work.push_back(next); + } + }; + if ins.enc == Enc::Sopp && Emitter::branch_cond(ins.op).is_some() { + let target = ins.offset as i64 + 4 + 4 * ins.aux.imm; + let Ok(next) = insns.binary_search_by_key(&target, |i| i.offset as i64) else { + return BTreeMap::new(); + }; + merge(next); + if ins.op == 2 { + continue; + } + } + if ins.mnemonic != "s_endpgm" { + merge(index + 1); + } + } + let mut result = BTreeMap::new(); + for (ins, state) in insns.iter().zip(input) { + if let Some(reg) = register_at(ins) { + if let Some(v) = state.and_then(|s| s.get(®).copied()) { + result.insert((ins.offset, reg), v.upper()); + } + } + } + result +} diff --git a/tools/shader-compiler/src/hlsl/wave_cull.rs b/tools/shader-compiler/src/hlsl/wave_cull.rs index b6c9244e..948510fc 100644 --- a/tools/shader-compiler/src/hlsl/wave_cull.rs +++ b/tools/shader-compiler/src/hlsl/wave_cull.rs @@ -216,7 +216,7 @@ pub(super) fn emit(em: &mut Emitter<'_>, idx: usize, i: &Insn, target: Option { - if !em.hoist_wave_exchanges { em.line(&first_read(idx, i, false)?); } + if !em.hoist_wave_exchanges { em.line(&first_read(idx, i)?); } em.ws(&i.dst[0], &format!("first_value{idx}"))?; } "s_mov_b32" if matches!(i.dst.first(), Some(Opnd::ExecLo | Opnd::ExecHi)) => { @@ -254,20 +254,17 @@ pub(super) fn exchange(idx: usize, i: &Insn, mesh: bool) -> Result Ok(Some(format!("uint2 page_vcc{idx} = tb_page_ballot(tb_wave_tid, (vcc_lo & 1u) != 0u);"))), "v_permlanex16_b32" => Ok(Some(cross_row(idx, i)?)), - "v_readfirstlane_b32" => Ok(Some(first_read(idx, i, mesh)?)), + "v_readfirstlane_b32" => Ok(Some(first_read(idx, i)?)), "v_add_nc_u32" | "v_max_u32" | "v_add_f32" if matches!(i.src.first(), Some(Opnd::Raw(233 | 250))) => Ok(Some(dpp_read(idx, i)?.0)), _ => super::page_waves::rendezvous(idx, i), } } -fn first_read(idx: usize, i: &Insn, empty_mask_reads_lane_zero: bool) -> Result { +fn first_read(idx: usize, i: &Insn) -> Result { let value = r(&i.src[0])?; - let upper = format!("32u + uint(firstbitlow(first_mask{idx}.y))"); - let upper = if empty_mask_reads_lane_zero { - format!("first_mask{idx}.y != 0u ? {upper} : 0u") - } else { upper }; + // RDNA2 selects lane zero when EXEC is empty, even for a scalar write in compute. Ok(format!("uint2 first_mask{idx} = tb_page_ballot(tb_wave_tid, (exec_lo & 1u) != 0u); -uint first_lane{idx} = first_mask{idx}.x != 0u ? uint(firstbitlow(first_mask{idx}.x)) : {upper}; +uint first_lane{idx} = first_mask{idx}.x != 0u ? uint(firstbitlow(first_mask{idx}.x)) : first_mask{idx}.y != 0u ? 32u + uint(firstbitlow(first_mask{idx}.y)) : 0u; uint first_value{idx} = tb_page_read(tb_wave_tid, {value}, first_lane{idx});")) } @@ -298,3 +295,18 @@ fn dpp_read(idx: usize, i: &Insn) -> Result<(String, String), String> { }; Ok((format!("uint shifted{idx} = tb_page_read(tb_wave_tid, {src}, {lane});"), valid)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn readfirstlane_selects_lane_zero_when_both_exec_words_are_empty() { + // v_readfirstlane_b32 s28, v9 + let ops = crate::rdna2::disassemble(&0x7e38_0509u32.to_le_bytes()); + for mesh in [false, true] { + let code = exchange(0, &ops[0], mesh).unwrap().unwrap(); + assert!(code.contains("first_mask0.y != 0u ? 32u + uint(firstbitlow(first_mask0.y)) : 0u"), "{code}"); + } + } +} diff --git a/tools/shader-compiler/src/normalized_half.hlsl b/tools/shader-compiler/src/normalized_half.hlsl new file mode 100644 index 00000000..e7674a96 --- /dev/null +++ b/tools/shader-compiler/src/normalized_half.hlsl @@ -0,0 +1,23 @@ + +uint tb_norm_f16(uint bits, uint mode, bool signedResult) { + uint magnitude = bits & 0x7fffu; + bool negative = (bits & 0x8000u) != 0u; + if (magnitude > 0x7c00u || (negative && !signedResult)) return 0u; + if (magnitude < 0x400u && (mode & 0x40u) == 0u) return 0u; + + uint scale = signedResult ? 32767u : 65535u; + uint result = scale; + if (magnitude < 0x3c00u) { + // The scaled significand fits in 27 bits. Round this exact product + // once: rounding it to float first can create a false tie near 0.5. + uint exponent = magnitude >> 10; + uint significand = (magnitude & 1023u) + (exponent == 0u ? 0u : 1024u); + uint shift = 25u - max(exponent, 1u); + uint product = significand * scale; + result = product >> shift; + uint remainder = product & ((1u << shift) - 1u); + uint midpoint = 1u << (shift - 1u); + if (remainder > midpoint || (remainder == midpoint && (result & 1u) != 0u)) ++result; + } + return negative ? ((0u - result) & 0xffffu) : result; +} diff --git a/tools/shader-compiler/src/ray/alu.rs b/tools/shader-compiler/src/ray/alu.rs index 924c0179..0b1a680b 100644 --- a/tools/shader-compiler/src/ray/alu.rs +++ b/tools/shader-compiler/src/ray/alu.rs @@ -3,21 +3,9 @@ use super::operand; use crate::rdna2::{Enc, Insn, Opnd}; -pub(super) const HLSL: &str = r#" +pub(super) const HLSL: &str = concat!(include_str!("../float_to_integer.hlsl"), r#" uint tb_ray_ballot(bool active) { return WaveActiveBallot(active)[WaveGetLaneIndex() >> 5]; } uint tb_ray_first_lane() { return (WaveGetLaneIndex() & ~31u) + firstbitlow(tb_ray_ballot(true)); } -bool tb_ray_nan(uint bits) { return (bits & 0x7fffffffu) > 0x7f800000u; } -uint tb_ray_to_uint(float x) { - if (!(x > 0.0) || tb_ray_nan(asuint(x))) return 0u; - if (x >= 4294967296.0) return 0xffffffffu; - return uint(x); -} -uint tb_ray_to_int(float x) { - if (tb_ray_nan(asuint(x))) return 0u; - if (x >= 2147483648.0) return 0x7fffffffu; - if (x <= -2147483648.0) return 0x80000000u; - return asuint(int(x)); -} float tb_ray_legacy_mul(float a, float b) { if ((asuint(a) & 0x7fffffffu) == 0u || (asuint(b) & 0x7fffffffu) == 0u) return 0.0; return a * b; @@ -33,10 +21,17 @@ float tb_ray_legacy_mad(float a, float b, float c) { return sum; } float tb_ray_median(float a, float b, float c) { - if (tb_ray_nan(asuint(a)) || tb_ray_nan(asuint(b)) || tb_ray_nan(asuint(c))) + if (tb_nan_bits(asuint(a)) || tb_nan_bits(asuint(b)) || tb_nan_bits(asuint(c))) return min(min(a, b), c); return max(min(a, b), min(max(a, b), c)); } +float tb_ray_widen_half(uint bits) { + // f16tof32 may canonicalize NaNs on desktop GPUs. Keep the sign and + // payload while quieting signaling NaNs for IEEE-mode conversion. + if ((bits & 0x7fffu) > 0x7c00u) + return asfloat(((bits & 0x8000u) << 16u) | 0x7fc00000u | ((bits & 1023u) << 13u)); + return f16tof32(bits & 65535u); +} uint tb_ray_half(float value) { uint bits = asuint(value); uint sign = (bits >> 16) & 0x8000u; @@ -53,6 +48,23 @@ uint tb_ray_half(float value) { uint rounded = high + uint(remainder > mid || (remainder == mid && (high & 1u) != 0u)); return sign | (uint(max(0, exponent + 14)) * 1024u + rounded); } +uint tb_ray_mul24(uint a, uint b, bool signedOperands, bool highWord, bool clampResult) { + a = signedOperands ? asuint(asint(a << 8) >> 8) : a & 0xffffffu; + b = signedOperands ? asuint(asint(b << 8) >> 8) : b & 0xffffffu; + uint low = a * b; + if (!highWord && !clampResult) return low; + + // Split each operand into a low 16-bit digit and a signed or unsigned + // upper byte. The cross products and their sum fit in a signed dword. + int a0 = int(a & 65535u), b0 = int(b & 65535u); + int a1 = asint(a) >> 16, b1 = asint(b) >> 16; + int crossTerms = int((uint(a0) * uint(b0)) >> 16) + a1 * b0 + a0 * b1; + int high = a1 * b1 + (crossTerms >> 16); + if (highWord) return asuint(high); + if (!signedOperands) return high == 0 ? low : 0xffffffffu; + if (high == (asint(low) >> 31)) return low; + return high < 0 ? 0x80000000u : 0x7fffffffu; +} uint tb_ray_perm(uint a, uint b, uint selectors) { uint result = 0u; [unroll] for (uint i = 0u; i < 4u; ++i) { @@ -90,7 +102,7 @@ uint2 tb_ray_shift_right(uint2 pair, uint bits) { if (bits >= 32u) return uint2(pair.y >> (bits - 32u), 0u); return uint2((pair.x >> bits) | (pair.y << (32u - bits)), pair.y >> bits); } -"#; +"#, include_str!("../fract_f32.hlsl")); fn high_word(base: Opnd) -> Result { match base { @@ -100,13 +112,31 @@ fn high_word(base: Opnd) -> Result { } } +pub(super) fn sdwa_field(selector: u32) -> Option<(u32, u32)> { + match selector { + byte @ 0..=3 => Some((8, byte * 8)), + word @ 4..=5 => Some((16, (word - 4) * 16)), + 6 => Some((32, 0)), + _ => None, + } +} + +// Address and frame recognition may use the ordinary full-word semantics only +// when SDWA leaves the source words and destination unchanged in width. +pub(super) fn whole_sdwa_words(ins: &Insn) -> bool { + ins.aux.sdwa.is_none_or(|ext| { + let source_is_whole = |field: u32| matches!(field & 0x7f, 6 | 14); + matches!((ext >> 8) & 0xff, 6 | 14 | 22) + && source_is_whole(ext >> 16) + && (ins.src.len() < 2 || source_is_whole(ext >> 24)) + }) +} + fn sdwa_word(word: &str, field: u32) -> Result { - let (width, offset) = match field & 7 { - sel @ 0..=3 => (8, 8 * sel), - sel @ 4..=5 => (16, 16 * (sel - 4)), - 6 => return Ok(word.into()), - _ => return Err("reserved SDWA source selector".into()), - }; + let (width, offset) = sdwa_field(field & 7).ok_or("reserved SDWA source selector")?; + if width == 32 { + return Ok(word.into()); + } let mask = (1u32 << width) - 1; if field & 8 != 0 { Ok(format!( @@ -119,6 +149,102 @@ fn sdwa_word(word: &str, field: u32) -> Result { } } +fn widen_half(source: &Opnd, selector: u32, absolute: bool, negate: bool) -> Result { + let mut word = operand(source)?; + if matches!(source, Opnd::ConstF32(_)) { + word = format!("f32tof16(asfloat({word}))"); + } + let mut bits = sdwa_word(&word, selector)?; + if absolute { + bits = format!("({bits} & 0x7fffu)"); + } + if negate { + bits = format!("({bits} ^ 0x8000u)"); + } + Ok(format!("tb_ray_widen_half({bits})")) +} + +// Pack the low bits of an ALU result into the selected destination field. +fn sdwa_destination(dst: &str, value: &str, control: u32) -> Result { + let unused = control >> 3; + if unused > 2 { + return Err("unsupported SDWA destination control".into()); + } + let (width, shift) = sdwa_field(control & 7).ok_or("reserved SDWA destination selector")?; + if width == 32 { + return Ok(value.into()); + } + let mask = (1u32 << width) - 1; + let placed = format!("(({value} & {mask}u) << {shift}u)"); + Ok(match unused { + 1 => format!( + "asuint(asint({value} << {}u) >> {}u)", + 32 - width, + 32 - width - shift + ), + 2 => format!("({dst} & {:#010x}u) | {placed}", !(mask << shift)), + _ => placed, + }) +} + +pub(super) const SDWA_CLAMP: u32 = 1 << 5; + +pub(super) struct Mul24 { + signed: bool, + high: bool, + clamp: bool, +} + +impl Mul24 { + pub(super) fn decode(ins: &Insn) -> Option { + let (signed, high) = match ins.mnemonic.as_str() { + "v_mul_u32_u24" => (false, false), + "v_mul_i32_i24" => (true, false), + "v_mul_hi_u32_u24" => (false, true), + "v_mul_hi_i32_i24" => (true, true), + _ => return None, + }; + let clamp = match ins.enc { + Enc::Vop2 => ins.aux.sdwa.is_some_and(|ext| (ext >> 8) & SDWA_CLAMP != 0), + Enc::Vop3 => { + let clamp = ins.aux.imm != 0; + // Only the low product accepts VOP3 CLAMP. Neither form uses + // OP_SEL, floating source modifiers or output scaling. + if ins.raw[0] & 0x7800 != 0 || ins.aux.mask != 0 || ins.aux.imm2 != 0 + || (high && clamp) + { + return None; + } + clamp + } + _ => return None, + }; + Some(Self { signed, high, clamp }) + } + + fn hlsl(&self, a: &str, b: &str) -> String { + format!("tb_ray_mul24({a}, {b}, {}, {}, {})", self.signed, self.high, self.clamp) + } + + pub(super) fn fold(&self, a: u32, b: u32) -> u32 { + let extend = |x: u32| if self.signed { + i64::from(((x << 8) as i32) >> 8) + } else { + i64::from(x & 0xffffff) + }; + let product = extend(a) * extend(b); + if self.high { + (product >> 32) as u32 + } else if self.clamp && self.signed { + product.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as u32 + } else if self.clamp { + product.min(i64::from(u32::MAX)) as u32 + } else { + product as u32 + } + } +} + pub(super) fn vector(ins: &Insn) -> Result { let name = ins.mnemonic.as_str(); if name == "v_nop" { @@ -145,53 +271,97 @@ pub(super) fn vector(ins: &Insn) -> Result { "{dst} = (exec != 0u && {left} {cmp} {right}) ? ~0u : 0u;" )); } - if name == "v_cvt_f32_f16" && control == 6 && sdwa & 0xffc8_0000 == 0 { - let selected = sdwa_word(&raw(0)?, sdwa >> 16)?; - let mut value = format!("f16tof32({selected} & 65535u)"); + if name == "v_cvt_f32_f16" { + let src = source(0)?; + if sdwa & 0xff48_0000 != 0 || matches!(src, Opnd::Literal(_)) { + return Err(format!("unsupported SDWA source {sdwa:#x} for {name}")); + } + let selector = (sdwa >> 16) & 7; + let value = widen_half(src, selector, sdwa & (1 << 21) != 0, sdwa & (1 << 20) != 0)?; + let bits = if control & SDWA_CLAMP == 0 { + format!("asuint({value})") + } else if control & 7 < 4 { + // A widened half, including a propagated NaN, always has a zero + // low byte. Saturation to 0 or 1 also leaves that byte zero. + "0u".into() + } else if matches!(src, Opnd::ConstF32(_)) && selector >= 4 { + // Inline floating constants are normal halves, with a zero high word. + format!("asuint(saturate({value}))") + } else { + return Err("clamped half conversion needs the ray launch FP mode".into()); + }; + let packed = sdwa_destination(&dst, &bits, control & !SDWA_CLAMP)?; + return Ok(format!("{dst} = {packed};")); + } + let from_f32 = match name { + "v_cvt_f16_f32" => Some("tb_ray_half"), + "v_cvt_i32_f32" => Some("tb_cvt_i32_f32"), + "v_cvt_u32_f32" => Some("tb_cvt_u32_f32"), + _ => None, + }; + if let Some(convert) = from_f32 { + // Only source selection, ABS and NEG apply to this floating operand. + // SDWA has no trailing literal word. + if sdwa & 0xff48_0000 != 0 || matches!(source(0)?, Opnd::Literal(_)) { + return Err(format!("unsupported SDWA source {sdwa:#x} for {name}")); + } + let mut bits = sdwa_word(&raw(0)?, sdwa >> 16)?; if sdwa & (1 << 21) != 0 { - value = format!("abs({value})"); + bits = format!("({bits} & 0x7fffffffu)"); } if sdwa & (1 << 20) != 0 { - value = format!("(-{value})"); + bits = format!("({bits} ^ 0x80000000u)"); } - return Ok(format!("{dst} = asuint({value});")); - } - if name == "v_cvt_f16_f32" && control == 5 && sdwa >> 16 == 6 { - return Ok(format!("{dst} = tb_ray_half(asfloat({})) << 16u;", raw(0)?)); + let value = format!("{convert}(asfloat({bits}))"); + let packed = sdwa_destination(&dst, &value, control)?; + return Ok(format!("{dst} = {packed};")); } - if matches!(name, "v_cvt_u32_f32" | "v_cvt_i32_f32") && control <= 6 && sdwa >> 16 == 6 { - // Full float source, UNUSED_PAD destination. Select the low bits - // after conversion and zero all other bytes of the destination. - let convert = if name == "v_cvt_i32_f32" { "tb_ray_to_int" } else { "tb_ray_to_uint" }; - let converted = format!("{convert}(asfloat({}))", raw(0)?); - let packed = match control { - 0..=3 => format!("(({converted} & 255u) << {}u)", 8 * control), - 4 | 5 => format!("(({converted} & 65535u) << {}u)", 16 * (control - 4)), - _ => converted, + if matches!(name, "v_cvt_f32_i32" | "v_cvt_f32_u32") { + if sdwa & 0xff70_0000 != 0 || matches!(source(0)?, Opnd::Literal(_)) { + return Err(format!("unsupported SDWA source {sdwa:#x} for {name}")); + } + let selected = sdwa_word(&raw(0)?, sdwa >> 16)?; + let mut value = if name == "v_cvt_f32_i32" { + format!("float(asint({selected}))") + } else { + format!("float({selected})") }; + if control & SDWA_CLAMP != 0 { + value = format!("saturate({value})"); + } + let packed = sdwa_destination(&dst, &format!("asuint({value})"), control & !SDWA_CLAMP)?; return Ok(format!("{dst} = {packed};")); } - // Full DWORD destination, no saturation or floating-point modifiers. - if (sdwa >> 8) & 0xff != 6 || sdwa & 0x7070_0000 != 0 { - return Err(format!("unsupported SDWA control {sdwa:#x} for {name}")); + // Integer sources can select and sign-extend a field from either register. + if sdwa & 0x7070_0000 != 0 || ins.src.iter().any(|src| matches!(src, Opnd::Literal(_))) { + return Err(format!("unsupported SDWA source {sdwa:#x} for {name}")); } let a = sdwa_word(&raw(0)?, sdwa >> 16)?; - if name == "v_cvt_f32_u32" { - return Ok(format!("{dst} = asuint(float({a}));")); - } let b = sdwa_word(&raw(1)?, sdwa >> 24)?; - if name == "v_lshlrev_b32" { - return Ok(format!("{dst} = {b} << ({a} & 31u);")); + if let Some(mul) = Mul24::decode(ins) { + let packed = sdwa_destination(&dst, &mul.hlsl(&a, &b), control & !SDWA_CLAMP)?; + return Ok(format!("{dst} = {packed};")); } - let op = match name { - "v_add_nc_u32" => "+", - "v_sub_nc_u32" => "-", - "v_xor_b32" => "^", - "v_and_b32" => "&", - "v_or_b32" => "|", + let value = match name { + "v_min_i32" => format!("asuint(min(asint({a}), asint({b})))"), + "v_max_i32" => format!("asuint(max(asint({a}), asint({b})))"), + "v_min_u32" => format!("min({a}, {b})"), + "v_max_u32" => format!("max({a}, {b})"), + "v_lshlrev_b32" => format!("({b} << ({a} & 31u))"), + "v_lshrrev_b32" => format!("({b} >> ({a} & 31u))"), + "v_ashrrev_i32" => format!("(asuint(asint({b}) >> ({a} & 31u)))"), + "v_add_nc_u32" => format!("({a} + {b})"), + "v_sub_nc_u32" => format!("({a} - {b})"), + "v_xor_b32" => format!("({a} ^ {b})"), + "v_and_b32" => format!("({a} & {b})"), + "v_or_b32" => format!("({a} | {b})"), _ => return Err(format!("unsupported ray SDWA operation {name}")), }; - return Ok(format!("{dst} = {a} {op} {b};")); + let packed = sdwa_destination(&dst, &value, control)?; + return Ok(format!("{dst} = {packed};")); + } + if let Some(mul) = Mul24::decode(ins) { + return Ok(format!("{dst} = {};", mul.hlsl(&raw(0)?, &raw(1)?))); } if matches!(name, "v_swap_b32" | "v_movrels_b32" | "v_movreld_b32") { let (Opnd::Vgpr(d), Opnd::Vgpr(s)) = (dest, *source(0)?) else { @@ -298,19 +468,19 @@ pub(super) fn vector(ins: &Insn) -> Result { "gt" => format!("{left} > {right}"), "ge" => format!("{left} >= {right}"), "lg" if ty == "f32" => { - format!("!tb_ray_nan({a}) && !tb_ray_nan({b}) && {left} != {right}") + format!("!tb_nan_bits({a}) && !tb_nan_bits({b}) && {left} != {right}") } "neq" if ty == "f32" => { - format!("tb_ray_nan({a}) || tb_ray_nan({b}) || {left} != {right}") + format!("tb_nan_bits({a}) || tb_nan_bits({b}) || {left} != {right}") } "ngt" if ty == "f32" => { - format!("tb_ray_nan({a}) || tb_ray_nan({b}) || {left} <= {right}") + format!("tb_nan_bits({a}) || tb_nan_bits({b}) || {left} <= {right}") } "nge" if ty == "f32" => { - format!("tb_ray_nan({a}) || tb_ray_nan({b}) || {left} < {right}") + format!("tb_nan_bits({a}) || tb_nan_bits({b}) || {left} < {right}") } "nle" if ty == "f32" => { - format!("tb_ray_nan({a}) || tb_ray_nan({b}) || {left} > {right}") + format!("tb_nan_bits({a}) || tb_nan_bits({b}) || {left} > {right}") } _ => return Err(format!("unsupported ray comparison {name}")), }; @@ -376,7 +546,7 @@ pub(super) fn vector(ins: &Insn) -> Result { "v_max3_f32" => Some(format!("max(max({}, {}), {})", f(0)?, f(1)?, f(2)?)), "v_ceil_f32" => Some(format!("ceil({})", f(0)?)), "v_floor_f32" => Some(format!("floor({})", f(0)?)), - "v_fract_f32" => Some(format!("frac({})", f(0)?)), + "v_fract_f32" => Some(format!("tb_fract_f32({}, 0u)", f(0)?)), "v_rcp_f32" | "v_rcp_iflag_f32" => Some(format!("rcp({})", f(0)?)), "v_sqrt_f32" => Some(format!("sqrt({})", f(0)?)), "v_rsq_f32" => Some(format!("rsqrt({})", f(0)?)), @@ -390,19 +560,13 @@ pub(super) fn vector(ins: &Insn) -> Result { "v_cvt_f32_u32" => Some(format!("float({})", raw(0)?)), "v_cvt_f32_i32" => Some(format!("float(asint({}))", raw(0)?)), "v_cvt_f32_f16" => { - let shift = if ins.enc == Enc::Vop3 && ins.raw[0] & (1 << 11) != 0 { - 16 - } else { - 0 - }; - let mut value = format!("f16tof32(({} >> {shift}u) & 65535u)", raw(0)?); - if ins.aux.mask & 1 != 0 { - value = format!("abs({value})"); - } - if ins.aux.mask & 8 != 0 { - value = format!("(-{value})"); - } - Some(value) + let high = ins.enc == Enc::Vop3 && ins.raw[0] & (1 << 11) != 0; + Some(widen_half( + source(0)?, + if high { 5 } else { 6 }, + ins.aux.mask & 1 != 0, + ins.aux.mask & 8 != 0, + )?) } "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { let shift = (name.as_bytes()[name.len() - 1] - b'0') * 8; @@ -446,9 +610,9 @@ pub(super) fn vector(ins: &Insn) -> Result { }; format!("({condition} != 0u) ? {} : {}", bits(1)?, bits(0)?) } - "v_cvt_u32_f32" => format!("tb_ray_to_uint({})", f(0)?), - "v_cvt_i32_f32" => format!("tb_ray_to_int({})", f(0)?), - "v_cvt_f16_f32" if ins.enc == Enc::Vop1 => format!("tb_ray_half({})", f(0)?), + "v_cvt_u32_f32" => format!("tb_cvt_u32_f32({})", f(0)?), + "v_cvt_i32_f32" => format!("tb_cvt_i32_f32({})", f(0)?), + "v_cvt_f16_f32" if ins.enc == Enc::Vop1 => format!("({dst} & 0xffff0000u) | tb_ray_half({})", f(0)?), "v_perm_b32" => format!("tb_ray_perm({}, {}, {})", raw(0)?, raw(1)?, raw(2)?), "v_and_b32" => format!("{} & {}", raw(0)?, raw(1)?), "v_or_b32" => format!("{} | {}", raw(0)?, raw(1)?), @@ -468,7 +632,6 @@ pub(super) fn vector(ins: &Insn) -> Result { "v_min_u32" => format!("min({}, {})", raw(0)?, raw(1)?), "v_max_u32" => format!("max({}, {})", raw(0)?, raw(1)?), "v_ffbl_b32" => format!("firstbitlow({})", raw(0)?), - "v_mul_u32_u24" => format!("({} & 0xffffffu) * ({} & 0xffffffu)", raw(0)?, raw(1)?), "v_mad_u32_u24" => format!( "({} & 0xffffffu) * ({} & 0xffffffu) + {}", raw(0)?, diff --git a/tools/shader-compiler/src/ray/continuation/layout.rs b/tools/shader-compiler/src/ray/continuation/layout.rs index 6007725f..03d1c9eb 100644 --- a/tools/shader-compiler/src/ray/continuation/layout.rs +++ b/tools/shader-compiler/src/ray/continuation/layout.rs @@ -1,6 +1,6 @@ //! Validate native scheduler and stack ABI and locate the title's separately //! callable continuations. The trailing program word encodes its own extent. -use super::super::fingerprint; +use super::super::{alu::whole_sdwa_words, fingerprint}; use super::target; use crate::rdna2::{Enc, Insn, Opnd, instructions}; use std::ops::Range; @@ -26,6 +26,9 @@ fn immediate(arg: &Opnd) -> Option { fn frame_adjustment(code: &[Insn], index: usize) -> Option { let ins = &code[index]; + if !whole_sdwa_words(ins) { + return None; + } let [arg, base @ Opnd::Vgpr(_)] = ins.src.as_slice() else { return None; }; @@ -50,6 +53,7 @@ fn frame_adjustment(code: &[Insn], index: usize) -> Option { || op.dst.contains(&Opnd::Vgpr(7)) })?; if copy.mnemonic != "v_mov_b32" + || !whole_sdwa_words(copy) || copy.dst.as_slice() != [*base] || copy.src != [Opnd::Vgpr(7)] || code @@ -373,6 +377,17 @@ impl Layout { mod tests { use super::*; + #[test] + fn partial_stack_pointer_add_is_not_a_full_frame_adjustment() { + let delta = |ext: u32| { + let bytes: Vec<_> = [0x4a0e_0ef9, ext].into_iter().flat_map(u32::to_le_bytes).collect(); + frame_adjustment(&instructions(&bytes).collect::>(), 0) + }; + // v7 += 32 with DWORD and WORD_0 destinations respectively. + assert_eq!(delta(0x0686_16a0), Some(32)); + assert_eq!(delta(0x0686_14a0), None); + } + fn symbols(names: &[(&str, u32)]) -> Vec { let mut bytes = vec![0; 0x40 + names.len() * 24]; bytes[0x38..0x3c].copy_from_slice(&(names.len() as u32).to_le_bytes()); diff --git a/tools/shader-compiler/src/ray/continuation/tests.rs b/tools/shader-compiler/src/ray/continuation/tests.rs index 6ae9e33a..60fe8a8a 100644 --- a/tools/shader-compiler/src/ray/continuation/tests.rs +++ b/tools/shader-compiler/src/ray/continuation/tests.rs @@ -61,6 +61,137 @@ fn crossing_back_edges_dispatch_and_invalid_edges_fail() { assert!(lift(&[NOP]).is_err()); // fallthrough } +#[test] +fn compact_f32_to_f16_preserves_the_upper_word() { + // v_cvt_f16_f32 v4,v1; v_cvt_f16_f32 v4,v4. Even with aliased + // operands, conversion reads the old word before replacing its low half. + let hlsl = lift(&[0x7e08_1501, 0x7e08_1504, RETURN]).unwrap(); + assert!(hlsl.contains("v[4] = (v[4] & 0xffff0000u) | tb_ray_half(asfloat(v[1]));")); + assert!(hlsl.contains("v[4] = (v[4] & 0xffff0000u) | tb_ray_half(asfloat(v[4]));")); +} + +#[test] +fn sdwa_f32_to_f16_places_the_converted_bits_in_the_destination() { + let convert = |extension| lift(&[0x7e08_14f9, extension, RETURN]); + // BYTE_1 PRESERVE, WORD_0 SEXT, and DWORD PAD. + let preserve = convert(0x0006_1101).unwrap(); + assert!(preserve.contains("(v[4] & 0xffff00ffu)")); + assert!(preserve.contains("(tb_ray_half(asfloat(v[1])) & 255u) << 8u")); + let extend = convert(0x0006_0c01).unwrap(); + assert!(extend.contains("asint(tb_ray_half(asfloat(v[1])) << 16u) >> 16u")); + assert!(convert(0x0006_0601).unwrap().contains("v[4] = tb_ray_half(asfloat(v[1]));")); + // Reserved selector, reserved unused mode, and unhandled output modifiers. + for extension in [0x0006_0701, 0x0006_1801, 0x0006_2001, 0x0006_4001] { + assert!(convert(extension).is_err()); + } +} + +#[test] +fn sdwa_integer_conversions_apply_float_modifiers_before_packing() { + // Convert -abs(v1) to signed, replacing only WORD_0 in v4. + let signed = lift(&[0x7e08_10f9, 0x0036_1401, RETURN]).unwrap(); + assert!(signed.contains("(v[4] & 0xffff0000u)")); + assert!(signed.contains("tb_cvt_i32_f32(asfloat(((v[1] & 0x7fffffffu) ^ 0x80000000u)))")); + // Convert v1 to unsigned, replacing only BYTE_3 in v4. + let unsigned = lift(&[0x7e08_0ef9, 0x0006_1301, RETURN]).unwrap(); + assert!(unsigned.contains("(v[4] & 0x00ffffffu)")); + assert!(unsigned.contains("(tb_cvt_u32_f32(asfloat(v[1])) & 255u) << 24u")); +} + +#[test] +fn sdwa_integer_to_float_extends_before_conversion_and_clamps_before_writing() { + // Signed WORD_1 source: a negative high half must convert to a negative float. + let signed = lift(&[0x7e08_0af9, 0x000d_0601, RETURN]).unwrap(); + assert!(signed.contains("float(asint(")); + assert!(signed.contains("asint((v[1]) << 0u) >> 16u")); + // Unsigned DWORD source: clamp the float, then copy its low byte to BYTE_3. + let unsigned = lift(&[0x7e08_0cf9, 0x0006_3301, RETURN]).unwrap(); + assert!(unsigned.contains("(v[4] & 0x00ffffffu)")); + assert!(unsigned.contains("(asuint(saturate(float(v[1]))) & 255u) << 24u")); + assert!(lift(&[0x7e08_0cf9, 0x0006_4601, RETURN]).is_err()); // output scale +} + +#[test] +fn widening_an_inline_half_uses_half_precision_before_subword_selection() { + let compact = lift(&[0x7e08_16f2, RETURN]).unwrap(); // 1.0 + assert!(compact.contains("tb_ray_widen_half(f32tof16(asfloat(0x3f800000u)))")); + let high = lift(&[0x7e08_16f9, 0x0085_06f2, RETURN]).unwrap(); + assert!(high.contains("(f32tof16(asfloat(0x3f800000u))) >> 16u")); + let packed = lift(&[0x7e08_16f9, 0x0036_1501, RETURN]).unwrap(); + assert!(packed.contains("(v[4] & 0x0000ffffu)")); + assert!(packed.contains("tb_ray_widen_half(((v[1] & 0x7fffu) ^ 0x8000u))")); +} + +#[test] +fn sdwa_clamped_half_writes_only_launch_mode_independent_results() { + let convert = |ext| lift(&[0x7e08_16f9, ext, RETURN]); + // The low byte of any widened and saturated half is zero. + let byte = convert(0x0006_3201).unwrap(); // BYTE_2, PRESERVE + assert!(byte.contains("(v[4] & 0xff00ffffu)")); + assert!(!byte.contains("tb_ray_widen_half")); + let constant = convert(0x0086_26f0).unwrap(); // 0.5, DWORD + assert!(constant.contains("saturate(tb_ray_widen_half(")); + // A register can contain a NaN whose clamped result depends on DX10_CLAMP. + for ext in [0x0006_2601, 0x0015_3501, 0x0007_3201, 0x0006_7201] { + assert!(convert(ext).is_err()); + } +} + +#[test] +fn sdwa_binary_ops_write_the_selected_byte_after_evaluating_both_sources() { + // v4 = op(v1, v5), BYTE_1 with UNUSED_PRESERVE. + for (opcode, value) in [ + (0x3608_0af9, "v[1] & v[5]"), + (0x3808_0af9, "v[1] | v[5]"), + (0x3a08_0af9, "v[1] ^ v[5]"), + (0x4a08_0af9, "v[1] + v[5]"), + (0x4c08_0af9, "v[1] - v[5]"), + (0x3408_0af9, "v[5] << (v[1] & 31u)"), + (0x2c08_0af9, "v[5] >> (v[1] & 31u)"), + (0x3008_0af9, "asuint(asint(v[5]) >> (v[1] & 31u))"), + ] { + let hlsl = lift(&[opcode, 0x0606_1101, RETURN]).unwrap(); + assert!(hlsl.contains("(v[4] & 0xffff00ffu)")); + assert!(hlsl.contains(&format!("(({value}) & 255u) << 8u"))); + } + // Unsupported output scale and reserved source selector. + assert!(lift(&[0x3608_0af9, 0x0606_5101, RETURN]).is_err()); + assert!(lift(&[0x3608_0af9, 0x0706_1101, RETURN]).is_err()); +} + +#[test] +fn mul24_selects_signedness_result_word_and_saturation() { + for (encoding, flags) in [ + (vec![0x1208_0b01], "true, false, false"), + (vec![0x1808_0b01], "false, true, false"), + (vec![0xd50b_8004, 0x0002_0b01], "false, false, true"), + (vec![0x1408_0af9, 0x0606_1101], "true, true, false"), + ] { + let mut words = encoding; + words.push(RETURN); + let shader = lift(&words).unwrap(); + assert!(shader.contains(&format!("tb_ray_mul24(v[1], v[5], {flags})"))); + if words[0] == 0x1408_0af9 { + assert!(shader.contains("v[4] & 0xffff00ffu")); + } + } + // VOP3 integer multiply has no output scaling. + assert!(lift(&[0xd50b_0004, 0x0802_0b01, RETURN]).is_err()); +} + +#[test] +fn sdwa_minmax_compares_full_values_before_writing_the_selected_byte() { + for (opcode, expr) in [ + (0x2208_0af9, "asuint(min(asint(v[1]), asint(v[5])))"), + (0x2408_0af9, "asuint(max(asint(v[1]), asint(v[5])))"), + (0x2608_0af9, "min(v[1], v[5])"), + (0x2808_0af9, "max(v[1], v[5])"), + ] { + let hlsl = lift(&[opcode, 0x0606_1101, RETURN]).unwrap(); + assert!(hlsl.contains(&format!("(v[4] & 0xffff00ffu) | (({expr} & 255u) << 8u)"))); + } +} + #[test] fn consecutive_vector_moves_share_the_guard_until_exec_changes() { let move_v29 = 0x7e3a_0280; // v_mov_b32 v29, 0 diff --git a/tools/shader-compiler/src/ray/resources/material.rs b/tools/shader-compiler/src/ray/resources/material.rs index 3a882925..5bb572ac 100644 --- a/tools/shader-compiler/src/ray/resources/material.rs +++ b/tools/shader-compiler/src/ray/resources/material.rs @@ -4,6 +4,7 @@ mod image; mod relative; use super::{Bindings, local_record}; +use crate::ray::alu::{Mul24, SDWA_CLAMP, sdwa_field, whole_sdwa_words}; use crate::rdna2::{Enc, Insn, Opnd, instructions}; use std::{collections::BTreeMap, fmt::Write, ops::Range}; use tuxbox_dxbc::ray::State; @@ -66,10 +67,75 @@ impl Values { Some(u64::from(self.words[k]?) | (u64::from(self.words[k + 1]?) << 32)) } + fn sdwa_alu(&self, ins: &Insn, ext: u32) -> Option { + if ins.enc != Enc::Vop2 || ext & 0x7070_0000 != 0 { + return None; + } + let read = |op: &Opnd, field: u32| { + let word = match op { + Opnd::Literal(_) => return None, // SDWA has no trailing literal word + Opnd::ConstF32(f) => f.to_bits(), + Opnd::Null => 0, + _ => self.get(op)?, + }; + let (width, offset) = sdwa_field(field & 7)?; + let aligned = word << (32 - width - offset); + Some(if field & 8 == 0 { + aligned >> (32 - width) + } else { + ((aligned as i32) >> (32 - width)) as u32 + }) + }; + let a = read(ins.src.first()?, ext >> 16)?; + let b = read(ins.src.get(1)?, ext >> 24)?; + let mut control = (ext >> 8) & 255; + let value = match ins.mnemonic.as_str() { + "v_min_i32" => (a as i32).min(b as i32) as u32, + "v_max_i32" => (a as i32).max(b as i32) as u32, + "v_min_u32" => a.min(b), + "v_max_u32" => a.max(b), + "v_lshlrev_b32" => b.wrapping_shl(a), + "v_lshrrev_b32" => b.wrapping_shr(a), + "v_ashrrev_i32" => (b as i32).wrapping_shr(a) as u32, + "v_add_nc_u32" => a.wrapping_add(b), + "v_sub_nc_u32" => a.wrapping_sub(b), + "v_and_b32" => a & b, + "v_or_b32" => a | b, + "v_xor_b32" => a ^ b, + _ => { + let mul = Mul24::decode(ins)?; + control &= !SDWA_CLAMP; + mul.fold(a, b) + } + }; + let (width, offset) = sdwa_field((ext >> 8) & 7)?; + let mask = u32::MAX >> (32 - width); + let placed = (value & mask) << offset; + match control >> 3 { + 0 => Some(placed), + 1 => Some((((value << (32 - width)) as i32) >> (32 - width - offset)) as u32), + 2 if width == 32 => Some(value), + 2 => Some((self.get(ins.dst.first()?)? & !(mask << offset)) | placed), + _ => None, + } + } + fn alu(&self, ins: &Insn) -> [Option; 2] { + if let Some(ext) = ins.aux.sdwa { + let value = self.sdwa_alu(ins, ext); + // Identity selectors also allow existing whole-word folds, e.g. MOV. + if value.is_some() || !whole_sdwa_words(ins) + || ins.src.iter().any(|op| matches!(op, Opnd::Literal(_))) + { + return [value, None]; + } + } let x = ins.src.first().and_then(|x| self.get(x)); let y = ins.src.get(1).and_then(|x| self.get(x)); let z = ins.src.get(2).and_then(|x| self.get(x)); + if let Some(mul) = Mul24::decode(ins) { + return [x.zip(y).map(|(a, b)| mul.fold(a, b)), None]; + } if ins.mnemonic == "s_getpc_b64" { return [ Some(super::super::continuation::CODE_BASE + (ins.offset + ins.dwords * 4) as u32), @@ -496,7 +562,7 @@ impl Layout { if let Some(k) = dst { regs.words.get_mut(k..k + n)?.copy_from_slice(&words[..n]); regs.code_address.get_mut(k..k + n)?.fill(false); - regs.code_address[k] = is_table_pointer; + regs.code_address[k] = is_table_pointer && whole_sdwa_words(ins); } Some(()) } @@ -658,6 +724,73 @@ mod tests { instruction } + #[test] + fn mul24_folds_signed_overflow_and_preserves_adjacent_bytes() { + let mut regs = Values::new(); + regs.words[129] = Some(0xab80_0000); // -2^23, or +2^23 unsigned + regs.words[133] = Some(257); + regs.words[132] = Some(0xaabb_ccdd); + for (op, ext, expected) in [ + (0xd509_8004, 0x0002_0b01, 0x8000_0000), // signed saturation + (0xd50b_8004, 0x0002_0b01, 0x8080_0000), // unsigned fits + (0x1408_0af9, 0x0606_1101, 0xaabb_ffdd), // signed high word + (0x1808_0af9, 0x0606_1101, 0xaabb_00dd), // unsigned high word + ] { + assert_eq!(regs.alu(&decode(&[op, ext]))[0], Some(expected)); + } + // 65536 squared is the first value above the unsigned dword range. + regs.words[129] = Some(65536); + regs.words[133] = Some(65536); + assert_eq!(regs.alu(&decode(&[0xd50b_8004, 0x0002_0b01]))[0], Some(u32::MAX)); + assert_eq!(regs.alu(&decode(&[0xd50b_0004, 0x0002_0b01]))[0], Some(0)); + } + + #[test] + fn sdwa_minmax_folds_using_the_instruction_signedness() { + let mut regs = Values::new(); + regs.words[129] = Some(0x8000_00fe); + regs.words[133] = Some(0x7fff_ff01); + regs.words[132] = Some(0xaabb_ccdd); + for (opcode, expected) in [ + (0x2208_0af9, 0xaabb_fedd), // signed minimum + (0x2408_0af9, 0xaabb_01dd), // signed maximum + (0x2608_0af9, 0xaabb_01dd), // unsigned minimum + (0x2808_0af9, 0xaabb_fedd), // unsigned maximum + ] { + assert_eq!(regs.alu(&decode(&[opcode, 0x0606_1101]))[0], Some(expected)); + } + } + + #[test] + fn sdwa_right_shift_preserves_the_material_descriptor_bank() { + let mut regs = Values::new(); + let mut layout = Layout::default(); + regs.words[129] = Some(33); + regs.words[133] = Some(0x8000_0040); + regs.words[132] = Some(SRV); + // v_lshrrev_b32 v4,v1,v5: replace only BYTE_0 of the SRV address. + let shift = decode(&[0x2c08_0af9, 0x0606_1001]); + layout.instruction(&shift, &mut regs).unwrap(); + assert_eq!(regs.words[132], Some(SRV + 32)); + let address = regs.words[132].unwrap(); + assert_eq!(layout.resource(address, SRV, View::Structured).as_deref(), Some("tbSrv1")); + regs.words[132] = None; + layout.instruction(&shift, &mut regs).unwrap(); + assert_eq!(regs.words[132], None); + } + + #[test] + fn sdwa_add_does_not_carry_pointer_provenance_through_a_partial_write() { + let mut layout = Layout::default(); + let mut regs = Values::new(); + regs.code_address[129] = true; + let add = |ext| decode(&[0x4a08_0af9, ext]); + layout.instruction(&add(0x0606_0601), &mut regs).unwrap(); + assert!(regs.code_address[132]); + layout.instruction(&add(0x0606_1101), &mut regs).unwrap(); + assert!(!regs.code_address[132]); + } + #[test] fn flat_three_word_read_preserves_adjacent_live_descriptor() { let mut regs = Values::new();