diff --git a/docs/design.md b/docs/design.md index 656418c99a..f851ae1771 100644 --- a/docs/design.md +++ b/docs/design.md @@ -311,6 +311,7 @@ How the generated SPIR-V expects the runtime to work: | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. **Mesh shaders** read their root SGPRs through the graphics root window: s16..s31 come from dwords 8..23 (where a VS, PS or GS reads s8..s23), s8..s15 are 0, s0..s7 dwords 0..7; the index records `"root_window": {"sgpr": 16, "dword": 8}` (D3D-448-GRAPHICS, `docs/d3d12_vulkan.md` 3.5). Checked by `tests/semantic/test_ms_root_window.py` (MeshEXT and `--mesh-compute`, CPU interpreter) and `d3d12_mesh_test` (RX 9070 XT). | | Direct resource heap | In the matched Prop/Tree BatchCull compute signature the two explicit tables and scalar constant occupy s4–s6. Bind the resource heap's uint32 arena-relative byte address at s7 (push-constant byte 28). The program supplies a zero high word and scales the resource index by 32 bytes. Other stages and signatures consume different SGPRs. See [descriptor heaps and the bindless model](d3d12_vulkan.md#34-descriptor-heaps-and-the-bindless-model) for the evidence and graphics examples. | | Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | +| 64-bit addresses without `Int64` | The translator builds every PhysicalStorageBuffer address from one idiom: widen a dword, shift the high word by 32, OR, add or subtract (64-bit constants included), AND a mask, take a word back (narrow to 32 bits, or shift right by 32), compare two such values (the NUM_RECORDS bound), convert to a pointer. `lower_addr64` runs on the assembled module: when a shader's only 64-bit integers are that idiom it becomes (low, high) pairs of 32-bit words, `OpIAddCarry` / `OpISubBorrow` carrying into the high word, pair compares high word first, and a `uvec2` bitcast to the pointer (as `GL_EXT_buffer_reference_uvec2`), and the module drops `OpCapability Int64`, so `index.json` no longer lists `shaderInt64` for it. Shifts by 1..31 either way become the two words' shifts with the bits that cross between them (`host_addr`'s 48-bit sign extension shifts left and then arithmetically right by 16); a left shift by a 32-bit value (the swizzled buffer offset's element-size log, a V# field) becomes the same on `k & 31` with the words moved up once `k >= 32`; a 64-bit multiply (the full `index * stride` of the swizzled offset and its 32-bit range check) becomes the low words' product with its high word from the four 16-bit half products, plus each low word times the other's high word. A shader with any other 64-bit integer use keeps `Int64`: right shifts by a variable amount, a 64-bit `OpPhi` or variable; so do dynamic-V# scalar-buffer loads and 64-bit data ops. `--int64-addresses` turns the lowering off. Checked by `tests/semantic/test_addr64_lowering.py`: both forms read the same word in `spirv_mini_interp` with a plain sum, a low-word carry and a 64-bit wrap, and dropping the carry is caught; on the GPU by the whole `runtime/test/shaders` suite (103 of its 117 memory-touching shaders drop `Int64`), the D3D12 fixture tests, and the reports on PR #2463 (NVIDIA Turing to Blackwell, AMD RDNA2 to RDNA4 on both drivers, Intel UHD and Arc A770 without `shaderInt64`, SwiftShader). Motivation: Intel drivers report `shaderInt64` false while supporting `bufferDeviceAddress` (#313, #1825). | | Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings (when the llvm-mc messages give one offset per rejected word, `shader_ir.parse_file`'s `invalid_at`, those words are skipped exactly and nothing is searched forward: a forward search let a data word printed as a copy of a later instruction take that instruction's place and lose every one after it; counted on the 1.0.2.1 pipeline library with #327's vcc-tuple decoding, 36 compute programs that stopped at "cannot re-anchor" now translate and pass `spirv-val`, none lost; `tests/semantic/test_reanchor_llvm_offsets.py`), translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Unused VOP3/VOP3P `SRC1` (bits 49:41) and `SRC2` (bits 58:50) fields are also ignored when stored as 0 and printed as `0x80`: LLVM 23 re-encodes a source it doesn't read as inline constant 0 (one-source `v_rcp`/`v_log`/`v_sqrt_f32_e64`, two-source `v_sub_f32_e64`/`v_cmp_*_e64`/`v_mul_lo_u32`/`v_pk_mul_f16`). Both checks for clean listings and re-anchoring use the parsed operand count to apply this exception only to unused sources. A used source encoded as 0 reads `s0` and is never treated as inline zero. `tests/semantic/test_printed_encoding.py` checks used `SRC1`/`SRC2` and an unused field with synthetic listings. Confirmed by a count over the corpus with LLVM 23.1.5: without it, 1,471 of the 1,473 shaders with embedded data are rejected ("reachable instruction with normalized encoding"); with it, all 1,473 translate and pass `spirv-val`. Runs with LLVM 21 already translated all of them, so older LLVMs presumably print the stored 0 (not re-checked). Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. A reachable instruction that falls through into words llvm-mc skipped (it printed no instruction there) is rejected too, as `fall-through into undecodable words`: until SHADER-813 the reachable path ended there without a word, so everything after the gap (exports, stores) was dropped from a module that still passed `spirv-val`. No VS/PS of the corpus has such a gap on a reachable path; in the FidelityFX FSPX programs it is the `v_dot4_i32_i8 ... op_sel` words LLVM 23 cannot decode (`docs/fspx.md`), so those programs are now refused instead of translated without their stores, until those words are decoded (#2038, #2323). `tests/test_rdna2spirv_decode.py` (`test_fall_through_into_undecodable_words_is_refused`). The exact re-anchoring path tries the same repair as the forward search for a `v_dot4_i32_i8` with an inline-integer S1 whose stored op_sel_hi (5) llvm-mc prints as the default (7), `restore_dot4_inline_sel`, before it marks the word: without it such a program is refused as "reachable instruction with normalized encoding" whenever its listing also reports rejected words. Counted on the 29 FidelityFX DLL programs (1.0.2.1, LLVM 21.1.8): 22 translate without it, 24 with it, all 24 pass `spirv-val`; `tests/semantic/test_reanchor_dot4_inline_sel.py`. | | VOP3 opcode 0x140 | LLVM disassembly of the synthetic words in `tests/test_rdna2_decode.py` gives `v_mad_legacy_f32` on gfx1010 through gfx1013 and `v_fma_legacy_f32` on gfx1030. The direct decoder defaults to gfx1013, matching the disassembler CLI. Checked by the unit test `test_vop3_legacy_mad_fma_target` in `tests/test_rdna2_decode.py`, which decodes the same words directly and runs the Python disassembler backend for gfx1013 and gfx1030. | | Printed encodings | A listing is LLVM's text for what it decoded, not the bytes it read, so the translator checks the two against each other: the re-anchoring above for listings with undecodable words, and, for every other listing whose header names its code range and whose blob sits next to it (`fssm/`, or `fspx/` for FSPX), each instruction's printed encoding against the bytes at its offset, with the same exceptions (`same_encoding`). A difference is `Unsupported`, naming the instruction, its offset and both byte strings, instead of a translation of the field as 0. The case that prompted it: llvm-mc's gfx1013 decoder (LLVM 21.1.8) drops the VOP3 `op_sel` bits (word 0, bits 14:11) of a 16-bit VOPC compare: `0a 08 a9 d4 01 05 02 00` disassembles as `v_cmp_lt_u16_e64 s10, v1, v2` and re-encodes with the bits cleared (its assembler rejects `op_sel` on VOPC for gfx1013 and gfx1030 alike). Counted over the 1.0.2.1 corpus: the 25,030 clean listings hold 30,335,381 instructions, and none differs from its bytes beyond those exceptions (754); the 166 16-bit VOPC compares (154 shaders, all `f16`) have `op_sel` clear. Hand-written listings, `run_gpu_tests.py`'s `code 0x0..0x0 (synthetic)` listings and a blob that doesn't hold the listing's code range (the tests' header-only FSSM) are not checked. `tests/semantic/test_printed_encoding.py` (a dropped VOPC `op_sel`, a later instruction, the SRC2 exception, and the unchecked cases). One difference is repaired instead of refused: a `v_fma_mix*` literal that llvm-mc prints cut to its low 16 bits (and re-encodes with a zero high half). llvm-mc 23.1.5 prints some of these literals in full as `lit(V)` (an f32 source, or a low half that is an inline constant; LLVM 21 printed the inline constant and dropped the literal word) and still re-encodes only the low half: `tools/shader_ir.py` reads `lit(V)` as V, and the same repair applies (5,733 such operands in the pipeline library, [shader_library.md](shader_library.md)). When the 8 instruction bytes match (`same_encoding` with all three sources counted as used, so a live `s0` can't pass as an inline 0) and the printed literal is the stored one's low half, every source the bytes encode as the literal (SRC field `0xff`) takes the stored 32 bits, so a source with `op_sel_hi` and `op_sel` set reads the high half instead of +0.0. Seen in one program of the FidelityFX DLL's `FSPX` code ([fspx.md](fspx.md)): src0 the low half, src2 the high half; the game's clean listings have no such difference (the count above). That the hardware gives op_sel's high half of the literal to that source is not measured; it is what Mesa's ACO compiler relies on (public: `optimize_constants()` in `src/amd/compiler/aco_optimizer.cpp`, Mesa `main` at `bb986060`, packs two constants as the two f16 halves of one literal, read through `v_fma_mix`'s `op_sel_hi` with the second source extracting the high half), and what the console compiler emitted here. `tools/fma_mix_literal_probe.py --oracle hw` measures it on an AMD GPU (the instruction's exact bytes through `tools/hw_oracle`; not run on one yet). `tests/semantic/test_fma_mix_literal.py` (the value through the interpreter, the re-anchoring path, an inline constant with the literal's printed value left alone, and the refused cases, a live source printed as inline 0 among them). A second shape is repaired too (`mix_inline_literal`): LLVM 21's form above. llvm-mc 21.1.8 (`-mcpu=gfx1013`) prints a `v_fma_mix*` literal whose low 16 bits are the f16 value of an inline constant as that constant and re-encodes the instruction in **8** bytes: every SRC field that held `0xff` holds the inline code, and the literal word is gone (`0x3f800000`, 1.0 as an f32 source, prints as `0`; `0x3c003800` as `0.5`, losing the high half 1.0). Swept with llvm-mc 21.1.8 over all 65,536 low halves under three high halves: exactly 90 low halves print this way (0..64, -1..-16, ±0.5, ±1.0, ±2.0, ±4.0, 1/(2π) as f16: `MIX_INLINE_F16`), whatever the high half; llvm-mc 23.1.6 prints all of them as `lit(V)`. The printed 8 bytes are 4 short of what the decoder read, so the later offsets of a clean listing were 4 low and its first such instruction was refused as a dropped field (one FSPX program, `tupacfan04`'s count in #8683). When every differing SRC field is `0xff` in the blob and the inline code of the stored literal's low half in the print, and the rest of the 8 bytes match exactly (`same_encoding`, all three sources live), each such source reads the stored 32 bits with the stored neg and abs (`NEG_HI`) bits, the instruction takes the 12 stored bytes, and the following offsets move up by 4 (also on the re-anchoring path). Any other difference stays `Unsupported`. CPU-checked by `tests/semantic/test_fma_mix_literal.py` (`FmaMixInlineLiteralTest`: an f32 source, two f16 halves, neg and abs, all 90 codes, both listing paths, the refused cases). | diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 8868dd5fb0..9dacfe24e3 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -930,6 +930,20 @@ def sval(x): values[res] = val(a[2]) if val(a[1]) else val(a[3]) elif op == "OpCopyObject": values[res] = val(a[1]) + elif op == "OpBitcast" and a[0] in ptr_types: + # A (low, high) pair of 32-bit words bitcast to a PhysicalStorageBuffer pointer (rdna2spirv.lower_addr64, + # as GL_EXT_buffer_reference_uvec2): the same address OpConvertUToPtr of the 64-bit value would give. + v = val(a[1]) + vt = types.t.get(id_type.get(a[1])) + if not (vt and vt[0] == "vec" and vt[2] == 2 and types.t.get(vt[1], ())[:2] == ("int", 32)): + raise UnsupportedConstruct("OpBitcast to a pointer from a type other than a 2-component 32-bit " + "integer vector") + if not (isinstance(v, tuple) and len(v) == 2 and all(isinstance(x, int) and not isinstance(x, bool) + for x in v)): + raise UnsupportedConstruct("OpBitcast to a pointer from something other than two 32-bit words") + if ptr_types[a[0]][0] != "PhysicalStorageBuffer": + raise UnsupportedConstruct("OpBitcast to a pointer that is not PhysicalStorageBuffer") + values[res] = pointers[res] = ("psb", (v[0] & MASK) | ((v[1] & MASK) << 32)) elif op == "OpBitcast": k, v = types.t[a[0]], val(a[1]) source = types.t.get(id_type.get(a[1])) diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index a2eb436fc9..d90e0c8bd3 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py @@ -804,6 +804,15 @@ def eval(self, lane, res, op, a): raise UnsupportedConstruct("nested OpCompositeInsert") v[int(a[3])] = self.raw(lane, a[1]) return tuple(v) + if op == "OpBitcast" and a[0] in m.ptr_types: + # A (low, high) uint pair bitcast to a buffer pointer (rdna2spirv.lower_addr64): the address + # OpConvertUToPtr of the 64-bit value would give. + cls, pointee = m.ptr_types[a[0]] + if cls != "PhysicalStorageBuffer": + raise UnsupportedConstruct(f"OpBitcast to storage class {cls}") + lo, hi = (int(x) for x in self.val(lane, a[1])) + lane.pointers[res] = ("psb", (lo & 0xFFFFFFFF) | ((hi & 0xFFFFFFFF) << 32), pointee) + return None if op == "OpBitcast": k, v = m.types[a[0]], self.val(lane, a[1]) if k[0] == "float" and isinstance(v, int) and not isinstance(v, bool): diff --git a/tests/semantic/test_addr64_lowering.py b/tests/semantic/test_addr64_lowering.py new file mode 100644 index 0000000000..b6dc4ea80f --- /dev/null +++ b/tests/semantic/test_addr64_lowering.py @@ -0,0 +1,190 @@ +"""tools/rdna2spirv.py lower_addr64: 64-bit buffer addresses as 32-bit pairs, without the Int64 capability. + +Every PhysicalStorageBuffer address the translator builds is one idiom (widen, shift the high word by 32, OR, add, +convert to a pointer). A shader whose only 64-bit integers are that idiom is rewritten to (low, high) word pairs +with OpIAddCarry carrying into the high word and a uvec2 bitcast to the pointer, and drops `OpCapability Int64` +(Vulkan shaderInt64, which Intel's drivers lack: #313). A shader with any other 64-bit integer use keeps Int64. + +Each program is translated twice, with the lowering (the default) and with --int64-addresses, and both run in +tests/semantic/spirv_mini_interp.py on the same memory: the loaded word must land at the same address, including +when the low words carry and when the 64-bit sum wraps. A negative control drops the carry from the lowered module +and checks that the carry case then reads the wrong word, so the test is sensitive to the lowering it checks. +""" +import os +import struct +import sys +import tempfile +import unittest +import warnings + +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 +sys.path.insert(0, TOOLS_DIR) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +M64 = (1 << 64) - 1 +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 32) & M32] + return si.run_workgroup(spv, THREADS, THREADS, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=pc, memory=dict(memory)) + + +def load_program(base): + """s_load_dword from the 64-bit pointer `base`, stored through the output V# at offset 0.""" + return [f"s_mov_b32 s6, {base & M32:#x}", f"s_mov_b32 s7, {(base >> 32) & M32:#x}", + "s_load_dword s8, s[6:7], 0x0", "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v1, s8", "buffer_store_dword v1, off, s[0:3], 0", "s_waitcnt vmcnt(0)"] + + +# (heap base, pointer): plain; the low words carry into the high word; the 64-bit sum wraps to zero. +CASES = [(0x1000, 0x2000), (0x1_FFFF_FFF0, 0x20), (0xFFFF_FFFF_FFFF_FFF0, 0x10)] + + +def global_program(base, offset): + """global_load_dword from the 64-bit VGPR address `base` with the signed instruction offset, stored at heap + 0. + The offset is sign-extended through a 64-bit signed integer (Gen.global_address), the one signed form the + lowering handles.""" + return [f"v_mov_b32 v2, {base & M32:#x}", f"v_mov_b32 v3, {(base >> 32) & M32:#x}", + f"global_load_dword v4, v[2:3], off offset:{offset}", "s_waitcnt vmcnt(0)", + "buffer_store_dword v4, off, s[0:3], 0", "s_waitcnt vmcnt(0)"] + + +# (heap base, VGPR address, signed offset): a negative offset across the low-word boundary, and a positive one. +GLOBAL_CASES = [(0x1000, 0x1_0000_0000, -4), (0x1000, 0x2000, -2048), (0x1_FFFF_FFF0, 0x20, 2044)] +# A VGPR address with bit 47 set is a negative 48-bit VA (Gen.host_addr sign-extends it: shifts by 16 both ways, which +# the lowering turns into the two words' shifts), so it reads below the heap base. +NEGATIVE_48_CASES = [(0x1_0000_0000, 0xFFFF_FFFF_FFF0, 8), (0x2_0000_1000, 0x8000_0000_0000, 0)] + + +def sext48(va): + return va - (1 << 48) if va & (1 << 47) else va + + +class AddressLoweringTests(unittest.TestCase): + def test_lowered_module_has_no_int64(self): + spv = translate("cs_a64_plain", load_program(0x2000)) + self.assertNotIn("OpCapability Int64", spv) + self.assertNotIn("%ulong", spv) + self.assertNotIn("%long", spv) + self.assertNotIn("OpConvertUToPtr", spv) + self.assertIn("OpIAddCarry %umul", spv) + self.assertIn("OpBitcast %_ptr_PSB_arr", spv) + self.assertIn("OpCapability PhysicalStorageBufferAddresses", spv) + self.assertIn("OpMemoryModel PhysicalStorageBuffer64", spv) + + def test_int64_addresses_flag_keeps_the_old_form(self): + spv = translate("cs_a64_flag", load_program(0x2000), lowered=False) + self.assertIn("OpCapability Int64", spv) + self.assertIn("%ulong = OpTypeInt 64 0", spv) + self.assertIn("OpConvertUToPtr", spv) + self.assertNotIn("OpIAddCarry %umul", spv) + + def test_same_address_as_the_int64_form(self): + for heap, base in CASES: + with self.subTest(heap=hex(heap), base=hex(base)): + addr = (heap + base) & M64 + memory = {addr: MAGIC, (addr + 4) & M64: 0x0BAD0004, (addr - 4) & M64: 0x0BAD0000} + want = run(translate("cs_a64_ref", load_program(base), lowered=False), heap, memory) + got = run(translate("cs_a64_low", load_program(base)), heap, memory) + self.assertEqual(want[heap & M64], MAGIC) # the reference read the word at heap + base + self.assertEqual(got, want) + + def test_signed_global_offset_same_address_as_the_int64_form(self): + for heap, base, offset in GLOBAL_CASES: + with self.subTest(heap=hex(heap), base=hex(base), offset=offset): + addr = (heap + base + offset) & M64 + memory = {addr: MAGIC, (addr + 4) & M64: 0x0BAD0004, (addr - 4) & M64: 0x0BAD0000} + lowered = translate("cs_a64_glo", global_program(base, offset)) + self.assertNotIn("OpCapability Int64", lowered) # the sign-extension is lowered too + self.assertNotIn("%long", lowered) + want = run(translate("cs_a64_glo_ref", global_program(base, offset), lowered=False), heap, memory) + got = run(lowered, heap, memory) + self.assertEqual(want[heap & M64], MAGIC) + self.assertEqual(got, want) + + def test_negative_48_bit_address_same_as_the_int64_form(self): + for heap, base, offset in NEGATIVE_48_CASES: + with self.subTest(heap=hex(heap), base=hex(base), offset=offset): + addr = (heap + sext48(base) + offset) & M64 + memory = {addr: MAGIC, (addr + 4) & M64: 0x0BAD0004, (addr - 4) & M64: 0x0BAD0000} + lowered = translate("cs_a64_neg", global_program(base, offset)) + self.assertNotIn("OpCapability Int64", lowered) + want = run(translate("cs_a64_neg_ref", global_program(base, offset), lowered=False), heap, memory) + got = run(lowered, heap, memory) + self.assertEqual(want[heap & M64], MAGIC) # the reference read below the heap base + self.assertEqual(got, want) + + def test_dropping_the_carry_is_caught(self): + heap, base = CASES[1] + addr = (heap + base) & M64 + spv = translate("cs_a64_nocarry", load_program(base)) + carries = [ln for ln in spv.split("\n") if ln.strip().endswith("s 1") and "OpCompositeExtract %uint %a64_" in ln] + self.assertTrue(carries, "no carry extract in the lowered module") + broken = spv + for ln in carries: + res = ln.split()[0] + broken = broken.replace(ln, f" {res} = OpCopyObject %uint %a64c_0") + got = run(broken, heap, {addr: MAGIC}) + self.assertNotEqual(got.get(heap & M64), MAGIC) + + def test_a_64bit_data_op_keeps_int64(self): + prog = ["s_mov_b32 s6, 0x2000", "s_mov_b32 s7, 0", "s_lshl_b64 s[6:7], s[6:7], 4"] + load_program(0)[2:] + spv = translate("cs_a64_data", prog) + self.assertIn("OpCapability Int64", spv) + self.assertIn("%ulong = OpTypeInt 64 0", spv) + self.assertNotIn("%a64", spv) + # and it still runs: the shift makes the pointer 0x20000 + memory = {0x1000 + 0x20000: MAGIC} + got = run(spv, 0x1000, memory) + self.assertEqual(got[0x1000], MAGIC) + + def test_lowering_is_idempotent_and_valid_without_psb(self): + spv = translate("cs_a64_idem", load_program(0x2000)) + self.assertEqual(rdna2spirv.lower_addr64(spv), spv) + plain = ["v_mov_b32 v1, 7", "v_add_nc_u32 v1, v1, v1"] + text = "\n".join(["OpCapability Shader", "%uint = OpTypeInt 32 0"]) + self.assertEqual(rdna2spirv.lower_addr64(text), text) # no 64-bit types: untouched + self.assertNotIn("%ulong", translate("cs_a64_noload", plain + load_program(0)[4:])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_buffer_atomic_fminmax_and_align.py b/tests/semantic/test_buffer_atomic_fminmax_and_align.py index e1399d69a5..c49976c65f 100644 --- a/tests/semantic/test_buffer_atomic_fminmax_and_align.py +++ b/tests/semantic/test_buffer_atomic_fminmax_and_align.py @@ -477,7 +477,9 @@ def test_spirv_emits_alignment_guard(self): for body, mask_const in cases: with self.subTest(insn=body[-1]): spv = translate(body) - self.assertIn("OpUConvert %uint", spv) + # The 64-bit address narrowed to its low word: OpUConvert %uint, or since lower_addr64 the pair's + # low word (an OpCopyObject of it). + self.assertTrue("OpUConvert %uint" in spv or "OpCopyObject %uint %a64_" in spv) self.assertIn("OpBitwiseAnd %uint", spv) self.assertIn(mask_const, spv) diff --git a/tests/semantic/test_buffer_store_format.py b/tests/semantic/test_buffer_store_format.py index 52e7343e86..010300c7ad 100644 --- a/tests/semantic/test_buffer_store_format.py +++ b/tests/semantic/test_buffer_store_format.py @@ -808,7 +808,9 @@ def test_tbuffer_store_emits_storage_buffer_ops_not_image_write(self) -> None: ], fssm=CS_FSSM, ) - self.assertIn("OpConvertUToPtr", spv) + # The store's buffer address: a (low, high) uint pair bitcast to the pointer (lower_addr64), or + # OpConvertUToPtr of the 64-bit value with --int64-addresses. + self.assertTrue("OpBitcast %_ptr_PSB" in spv or "OpConvertUToPtr" in spv) self.assertIn("OpStore", spv) self.assertIn("OpBranchConditional", spv) self.assertIn("OpSelectionMerge", spv) diff --git a/tests/semantic/test_loop_ballot_barrier.py b/tests/semantic/test_loop_ballot_barrier.py index c7c26c1232..7cb4cefdfb 100644 --- a/tests/semantic/test_loop_ballot_barrier.py +++ b/tests/semantic/test_loop_ballot_barrier.py @@ -238,6 +238,7 @@ def run_compute_workgroup(asm, threads, subgroup_size, push_constants=None, memo consts = mod["consts"] types = mod["types"] gvars = mod["gvars"] + ptr_elem = mod["ptr_elem"] blocks = mod["blocks"] make_zero = mod["make_zero"] mem = {} if memory is None else memory @@ -447,7 +448,13 @@ def step_inv(inv): elif op == "OpCopyObject": inv.ssa[res] = val_of(inv, args[1]) elif op == "OpBitcast": - inv.ssa[res] = val_of(inv, args[1]) + if args[0] in ptr_elem and ptr_elem[args[0]][0] == "PhysicalStorageBuffer": + # A (low, high) uint pair bitcast to a buffer pointer (rdna2spirv.lower_addr64): the address + # OpConvertUToPtr of the 64-bit value would give. + lo, hi = val_of(inv, args[1]) + inv.ssa[res] = ("phys", (lo & M32) | ((hi & M32) << 32)) + else: + inv.ssa[res] = val_of(inv, args[1]) elif op == "OpCompositeExtract": inv.ssa[res] = val_of(inv, args[1])[int(args[2])] elif op == "OpCompositeConstruct": diff --git a/tests/semantic/test_wave64_emulate_opt.py b/tests/semantic/test_wave64_emulate_opt.py index 0e304b8687..e0d247dd2e 100644 --- a/tests/semantic/test_wave64_emulate_opt.py +++ b/tests/semantic/test_wave64_emulate_opt.py @@ -32,6 +32,11 @@ wave64_emulate_opt = rdna2spirv.wave64_emulate_opt MASK32 = 0xFFFFFFFF + + +def _buffer_pointer_in(text): + """A buffer address becoming a pointer: the uint-pair bitcast (rdna2spirv.lower_addr64) or OpConvertUToPtr.""" + return "OpBitcast %_ptr_PSB" in text or "OpConvertUToPtr" in text VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # raw buffer covering all offsets @@ -455,6 +460,12 @@ def step_until_barrier(inv, step_budget): elif op == "OpUConvert": bits = types[a[0]][1] vals[res] = vals[a[1]] & ((1 << bits) - 1) + elif op == "OpBitcast" and a[0] in ptr_types: + # A (low, high) uint pair bitcast to a PhysicalStorageBuffer pointer (rdna2spirv.lower_addr64): the + # address OpConvertUToPtr of the 64-bit value would give. + lo, hi = vals[a[1]] + ptrs[res] = ("psb", (lo & MASK32) | ((hi & MASK32) << 32)) + vals[res] = ptrs[res] elif op == "OpBitcast": k = types[a[0]] v = vals[a[1]] @@ -1494,10 +1505,10 @@ def test_monotone_dirty_transfer_no_phantom_clear_after_x_round(self): i3 = next(i for i, l in enumerate(lines) if l.strip().startswith("%blk3 = OpLabel")) blk2_to_end = lines[i2:] store_idx = next(i for i, l in enumerate(blk2_to_end) - if "OpStore" in l and "OpConvertUToPtr" in "\n".join(blk2_to_end[max(0, i - 15):i])) + if "OpStore" in l and _buffer_pointer_in("\n".join(blk2_to_end[max(0, i - 15):i]))) i3_rel = i3 - i2 load_idx = next(i for i, l in enumerate(blk2_to_end[i3_rel:], i3_rel) - if "OpLoad %uint" in l and "OpConvertUToPtr" in "\n".join(blk2_to_end[max(0, i - 15):i])) + if "OpLoad %uint" in l and _buffer_pointer_in("\n".join(blk2_to_end[max(0, i - 15):i]))) self.assertTrue(any("OpControlBarrier" in l for l in blk2_to_end[store_idx:load_idx]), f"missing OpControlBarrier between blk2 buffer_store and blk3 buffer_load ({expected_mode})") for rev in (False, True): diff --git a/tests/test_rdna2spirv_xdxr_rules.py b/tests/test_rdna2spirv_xdxr_rules.py index 10bedb6d38..bb1cb753ad 100644 --- a/tests/test_rdna2spirv_xdxr_rules.py +++ b/tests/test_rdna2spirv_xdxr_rules.py @@ -43,21 +43,21 @@ class TestRdna2SpirvXdxrRules(unittest.TestCase): def test_buffer_load_ushort(self): """buffer_load_ushort loads 16 bits zero-extended into destination register.""" asm = translate_cs("cs_load_ushort", "\tbuffer_load_ushort v0, v1, s[0:3], 0 offen") - self.assertIn("OpConvertUToPtr %_ptr_PSB_arr", asm) + self.assertTrue("OpBitcast %_ptr_PSB_arr" in asm or "OpConvertUToPtr %_ptr_PSB_arr" in asm) # the buffer address (a uint pair since lower_addr64) self.assertIn("OpLoad %uint", asm) self.assertTrue("65535" in asm or "0xffff" in asm.lower()) def test_buffer_load_sshort_signed(self): """buffer_load_sshort loads 16 bits sign-extended into destination register.""" asm = translate_cs("cs_load_short", "\tbuffer_load_sshort v0, v1, s[0:3], 0 offen") - self.assertIn("OpConvertUToPtr %_ptr_PSB_arr", asm) + self.assertTrue("OpBitcast %_ptr_PSB_arr" in asm or "OpConvertUToPtr %_ptr_PSB_arr" in asm) # the buffer address (a uint pair since lower_addr64) self.assertIn("OpLoad %uint", asm) self.assertIn("OpBitFieldSExtract", asm) def test_tbuffer_load_format_8_uint(self): """tbuffer_load_format_x with BUF_FMT_8_UINT decodes format 5 into uint.""" asm = translate_cs("cs_tb_8_uint", "\ttbuffer_load_format_x v0, v1, s[0:3], 0 format:[BUF_FMT_8_UINT] offen") - self.assertIn("OpConvertUToPtr %_ptr_PSB_arr", asm) + self.assertTrue("OpBitcast %_ptr_PSB_arr" in asm or "OpConvertUToPtr %_ptr_PSB_arr" in asm) # the buffer address (a uint pair since lower_addr64) self.assertIn("OpLoad %uint", asm) self.assertIn("OpBitFieldUExtract %uint", asm) diff --git a/tests/test_translate.py b/tests/test_translate.py index fe2df12889..4daf00b884 100644 --- a/tests/test_translate.py +++ b/tests/test_translate.py @@ -295,7 +295,9 @@ def test_cs_store_packed_atomic_pointers(make_shader): access = defs[ptr].split() assert access[:2] == ["OpAccessChain", "%_ptr_PSB_uint"] _, _, base, index = access - assert defs[base].startswith("OpConvertUToPtr %_ptr_PSB_arr ") + # The array pointer is the address bitcast from a (low, high) uint pair (lower_addr64), or, with + # --int64-addresses, OpConvertUToPtr of the 64-bit value. + assert defs[base].startswith(("OpBitcast %_ptr_PSB_arr ", "OpConvertUToPtr %_ptr_PSB_arr ")) assert defs[index] == "OpConstant %uint 0" diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 73df48ed8e..2b86c3d181 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -84,6 +84,9 @@ # barycentrics, so .y/.z are AMD's i/j as with BaryCoordKHR. BARY_FALLBACK = False SHADER_CLOCK = False +# --int64-addresses: keep 64-bit integer address arithmetic (Int64) instead of lowering it to 32-bit pairs; see +# lower_addr64. +ADDR_PAIR = True FMA_KHR = False # --fma khr: fused multiply-adds are OpFmaKHR (SPV_KHR_fma, VK_KHR_shader_fma), not GLSL Fma FMA_EXACT = False # --fma exact: fused multiply-adds are emulated from single-rounded f32 ops (Gen.fma_exact) # --texel-offset-fallback: image_sample*_o without VK_KHR_maintenance8. The run-time texel offset is folded into the @@ -17177,9 +17180,241 @@ def label(prefix): else: tail = end_lock + " OpReturn\n OpFunctionEnd\n" insert_late_constants(gen, out, written) - return split_big_switch(no_contraction(dedupe_types( - "\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) + - "\n" + "\n".join(gen.body) + "\n" + tail))) + text = "\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) + \ + "\n" + "\n".join(gen.body) + "\n" + tail + if ADDR_PAIR: + text = lower_addr64(text) + return split_big_switch(no_contraction(dedupe_types(text))) + + +# ---- 64-bit addresses without Int64 ---- +# Every PhysicalStorageBuffer address the generator builds is one idiom: widen a 32-bit word (OpUConvert), shift a +# high word left by 32, OR, add or subtract (64-bit constants included), AND a mask, take a word back (narrow to +# 32 bits, or shift right by 32), sign-extend a dword (the signed offset of a global_* access) and shift it right +# arithmetically by 32, shift by 1..31 either way (host_addr's 48-bit sign extension: left and then arithmetically +# right by 16), compare two such values (the NUM_RECORDS bound), convert to a pointer. A shader +# whose only 64-bit integers are that idiom doesn't need the Int64 capability (Vulkan shaderInt64, which Intel's +# drivers lack, #313): lower_addr64 rewrites it to (low, high) pairs of 32-bit words, OpIAddCarry / OpISubBorrow +# carrying into the high word, compares high word first, and bitcasts the pair (a uvec2) to the pointer, as +# GL_EXT_buffer_reference_uvec2 does. A 64-bit multiply (the swizzled buffer offset's index * stride) and a left +# shift by a 32-bit value (its element-size log) are lowered too. A shader with any other 64-bit integer use (a right +# shift by a variable amount, a 64-bit OpPhi or variable) is left exactly as it was and keeps Int64. +# --int64-addresses turns the lowering off. +_A64_PRODUCERS = ("OpUConvert", "OpShiftLeftLogical", "OpShiftRightLogical", "OpBitwiseOr", "OpBitwiseAnd", "OpIAdd", + "OpISub", "OpSConvert", "OpBitcast", "OpShiftRightArithmetic", "OpIMul") +# 64-bit compares of two addresses: high words first, then the low words. +_A64_CMP = {"OpULessThan": ("OpULessThan", False), "OpULessThanEqual": ("OpULessThanEqual", False), + "OpUGreaterThan": ("OpULessThan", True), "OpUGreaterThanEqual": ("OpULessThanEqual", True), + "OpIEqual": None, "OpINotEqual": None} +_A64_ID = re.compile(r"%[\w.]+") + + +def lower_addr64(text): + lines = text.split("\n") + t64, c64, c32, prod, conv, cmp, narrow, rtype = set(), {}, {}, {}, {}, {}, {}, {} + for line in lines: + w = line.split() + if len(w) < 3 or w[1] != "=": + continue + res, op, args = w[0], w[2], w[3:] + if args: + rtype[res] = args[0] # the result type of every typed instruction + if op == "OpTypeInt" and args[:1] == ["64"]: + t64.add(res) + elif op == "OpConstant" and args and args[0] in t64: + c64[res] = int(args[1]) & 0xFFFFFFFFFFFFFFFF + elif op == "OpConstant" and args[:1] == ["%uint"] and len(args) == 2: + c32[res] = int(args[1]) & 0xFFFFFFFF # a shift amount may be a 32-bit constant + elif op in _A64_PRODUCERS and args and args[0] in t64: + prod[res] = (op, args[1:]) + elif op == "OpUConvert" and args[:1] == ["%uint"] and len(args) == 2: + narrow[res] = args[1] # a 64-bit value's low word (kept only if it is one) + elif op == "OpConvertUToPtr": + conv[res] = args + elif op in _A64_CMP and args[:1] == ["%bool"] and len(args) == 3: + cmp[res] = (op, args[1:]) + if not t64: + return text + v64 = set(c64) | set(prod) + # a shift's amount: a 64-bit or 32-bit constant of 1..32 (the 48-bit sign extension of host_addr shifts by 16), or + # for a left shift any 32-bit value (the swizzled buffer offset shifts by the element size's log, a V# field) + shift = {r: v for r, v in {**c32, **c64}.items() if 1 <= v <= 32} + narrow = {r: v for r, v in narrow.items() if v in v64} + for res, (op, a) in list(cmp.items()): # a compare of two 64-bit values; any other compare is left alone + if a[0] not in v64 and a[1] not in v64: + del cmp[res] + elif a[0] not in v64 or a[1] not in v64: + return text + for res, (op, a) in prod.items(): # the idiom, exactly + ok = (op in ("OpUConvert", "OpSConvert") and len(a) == 1 and a[0] not in v64 and + rtype.get(a[0]) in ("%uint", "%int")) or \ + (op == "OpBitcast" and len(a) == 1 and a[0] in v64) or \ + (op in ("OpShiftLeftLogical", "OpShiftRightLogical", "OpShiftRightArithmetic") and len(a) == 2 and + a[0] in v64 and a[1] in shift) or \ + (op == "OpShiftLeftLogical" and len(a) == 2 and a[0] in v64 and a[1] not in v64 and + rtype.get(a[1]) == "%uint") or \ + (op in ("OpBitwiseOr", "OpBitwiseAnd", "OpIAdd", "OpISub", "OpIMul") and len(a) == 2 and a[0] in v64 and + a[1] in v64) + if not ok: + return text + for line in lines: # any other mention of a 64-bit type or value: keep Int64 + w = line.split() + res = w[0] if len(w) >= 3 and w[1] == "=" else None + if res in t64 or res in c64 or res in prod or res in conv or res in cmp or res in narrow: + continue + if any(tok in t64 or tok in v64 for tok in _A64_ID.findall(line)): + return text + uc, pair, out, n = {}, {}, [], 0 + + def const(v): + if v not in uc: + uc[v] = f"%a64c_{v:x}" + return uc[v] + for cid, v in c64.items(): + pair[cid] = (const(v & 0xFFFFFFFF), const(v >> 32)) + for line in lines: + w = line.split() + res = w[0] if len(w) >= 3 and w[1] == "=" else None + if res in t64 or res in c64 or line.strip() == "OpCapability Int64": + continue + if res in prod: + op, a = prod[res] + if op == "OpUConvert": + pair[res] = (a[0], const(0)) + elif op == "OpBitcast": # between the 64-bit integer types: the same words + pair[res] = pair[a[0]] + elif op == "OpShiftLeftLogical" and a[1] not in shift: + # A left shift by a 32-bit value k (0..63 matter; SPIR-V leaves a shift by 32 or more undefined, so + # each word's shift stays under 32): k & 31 on both words with the bits that cross, then the words + # move up one if k >= 32. + n += 1 + (xl, xh), k, p = pair[a[0]], a[1], f"%a64_{n}" + out += [f" {p}k = OpBitwiseAnd %uint {k} {const(31)}", + f" {p}r = OpISub %uint {const(31)} {p}k", + f" {p}l = OpShiftLeftLogical %uint {xl} {p}k", + f" {p}a = OpShiftLeftLogical %uint {xh} {p}k", + f" {p}b = OpShiftRightLogical %uint {xl} {p}r", # lo >> (31 - k) >> 1: 0 when k = 0 + f" {p}c = OpShiftRightLogical %uint {p}b {const(1)}", + f" {p}h = OpBitwiseOr %uint {p}a {p}c", + f" {p}g = OpUGreaterThanEqual %bool {k} {const(32)}", + f" {p}L = OpSelect %uint {p}g {const(0)} {p}l", + f" {p}H = OpSelect %uint {p}g {p}l {p}h"] + pair[res] = (p + "L", p + "H") + elif op == "OpIMul": + # The low 64 bits of the product: the low words' full product (its high word from the four 16-bit + # half products, with plain 32-bit multiplies, so the test interpreters can run it too), plus each + # low word times the other's high word into the high word (the rest lies above 64 bits). + n += 1 + (xl, xh), (yl, yh), p = pair[a[0]], pair[a[1]], f"%a64_{n}" + h16, c16 = const(0xFFFF), const(16) + out += [f" {p}l = OpIMul %uint {xl} {yl}", + f" {p}x0 = OpBitwiseAnd %uint {xl} {h16}", f" {p}x1 = OpShiftRightLogical %uint {xl} {c16}", + f" {p}y0 = OpBitwiseAnd %uint {yl} {h16}", f" {p}y1 = OpShiftRightLogical %uint {yl} {c16}", + f" {p}p00 = OpIMul %uint {p}x0 {p}y0", f" {p}p01 = OpIMul %uint {p}x0 {p}y1", + f" {p}p10 = OpIMul %uint {p}x1 {p}y0", f" {p}p11 = OpIMul %uint {p}x1 {p}y1", + f" {p}m0 = OpShiftRightLogical %uint {p}p00 {c16}", + f" {p}m1 = OpBitwiseAnd %uint {p}p01 {h16}", f" {p}m2 = OpBitwiseAnd %uint {p}p10 {h16}", + f" {p}m3 = OpIAdd %uint {p}m0 {p}m1", f" {p}m = OpIAdd %uint {p}m3 {p}m2", + f" {p}c0 = OpShiftRightLogical %uint {p}p01 {c16}", f" {p}c1 = OpShiftRightLogical %uint {p}p10 {c16}", + f" {p}c2 = OpShiftRightLogical %uint {p}m {c16}", + f" {p}c3 = OpIAdd %uint {p}p11 {p}c0", f" {p}c4 = OpIAdd %uint {p}c3 {p}c1", + f" {p}c = OpIAdd %uint {p}c4 {p}c2", + f" {p}a = OpIMul %uint {xl} {yh}", + f" {p}b = OpIMul %uint {xh} {yl}", + f" {p}d = OpIAdd %uint {p}c {p}a", + f" {p}h = OpIAdd %uint {p}d {p}b"] + pair[res] = (p + "l", p + "h") + elif op == "OpShiftLeftLogical" and shift[a[1]] == 32: + pair[res] = (const(0), pair[a[0]][0]) + elif op == "OpShiftRightLogical" and shift[a[1]] == 32: + pair[res] = (pair[a[0]][1], const(0)) + elif op == "OpSConvert" or (op == "OpShiftRightArithmetic" and shift[a[1]] == 32): + # A sign-extended dword (a 32-bit value widened, or the arithmetic shift by 32, which keeps the high + # word and sign-extends it): the high word is the sign, the value shifted right arithmetically by 31. + n += 1 + p = f"%a64_{n}" + if op == "OpSConvert": + low = a[0] + if rtype.get(low) == "%int": + out.append(f" {p}l = OpBitcast %uint {low}") + low, signed = p + "l", a[0] + else: + out.append(f" {p}i = OpBitcast %int {low}") + signed = p + "i" + else: + low = pair[a[0]][1] + out.append(f" {p}i = OpBitcast %int {low}") + signed = p + "i" + out += [f" {p}s = OpShiftRightArithmetic %int {signed} {const(31)}", + f" {p}h = OpBitcast %uint {p}s"] + pair[res] = (low, p + "h") + elif op in ("OpShiftLeftLogical", "OpShiftRightLogical", "OpShiftRightArithmetic"): + # A shift by k of 1..31: each word takes the bits the other word shifts across (32 - k of them). + n += 1 + (xl, xh), k, p = pair[a[0]], shift[a[1]], f"%a64_{n}" + if op == "OpShiftLeftLogical": + out += [f" {p}l = OpShiftLeftLogical %uint {xl} {const(k)}", + f" {p}a = OpShiftLeftLogical %uint {xh} {const(k)}", + f" {p}b = OpShiftRightLogical %uint {xl} {const(32 - k)}", + f" {p}h = OpBitwiseOr %uint {p}a {p}b"] + else: + out += [f" {p}a = OpShiftRightLogical %uint {xl} {const(k)}", + f" {p}b = OpShiftLeftLogical %uint {xh} {const(32 - k)}", + f" {p}l = OpBitwiseOr %uint {p}a {p}b"] + if op == "OpShiftRightLogical": + out.append(f" {p}h = OpShiftRightLogical %uint {xh} {const(k)}") + else: + out += [f" {p}i = OpBitcast %int {xh}", + f" {p}s = OpShiftRightArithmetic %int {p}i {const(k)}", + f" {p}h = OpBitcast %uint {p}s"] + pair[res] = (p + "l", p + "h") + else: + n += 1 + (xl, xh), (yl, yh), p = pair[a[0]], pair[a[1]], f"%a64_{n}" + if op in ("OpBitwiseOr", "OpBitwiseAnd"): + out += [f" {p}l = {op} %uint {xl} {yl}", f" {p}h = {op} %uint {xh} {yh}"] + else: # the low words with the carry / borrow out, then the high words with it + wide, high = ("OpIAddCarry", "OpIAdd") if op == "OpIAdd" else ("OpISubBorrow", "OpISub") + out += [f" {p}s = {wide} %umul {xl} {yl}", + f" {p}l = OpCompositeExtract %uint {p}s 0", + f" {p}c = OpCompositeExtract %uint {p}s 1", + f" {p}g = {high} %uint {xh} {yh}", + f" {p}h = {high} %uint {p}g {p}c"] + pair[res] = (p + "l", p + "h") + continue + if res in narrow: + out.append(f" {res} = OpCopyObject %uint {pair[narrow[res]][0]}") + continue + if res in cmp: + n += 1 + op, a = cmp[res] + (xl, xh), (yl, yh), p = pair[a[0]], pair[a[1]], f"%a64_{n}" + if _A64_CMP[op] is None: + out += [f" {p}h = OpIEqual %bool {xh} {yh}", f" {p}l = OpIEqual %bool {xl} {yl}", + f" {p}e = OpLogicalAnd %bool {p}h {p}l"] + out.append(f" {res} = OpLogicalNot %bool {p}e" if op == "OpINotEqual" else + f" {res} = OpCopyObject %bool {p}e") + else: + lo_op, swap = _A64_CMP[op] + if swap: + (xl, xh), (yl, yh) = (yl, yh), (xl, xh) + out += [f" {p}h = OpULessThan %bool {xh} {yh}", f" {p}e = OpIEqual %bool {xh} {yh}", + f" {p}l = {lo_op} %bool {xl} {yl}", f" {p}a = OpLogicalAnd %bool {p}e {p}l", + f" {res} = OpLogicalOr %bool {p}h {p}a"] + continue + if res in conv and conv[res][1] in pair: + n += 1 + (xl, xh), p = pair[conv[res][1]], f"%a64_{n}" + out += [f" {p}v = OpCompositeConstruct %v2uint_a {xl} {xh}", + f" {res} = OpBitcast {conv[res][0]} {p}v"] + continue + out.append(line) + # The pair type and the 32-bit constants the rewrite used, declared right after %uint (constants are made as the + # body is rewritten, so they go in once it is done). + at = next(i for i, l in enumerate(out) if l.strip() == "%uint = OpTypeInt 32 0") + 1 + out[at:at] = ["%v2uint_a = OpTypeVector %uint 2"] + \ + [f"{name} = OpConstant %uint {v}" for v, name in sorted(uc.items())] + return "\n".join(out) # SPIR-V caps an instruction at 65,535 words. The dispatch loop's OpSwitch has one (literal, label) pair per block, @@ -20086,6 +20321,8 @@ def main(): help="wave64 vertex, pixel and geometry shaders that are not exact on 32-wide subgroups (tier C of " "tools/wave64_halves.py): warn = count them in the summary and mark them in the index, " "error = refuse them (Unsupported), off = skip the analysis") + ap.add_argument("--int64-addresses", action="store_true", + help="keep 64-bit integer address arithmetic (Int64 / shaderInt64) instead of lowering it to 32-bit pairs") ap.add_argument("--bary-fallback", action="store_true", help="pixel shaders that read raw barycentrics take them from an ordinary interpolated input " "(metadata: bary_fallback_input) instead of BaryCoordKHR, for devices without " @@ -20163,7 +20400,7 @@ def main(): LOOP_LIMIT = a.loop_limit MAX_STRUCTURED_DEPTH = a.max_structured_depth global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV - global PC_TAIL_UBO, ADDRESS_GUARD + global PC_TAIL_UBO, ADDR_PAIR, ADDRESS_GUARD PC_TAIL_UBO = a.pc_tail_ubo ADDRESS_GUARD = a.address_guard global FMA_EXACT @@ -20176,6 +20413,7 @@ def main(): WAVE64_EMULATE = a.wave64_emulate WAVE64_GRAPHICS = a.wave64_graphics BARY_FALLBACK = a.bary_fallback + ADDR_PAIR = not a.int64_addresses TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback MESH_COMPUTE = a.mesh_compute F16_HALVES = a.f16_interp_fallback