mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 12:08:36 +00:00
In Gen.buffer_address (tools/rdna2spirv.py), emit `OpShiftRightLogical %ulong wide %c64_32` followed by `OpIEqual %bool hi_w %cl0` instead of `OpULessThanEqual %bool wide %clffffffff`. NVIDIA 580.82.07 NVVM aborts pipeline creation (`NVVM compilation failed: 3`, VkResult -13) on the unsigned 64-bit compare when a literal V# folds `wide` to `0 + idx * stride` (reported and A/B-tested on L4 by @kevincommits in ubiquitarianism/leonida#1608#issuecomment-7208330785). Over uint64, `(wide >> 32) == 0` is mathematically identical to `wide <= 0xFFFFFFFF`. Since lower_addr64 (SHADER-423), the 64-bit compare still reaches the driver with --int64-addresses, and by default in any module the lowering leaves in its Int64 form (a 64-bit scalar op such as s_lshl_b64 elsewhere in the shader). Where the lowering does apply, the new form lowers to a high-word `== 0` test, without the pair compare's redundant low-word `<= 0xFFFFFFFF` term. tests/semantic/test_buffer_offset_wrap.py runs every access (including the exact 32-bit boundary cases: `0xFFFFFFFC` dword, `0xFFFFFFFF` byte vs `0x1_0000_0000`) three ways: lowered (default), --int64-addresses, and default with Int64 kept. It checks that no compare with the 32-bit limit is emitted in any of them (raw and after spirv_opt.optimize), that the Int64 forms test `(wide >> 32) == 0`, and that the modules pass spirv-val when it is on PATH. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
268 lines
13 KiB
Python
268 lines
13 KiB
Python
"""A buffer offset that does not fit 32 bits is out of range in every OOB_SELECT mode.
|
|
|
|
The hardware adds index * stride (a full product) and soffset to the 48-bit V# base without wrapping at 32 bits, so
|
|
an index of 0xFFFFFFFF with a 20-byte stride lands far outside the buffer and the access has no effect. A translator
|
|
that keeps the offset in 32 bits turns the same access into base - 20, which is inside a view that covers a whole
|
|
pool: OOB_SELECT 3 does not check the index and 2 checks nothing. (Rule and hardware observation: five-star-recomp,
|
|
commit b9b57e2. The expected memory below is written out by hand.)
|
|
|
|
The fit test is `(wide >> 32) == 0`, not `wide <= 0xFFFFFFFF`: NVIDIA 580.82.07's NVVM fails pipeline creation
|
|
(`NVVM compilation failed: 3`, VkResult -13) on that unsigned 64-bit compare when a literal V# folds `wide` to
|
|
`0 + idx * stride`. Every access runs three ways: with lower_addr64 (the default, 32-bit pairs), with
|
|
--int64-addresses, and by default in a module the lowering leaves in its Int64 form (a 64-bit scalar op elsewhere in
|
|
the shader), where a 64-bit compare would reach the driver.
|
|
|
|
python -I tests/semantic/test_buffer_offset_wrap.py -v
|
|
"""
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
ROOT = os.path.dirname(os.path.dirname(HERE))
|
|
TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
|
|
|
|
sys.dont_write_bytecode = True
|
|
if TOOLS_DIR not in sys.path:
|
|
sys.path.insert(0, TOOLS_DIR)
|
|
if HERE not in sys.path:
|
|
sys.path.insert(0, HERE)
|
|
|
|
import rdna2spirv
|
|
import spirv_opt
|
|
from spirv_mini_interp import run_workgroup
|
|
from test_loop_ballot_barrier import _translate_cs
|
|
|
|
BASE, OUTPUT = 0x4000, 0x8000
|
|
STRIDE, BYTES = 20, 4096
|
|
LANES = 32
|
|
RAW, DISABLED, STRUCTURED_OFFSET = 0x31016FAC, 0x21016FAC, 0x01016FAC
|
|
SENTINEL, VALUE = 0xA5A5A5A5, 77
|
|
|
|
|
|
def indexed(index, literal_word3=None, stride=STRIDE, records=BYTES):
|
|
"""Store VALUE at `index` of the view in s[0:3], load it back and write what was read to the output view."""
|
|
lines = []
|
|
view = "s[0:3]"
|
|
if literal_word3 is not None:
|
|
# The same descriptor from immediates, which the translator folds: the mode is known when translating.
|
|
lines += [f"s_mov_b32 s8, {BASE:#x}", f"s_mov_b32 s9, {stride << 16:#x}", f"s_mov_b32 s10, {records:#x}",
|
|
f"s_mov_b32 s11, {literal_word3:#x}"]
|
|
view = "s[8:11]"
|
|
return lines + [
|
|
f"v_mov_b32_e32 v1, {index}",
|
|
f"v_mov_b32_e32 v2, {VALUE}",
|
|
f"buffer_store_dword v2, v1, {view}, 0 idxen",
|
|
f"buffer_load_dword v3, v1, {view}, 0 idxen",
|
|
"v_lshlrev_b32_e32 v4, 2, v0",
|
|
"buffer_store_dword v3, v4, s[4:7], 0 offen",
|
|
"s_endpgm"]
|
|
|
|
|
|
def soffset_case(voff, soff, byte=False):
|
|
"""Store VALUE at voff + soff in s[0:3], load it back and write what was read to the output view."""
|
|
store_op = "buffer_store_byte" if byte else "buffer_store_dword"
|
|
load_op = "buffer_load_ubyte" if byte else "buffer_load_dword"
|
|
return [
|
|
f"v_mov_b32_e32 v1, {voff}",
|
|
f"v_mov_b32_e32 v2, {VALUE}",
|
|
f"s_mov_b32 s12, {soff}",
|
|
f"{store_op} v2, v1, s[0:3], s12 offen",
|
|
f"{load_op} v3, v1, s[0:3], s12 offen",
|
|
"v_lshlrev_b32_e32 v4, 2, v0",
|
|
"buffer_store_dword v3, v4, s[4:7], 0 offen",
|
|
"s_endpgm"]
|
|
|
|
|
|
# off = 0xFFFFFFF0 (32-bit, as the hardware forms it), then soffset 0x20 is added in 64 bits: 0x1_0000_0010.
|
|
SOFFSET = soffset_case(-16, 32)
|
|
|
|
# A 64-bit scalar data op on registers the accesses don't use: lower_addr64 leaves such a module in its Int64 form
|
|
# even by default (test_addr64_lowering.py, test_a_64bit_data_op_keeps_int64).
|
|
DATA64 = ["s_mov_b32 s16, 1", "s_mov_b32 s17, 0", "s_lshl_b64 s[16:17], s[16:17], 4"]
|
|
|
|
# (name, lower_addr64 on, program prefix, module keeps Int64)
|
|
CONFIGS = (("lowered", True, [], False), ("int64-addresses", False, [], True), ("kept Int64", True, DATA64, True))
|
|
|
|
# The unsigned 64-bit bound compare in the Int64 form, and lower_addr64's image of `wide <= 0xFFFFFFFF` (the low
|
|
# word compared with 0xFFFFFFFF after the high-word test).
|
|
U64_LIMIT_COMPARES = (r"OpULessThanEqual %bool %\S+ %clffffffff\b", r"OpULessThan %bool %\S+ %cl100000000\b")
|
|
PAIR_LIMIT_COMPARE = r"OpULessThanEqual %bool %\S+ %a64c_ffffffff\b"
|
|
|
|
SPIRV_AS, SPIRV_VAL = shutil.which("spirv-as"), shutil.which("spirv-val")
|
|
|
|
|
|
def translate(name, lines, lowered=True):
|
|
"""_translate_cs with lower_addr64 on (the default) or off (--int64-addresses)."""
|
|
saved = rdna2spirv.ADDR_PAIR
|
|
rdna2spirv.ADDR_PAIR = lowered
|
|
try:
|
|
module, _ = _translate_cs(name, lines, threads=LANES)
|
|
finally:
|
|
rdna2spirv.ADDR_PAIR = saved
|
|
return module
|
|
|
|
|
|
def spirv_val_errors(text):
|
|
"""Assemble and validate for Vulkan 1.2; returns the tool's error text, or "" when the module is valid."""
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
src, spv = os.path.join(tmp, "module.spvasm"), os.path.join(tmp, "module.spv")
|
|
with open(src, "w", encoding="utf-8", newline="\n") as f:
|
|
f.write(text)
|
|
for tool, args in ((SPIRV_AS, [src, "-o", spv]), (SPIRV_VAL, [spv])):
|
|
r = subprocess.run([tool, "--target-env", "vulkan1.2"] + args, capture_output=True, text=True)
|
|
if r.returncode:
|
|
return f"{os.path.basename(tool)}: {r.stdout}{r.stderr}"
|
|
return ""
|
|
|
|
|
|
class BufferOffsetWrapTests(unittest.TestCase):
|
|
"""The accesses with lower_addr64, the default."""
|
|
LOWERED, PREFIX, INT64 = True, [], False
|
|
|
|
def run_case(self, lines, word3, stride=STRIDE, records=BYTES, extra_addresses=()):
|
|
module = translate("cs_buffer_offset_wrap", self.PREFIX + lines, self.LOWERED)
|
|
self.assertEqual("OpCapability Int64" in module, self.INT64) # the address form this class is about
|
|
memory = {address: SENTINEL for address in range(BASE - 64, BASE + 128, 4)}
|
|
for address in extra_addresses:
|
|
memory[address] = SENTINEL
|
|
before = dict(memory)
|
|
result = run_workgroup(
|
|
module, LANES, LANES,
|
|
inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i, "%local_index": i},
|
|
push_constants=[BASE, stride << 16, records, word3, OUTPUT, 0, LANES * 4, RAW] + [0] * 24,
|
|
memory=memory)
|
|
view = {address: result[address] for address in before}
|
|
return view, before, [result[OUTPUT + 4 * lane] for lane in range(LANES)]
|
|
|
|
def test_index_inside_the_buffer_is_stored_and_read(self):
|
|
for name, word3, literal in (("raw", RAW, None), ("raw literal", RAW, RAW),
|
|
("disabled", DISABLED, None), ("disabled literal", DISABLED, DISABLED)):
|
|
with self.subTest(mode=name):
|
|
view, before, read = self.run_case(indexed(2, literal), word3)
|
|
before[BASE + 2 * STRIDE] = VALUE
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [VALUE] * LANES)
|
|
|
|
def test_index_whose_product_with_the_stride_passes_32_bits_has_no_effect(self):
|
|
# 0xFFFFFFFF * 20 = 0x13_FFFF_FFEC; modulo 2^32 it would be the 20 bytes below the base.
|
|
for name, word3, literal in (("raw", RAW, None), ("raw literal", RAW, RAW), ("disabled", DISABLED, None),
|
|
("disabled literal", DISABLED, DISABLED)):
|
|
with self.subTest(mode=name):
|
|
view, before, read = self.run_case(indexed(-1, literal), word3)
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [0] * LANES)
|
|
|
|
def test_32bit_boundary_fits_and_first_overflow_is_rejected(self):
|
|
top_aligned = 0xFFFFFFFC
|
|
for name, literal in (("disabled", None), ("disabled literal", DISABLED)):
|
|
with self.subTest(kind="idxen", mode=name, edge="fits"):
|
|
view, before, read = self.run_case(
|
|
indexed("0x3fffffff", literal, stride=4), DISABLED, stride=4,
|
|
extra_addresses=(BASE + top_aligned,))
|
|
before[BASE + top_aligned] = VALUE
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [VALUE] * LANES)
|
|
with self.subTest(kind="idxen", mode=name, edge="overflow"):
|
|
view, before, read = self.run_case(
|
|
indexed("0x40000000", literal, stride=4), DISABLED, stride=4,
|
|
extra_addresses=(BASE + top_aligned,))
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [0] * LANES)
|
|
with self.subTest(kind="soffset", edge="fits"):
|
|
view, before, read = self.run_case(
|
|
soffset_case(-8, 4), DISABLED, stride=0, extra_addresses=(BASE + top_aligned,))
|
|
before[BASE + top_aligned] = VALUE
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [VALUE] * LANES)
|
|
with self.subTest(kind="soffset", edge="overflow"):
|
|
view, before, read = self.run_case(
|
|
soffset_case(-4, 4), DISABLED, stride=0, extra_addresses=(BASE + top_aligned,))
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [0] * LANES)
|
|
with self.subTest(kind="byte_soffset", edge="0xffffffff_fits"):
|
|
view, before, read = self.run_case(
|
|
soffset_case(-4, 3, byte=True), DISABLED, stride=0, extra_addresses=(BASE + top_aligned,))
|
|
before[BASE + top_aligned] = (SENTINEL & 0x00FFFFFF) | (VALUE << 24)
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [VALUE] * LANES)
|
|
with self.subTest(kind="byte_soffset", edge="0x100000000_overflow"):
|
|
view, before, read = self.run_case(
|
|
soffset_case(-4, 4, byte=True), DISABLED, stride=0, extra_addresses=(BASE + top_aligned,))
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [0] * LANES)
|
|
|
|
def test_structured_modes_already_refuse_the_index(self):
|
|
view, before, read = self.run_case(indexed(-1), STRUCTURED_OFFSET, records=8)
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [0] * LANES)
|
|
|
|
def test_soffset_is_added_without_wrapping(self):
|
|
# DISABLED checks only that the buffer is not empty; modulo 2^32 the access would land at base + 0x10.
|
|
view, before, read = self.run_case(SOFFSET, DISABLED, stride=0)
|
|
self.assertEqual(view, before)
|
|
self.assertEqual(read, [0] * LANES)
|
|
|
|
class BufferOffsetWrapInt64AddressesTests(BufferOffsetWrapTests):
|
|
"""The same accesses with --int64-addresses."""
|
|
LOWERED, INT64 = False, True
|
|
|
|
|
|
class BufferOffsetWrapKeptInt64Tests(BufferOffsetWrapTests):
|
|
"""The same accesses by default, in a module lower_addr64 leaves in its Int64 form."""
|
|
PREFIX, INT64 = DATA64, True
|
|
|
|
|
|
class FitPredicateTests(unittest.TestCase):
|
|
"""The emitted fit test, for the literal V# that folds `wide` to `0 + idx * stride` (the NVVM failure's shape)."""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.MODULES = []
|
|
for config, lowered, prefix, int64 in CONFIGS:
|
|
for mode, literal in (("disabled literal", DISABLED), ("raw literal", RAW)):
|
|
module = translate("cs_buffer_offset_wrap_pred", prefix + indexed(2, literal, stride=64, records=5),
|
|
lowered)
|
|
for variant, text in (("translated", module), ("spirv_opt", spirv_opt.optimize(module))):
|
|
cls.MODULES.append((dict(config=config, mode=mode, variant=variant), int64, text))
|
|
|
|
def test_no_compare_with_the_32_bit_limit(self):
|
|
for labels, _, text in self.MODULES:
|
|
with self.subTest(**labels):
|
|
for pattern in U64_LIMIT_COMPARES + (PAIR_LIMIT_COMPARE,):
|
|
self.assertNotRegex(text, pattern)
|
|
|
|
def test_int64_form_tests_the_high_word(self):
|
|
for labels, int64, text in self.MODULES:
|
|
if not int64:
|
|
continue
|
|
with self.subTest(**labels):
|
|
self.assertIn("OpCapability Int64", text)
|
|
shifts = re.findall(r"(%\S+) = OpShiftRightLogical %ulong %\S+ %c64_32\b", text)
|
|
self.assertTrue(
|
|
any(re.search(rf"= OpIEqual %bool {re.escape(hi)} %cl0\b", text) for hi in shifts),
|
|
"expected (wide >> 32) == 0 as the offset-fit test")
|
|
|
|
def test_lowered_form_has_no_int64(self):
|
|
for labels, int64, text in self.MODULES:
|
|
if int64:
|
|
continue
|
|
with self.subTest(**labels):
|
|
self.assertNotIn("OpCapability Int64", text)
|
|
self.assertNotIn("%ulong", text)
|
|
self.assertRegex(text, r"= OpIEqual %bool %a64_\w+ %a64c_0\b")
|
|
|
|
@unittest.skipUnless(SPIRV_AS and SPIRV_VAL, "spirv-as / spirv-val not on PATH")
|
|
def test_modules_pass_spirv_val(self):
|
|
for labels, _, text in self.MODULES:
|
|
with self.subTest(**labels):
|
|
self.assertEqual(spirv_val_errors(text), "")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|