upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 15:51:40 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 15:51:40 +0100
commitdf91c6624b69ee4e6c6eeca20ed68d331ed0e728 (patch)
tree323c88b9df89bf8abaa2b98d10808474ab675dc2 /tools
parentb40d8039a98f57b26bd05860febbabbe59b97873 (diff)
parent6a6704df1592e1dc4a3215ddf1423a78adb52045 (diff)
Merge main into test/valu-int-misc (#1492)
Conflicted files: runtime/test/shaders/check.py, scripts/run_gpu_tests.py AI-assisted.
Diffstat (limited to 'tools')
-rw-r--r--tools/anim_index.py2
-rw-r--r--tools/anim_rigs.py172
-rw-r--r--tools/awc_names.py3
-rw-r--r--tools/awc_opus.py43
-rw-r--r--tools/bink_index.py2
-rw-r--r--tools/bink_names.py2
-rw-r--r--tools/bvh_index.py2
-rw-r--r--tools/cf_ref.py25
-rw-r--r--tools/f32_fuzz.py11
-rw-r--r--tools/fspx_unpack.py6
-rw-r--r--tools/gamedata_index.py10
-rw-r--r--tools/gamedata_xml.py2
-rw-r--r--tools/hashdict.py15
-rw-r--r--tools/imhex/rbf0.hexpat96
-rw-r--r--tools/imhex/rpf9.hexpat32
-rw-r--r--tools/int_hw_probe.py767
-rw-r--r--tools/manifest.py34
-rw-r--r--tools/navmesh_decode.py2
-rw-r--r--tools/navmesh_index.py12
-rw-r--r--tools/opus_tags.py4
-rw-r--r--tools/page_index.py2
-rw-r--r--tools/pe_inspect.py4
-rw-r--r--tools/rbf0_index.py2
-rw-r--r--tools/rbf0_tree.py2
-rw-r--r--tools/rdna2spirv.py615
-rw-r--r--tools/restofworld_index.py2
-rw-r--r--tools/rsc8_audio.py2
-rw-r--r--tools/salu_diff.py7
-rw-r--r--tools/shader_link_check.py313
-rw-r--r--tools/spirv_gs_to_compute.py8
-rw-r--r--tools/spirv_interface.py522
-rw-r--r--tools/spirv_metal_set0.py5
-rw-r--r--tools/story_index.py2
-rw-r--r--tools/tex_export.py29
-rw-r--r--tools/text_tables.py87
-rw-r--r--tools/valu_fuzz.py4
-rw-r--r--tools/vk_subgroup_info.py55
-rw-r--r--tools/world_index.py27
-rw-r--r--tools/world_names.py2
-rw-r--r--tools/xdxr_bvh.py10
40 files changed, 2727 insertions, 215 deletions
diff --git a/tools/anim_index.py b/tools/anim_index.py
index e950c0461..29d590685 100644
--- a/tools/anim_index.py
+++ b/tools/anim_index.py
@@ -458,7 +458,7 @@ def write_output(path, rows, summary):
458 json.dump({"summary": summary, "files": rows}, f, indent=1) 458 json.dump({"summary": summary, "files": rows}, f, indent=1)
459 return 459 return
460 with open(path, "w", encoding="utf-8", newline="") as f: 460 with open(path, "w", encoding="utf-8", newline="") as f:
461 w = csv.writer(f) 461 w = csv.writer(f, lineterminator="\n")
462 w.writerow(COLUMNS) 462 w.writerow(COLUMNS)
463 for r in rows: 463 for r in rows:
464 w.writerow([f"0x{r['offset']:x}" if i == 0 else ("" if r[c] is None else r[c]) 464 w.writerow([f"0x{r['offset']:x}" if i == 0 else ("" if r[c] is None else r[c])
diff --git a/tools/anim_rigs.py b/tools/anim_rigs.py
new file mode 100644
index 000000000..40afdc437
--- /dev/null
+++ b/tools/anim_rigs.py
@@ -0,0 +1,172 @@
1"""Read the rig dictionaries in anim.rpf and join the RBF0 rig-set manager's entries to them (ASSET-20).
2
3 python -I tools/anim_rigs.py <package>\\anim.rpf <work>\\anim-rigs.json [--rigs <work>\\rigs.json]
4
5A rig dictionary has the clip dictionary's root layout (docs/animation.md, "Clip dictionaries are RAGE
6resources") with `RIG` + a version byte at +0x70 instead of the pack array. Its map is keyed by `joaat32` of a rig
7path. Each value points at +0x20 to a `RIG` block, which holds tables of 8-byte `(hash, word)` items. `--rigs`
8takes the JSON `anim_index.py --rigs` writes and resolves every rig-set entry (source = rig dictionary name,
9rig = key). The output holds counts and one row per rig dictionary, no item values.
10"""
11import argparse
12import collections
13import json
14import mmap
15import os
16import struct
17import sys
18import zlib
19
20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21import anim_clips # noqa: E402
22import anim_index # noqa: E402
23
24SYSTEM = anim_clips.SYSTEM
25MAGIC = b"RIG"
26
27
28def is_rig_dictionary(data):
29 return len(data) >= 0x78 and data[0x70:0x73] == MAGIC
30
31
32def block_tables(s, at):
33 """Tables of a `RIG` block at page offset `at`: `RIG` + u8 version, u32 length of what follows, then tables
34 `{u32 kind hash; u32 size = 0xC + 8 * count; u32 count; u32 word}` + count × `{u32 hash; u32 word}`, with other
35 bytes between them. Returns (version, length, [(kind, count)])."""
36 if s.d[at:at + 3] != MAGIC:
37 raise anim_clips.DecodeError(f"no RIG block at 0x{at:x}")
38 version, length = s.d[at + 3], s.u32(at + 4)
39 end = min(len(s.d), at + 8 + length)
40 o, tables = at + 8, []
41 while o + 16 <= end:
42 kind, size, count, _word = struct.unpack_from("<4I", s.d, o)
43 if 0 < count < 4096 and size == 0xC + 8 * count and o + 16 + 8 * count <= end:
44 tables.append((kind, count))
45 o += 16 + 8 * count
46 else:
47 o += 4
48 return version, length, tables
49
50
51def parse_rig_dictionary(s):
52 """Root: +0x38 name, +0x48 map (key = joaat32(rig path), high half 0), +0x68 joaat32(name), +0x70 `RIG`."""
53 d = {"name": s.string(0x38), "hash": s.u32(0x68), "version": s.d[0x73], "entries": []}
54 for key, value in s.atmap(0x48):
55 if value is None:
56 continue
57 block = s.ptr(value + 0x20)
58 e = {"key": key & 0xFFFFFFFF, "key_high": key >> 32, "block": block}
59 if block is not None:
60 e["block_version"], e["block_length"], e["tables"] = block_tables(s, block)
61 d["entries"].append(e)
62 return d
63
64
65def _read(path, segments):
66 with open(path, "rb") as fh:
67 data = b""
68 for off, stored, raw in segments:
69 fh.seek(off)
70 data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored))
71 return data
72
73
74def scan(path, start=None, limit=None):
75 rows, walk = anim_index.scan_rpf(path, start, limit)
76 with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m:
77 groups, _unresolved, _gaps = anim_clips.group(m, rows)
78 stats, dicts = collections.Counter(), []
79 for _i, parts in groups:
80 segments = [anim_clips.segment(rows, k) for k in parts]
81 with open(path, "rb") as fh:
82 fh.seek(segments[0][0])
83 head = fh.read(segments[0][1])
84 first = head if segments[0][2] else zlib.decompressobj().decompress(head, 0x80)
85 if not is_rig_dictionary(first):
86 continue
87 s = anim_clips.System(_read(path, segments))
88 try:
89 d = parse_rig_dictionary(s)
90 except (anim_clips.DecodeError, struct.error) as e:
91 stats["rig_dictionaries_unparsed"] += 1
92 dicts.append({"offset": segments[0][0], "error": str(e)[:120]})
93 continue
94 d["offset"], d["streams"], d["system_bytes"] = segments[0][0], len(segments), len(s.d)
95 dicts.append(d)
96 stats["rig_dictionaries"] += 1
97 stats["rig_dictionary_hash_matches_name"] += d["name"] is not None and anim_index.joaat32(d["name"]) == d["hash"]
98 stats[f"rig_dictionary_version:{d['version']}"] += 1
99 for e in d["entries"]:
100 stats["entries"] += 1
101 stats["entries_key_high_zero"] += e["key_high"] == 0
102 if e["block"] is None:
103 stats["entries_without_block"] += 1
104 continue
105 stats["entries_with_block"] += 1
106 stats[f"block_version:{e['block_version']}"] += 1
107 stats["tables"] += len(e["tables"])
108 for kind, count in e["tables"]:
109 stats[f"table_kind:0x{kind:08x}"] += 1
110 stats[f"table_items:0x{kind:08x}"] += count
111 return dicts, {"streams": walk["files"], "dictionary_roots": len(groups), "counts": dict(sorted(stats.items()))}
112
113
114def join_rbf0(dicts, rigs):
115 """Resolve the rig-set manager's entries: source = rig dictionary name, joaat32(rig) = a key there."""
116 keys = {d["name"]: {e["key"] for e in d.get("entries", ())} for d in dicts if d.get("name")}
117 entries = [e for rs in rigs["rbf0"]["rigsets"] for e in rs["entries"]]
118 c = collections.Counter()
119 for e in entries:
120 h = anim_index.joaat32(e["rig"].lower())
121 if h in keys.get(e["source"], ()):
122 c["resolved"] += 1
123 elif any(h in k for k in keys.values()):
124 c["in_another_dictionary"] += 1
125 elif e["source"] not in keys:
126 c["no_dictionary_named_source"] += 1
127 else:
128 c["key_missing"] += 1
129 distinct = {(e["source"], e["rig"].lower()) for e in entries}
130 used = {(src, anim_index.joaat32(r)) for src, r in distinct}
131 c["distinct_rigs"] = len(distinct)
132 c["keys"] = sum(len(k) for k in keys.values())
133 c["keys_named_by_an_entry"] = sum(1 for name, k in keys.items() for h in k if (name, h) in used)
134 return dict(sorted(c.items()))
135
136
137def main():
138 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
139 ap.add_argument("archive", help="anim.rpf")
140 ap.add_argument("out", help="output .json (counts and one row per rig dictionary)")
141 ap.add_argument("--rigs", help="the JSON anim_index.py --rigs wrote, to resolve the RBF0 entries")
142 ap.add_argument("--start", type=anim_index.offset, help="first byte to scan (default: the RPF data start)")
143 ap.add_argument("--limit", type=anim_index.byte_count, help="number of bytes to scan")
144 a = ap.parse_args()
145 try:
146 dicts, summary = scan(a.archive, a.start, a.limit)
147 if a.rigs:
148 with open(a.rigs, encoding="utf-8") as f:
149 summary["rbf0_join"] = join_rbf0(dicts, json.load(f))
150 except ValueError as e:
151 sys.exit(f"{a.archive}: {e}")
152 except OSError as e:
153 sys.exit(f"{e.filename or a.archive}: {e.strerror or e}")
154 rows = [{k: v for k, v in d.items() if k != "entries"} | {"entries": len(d.get("entries", ()))} for d in dicts]
155 try:
156 with open(a.out, "w", encoding="utf-8") as f:
157 json.dump({"summary": summary, "rig_dictionaries": rows}, f, indent=1)
158 except OSError as e:
159 sys.exit(f"{a.out}: cannot write: {e.strerror or e}")
160 c = summary["counts"]
161 print(json.dumps({k: c.get(k, 0) for k in ("rig_dictionaries", "entries", "entries_with_block", "tables")}))
162 if "rbf0_join" in summary:
163 print(json.dumps(summary["rbf0_join"]))
164 return 0
165
166
167if __name__ == "__main__":
168 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
169 sys.stdout.reconfigure(errors="replace")
170 except (AttributeError, ValueError, OSError):
171 pass
172 sys.exit(main())
diff --git a/tools/awc_names.py b/tools/awc_names.py
index d3bc22135..ae8b345fe 100644
--- a/tools/awc_names.py
+++ b/tools/awc_names.py
@@ -321,7 +321,8 @@ def main(argv=None) -> int:
321 json.dump({"summary": summary, "streams": rows}, fh, indent=1) 321 json.dump({"summary": summary, "streams": rows}, fh, indent=1)
322 else: 322 else:
323 with open(a.out, "w", encoding="utf-8", newline="") as fh: 323 with open(a.out, "w", encoding="utf-8", newline="") as fh:
324 w = csv.DictWriter(fh, fieldnames=["source", "bank", "stream_id", "name", "rule"]) 324 w = csv.DictWriter(fh, fieldnames=["source", "bank", "stream_id", "name", "rule"],
325 lineterminator="\n")
325 w.writeheader() 326 w.writeheader()
326 w.writerows(rows) 327 w.writerows(rows)
327 except OSError as error: 328 except OSError as error:
diff --git a/tools/awc_opus.py b/tools/awc_opus.py
index cb96c55a9..5bad0dfbb 100644
--- a/tools/awc_opus.py
+++ b/tools/awc_opus.py
@@ -95,25 +95,47 @@ OPUS_PRE_SKIP = 312
95 95
96def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0, 96def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0,
97 pre_skip: int = OPUS_PRE_SKIP) -> int: 97 pre_skip: int = OPUS_PRE_SKIP) -> int:
98 """length: the stream's declared per-channel sample count at 48 kHz; the last page's granule position is 98 """length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is
99 trimmed to pre_skip + length (Ogg Opus granules count the pre-skip too), so decoders drop the encoder priming 99 trimmed to pre_skip + length (Ogg Opus granules count the pre-skip too), so decoders drop the encoder priming
100 at the start and stop at the exact end instead of the padded last frame.""" 100 at the start and stop at the exact end instead of the padded last frame.
101
102 The EOS page is emitted at the packet that first reaches pre_skip + length; any later packets are encoder
103 padding and are dropped. Clamping only the final page would make its granule smaller than the previous page's
104 when the trim point falls before that page starts, which is invalid Ogg and makes decoders keep the excess.
105 """
106 if not 0 <= pre_skip <= 0xFFFF:
107 raise ValueError(f"pre-skip must be 0..65535, got {pre_skip}")
108 if length < 0:
109 raise ValueError(f"length must be non-negative, got {length}")
110 total = sum(opus_samples(p) for p in packets)
111 if pre_skip > total:
112 pre_skip = total # a granule below the pre-skip makes the stream undecodable
101 head = b"OpusHead" + struct.pack("<BBHIhB", 1, channels, pre_skip, 48000, 0, 0) 113 head = b"OpusHead" + struct.pack("<BBHIhB", 1, channels, pre_skip, 48000, 0, 0)
102 tags = b"OpusTags" + struct.pack("<I", 8) + b"leonida " + struct.pack("<I", 0) 114 tags = b"OpusTags" + struct.pack("<I", 8) + b"leonida " + struct.pack("<I", 0)
103 out = [ogg_page(serial, 0, 0, [head], 0x02), ogg_page(serial, 1, 0, [tags], 0x00)] 115 out = [ogg_page(serial, 0, 0, [head], 0x02), ogg_page(serial, 1, 0, [tags], 0x00)]
104 seq, granule, pending, size = 2, 0, [], 0 116 seq, granule, pending, size = 2, 0, [], 0
117 target = pre_skip + length if length > 0 else None
118 written = 0
119 if not packets:
120 out.append(ogg_page(serial, 2, pre_skip, [], 0x04))
121 write_file(path, b"".join(out))
122 return pre_skip
105 for i, p in enumerate(packets): 123 for i, p in enumerate(packets):
106 pending.append(p) 124 pending.append(p)
107 granule += opus_samples(p) 125 granule += opus_samples(p)
108 size += len(p) 126 size += len(p)
127 reach = target is not None and granule >= target
109 last = i == len(packets) - 1 128 last = i == len(packets) - 1
110 if size > 4000 or len(pending) >= 50 or last: 129 if reach or size > 4000 or len(pending) >= 50 or last:
111 g = min(granule, pre_skip + length) if (last and 0 < length) else granule 130 g = target if reach else granule
112 out.append(ogg_page(serial, seq, g, pending, 0x04 if last else 0x00)) 131 out.append(ogg_page(serial, seq, g, pending, 0x04 if (reach or last) else 0x00))
132 written = g
113 seq += 1 133 seq += 1
114 pending, size = [], 0 134 pending, size = [], 0
135 if reach or last:
136 break
115 write_file(path, b"".join(out)) 137 write_file(path, b"".join(out))
116 return granule 138 return written
117 139
118 140
119def write_file(path: str, data: bytes) -> None: 141def write_file(path: str, data: bytes) -> None:
@@ -293,9 +315,12 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP):
293 pk = opus_packets(d, at, size) 315 pk = opus_packets(d, at, size)
294 if pk: 316 if pk:
295 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and 317 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and
296 # half of it for stereo in all 7,451 measured streams. Fall back to dividing the 318 # half of it for stereo in all 7,451 measured streams. Use it only when it agrees
297 # interleaved count when a synthetic or malformed block leaves the field zero. 319 # with the interleaved +0 count; a synthetic or malformed block that disagrees
298 frames = s["frames"] or s["samples"] // max(1, s["channels"]) 320 # must not silently truncate the real audio.
321 frames = s["frames"]
322 if not frames or frames * s["channels"] != s["samples"]:
323 frames = s["samples"] // max(1, s["channels"])
299 write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames, 324 write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames,
300 pre_skip=pre_skip) 325 pre_skip=pre_skip)
301 counts["opus"] += 1 326 counts["opus"] += 1
diff --git a/tools/bink_index.py b/tools/bink_index.py
index 5b04ec769..2b8232834 100644
--- a/tools/bink_index.py
+++ b/tools/bink_index.py
@@ -276,7 +276,7 @@ def _flat(row, fields):
276def write_csv(path, rows, probe): 276def write_csv(path, rows, probe):
277 fields = BASE_FIELDS + (PROBE_FIELDS if probe else []) 277 fields = BASE_FIELDS + (PROBE_FIELDS if probe else [])
278 with open(path, "w", encoding="utf-8", newline="") as fh: 278 with open(path, "w", encoding="utf-8", newline="") as fh:
279 writer = csv.DictWriter(fh, fieldnames=fields) 279 writer = csv.DictWriter(fh, fieldnames=fields, lineterminator="\n")
280 writer.writeheader() 280 writer.writeheader()
281 for row in rows: 281 for row in rows:
282 writer.writerow(_flat(row, fields)) 282 writer.writerow(_flat(row, fields))
diff --git a/tools/bink_names.py b/tools/bink_names.py
index c8b2e763d..13bc9b12a 100644
--- a/tools/bink_names.py
+++ b/tools/bink_names.py
@@ -303,7 +303,7 @@ def write(out, rows, unmatched, summary):
303 json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1) 303 json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1)
304 else: 304 else:
305 with open(out, "w", encoding="utf-8", newline="") as fh: 305 with open(out, "w", encoding="utf-8", newline="") as fh:
306 w = csv.DictWriter(fh, fieldnames=FIELDS) 306 w = csv.DictWriter(fh, fieldnames=FIELDS, lineterminator="\n")
307 w.writeheader() 307 w.writeheader()
308 w.writerows(rows) 308 w.writerows(rows)
309 309
diff --git a/tools/bvh_index.py b/tools/bvh_index.py
index 94acc06ab..90bcd3bbc 100644
--- a/tools/bvh_index.py
+++ b/tools/bvh_index.py
@@ -363,7 +363,7 @@ def write_outputs(rows, summaries, out, csv_path):
363 "compression_params", "dehydrated", "chunked", "bounds_min", "bounds_max", 363 "compression_params", "dehydrated", "chunked", "bounds_min", "bounds_max",
364 "hash", "off_a0", "hi16", "lo16", "desc_word", "fragment"] 364 "hash", "off_a0", "hi16", "lo16", "desc_word", "fragment"]
365 with open(csv_path, "w", newline="", encoding="utf-8") as f: 365 with open(csv_path, "w", newline="", encoding="utf-8") as f:
366 w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore") 366 w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore", lineterminator="\n")
367 w.writeheader() 367 w.writeheader()
368 for r in rows: 368 for r in rows:
369 r = dict(r) 369 r = dict(r)
diff --git a/tools/cf_ref.py b/tools/cf_ref.py
index 6ceaac292..e8aa45565 100644
--- a/tools/cf_ref.py
+++ b/tools/cf_ref.py
@@ -101,10 +101,14 @@ class WaveMachine(cpu_ref.Machine):
101 return self.vcc & self.wmask 101 return self.vcc & self.wmask
102 if t == "vcc_lo": 102 if t == "vcc_lo":
103 return self.vcc & MASK32 103 return self.vcc & MASK32
104 if t == "vcc_hi":
105 return (self.vcc >> 32) & MASK32
104 if t == "exec": 106 if t == "exec":
105 return self.exec & self.wmask 107 return self.exec & self.wmask
106 if t == "exec_lo": 108 if t == "exec_lo":
107 return self.exec & MASK32 109 return self.exec & MASK32
110 if t == "exec_hi":
111 return 0 if self.wave == 32 else (self.exec >> 32) & MASK32
108 if t == "null": 112 if t == "null":
109 return 0 113 return 0
110 if k == "imm": 114 if k == "imm":
@@ -126,12 +130,19 @@ class WaveMachine(cpu_ref.Machine):
126 if t == "vcc_lo": 130 if t == "vcc_lo":
127 self.vcc = (self.vcc & ~MASK32 & MASK64) | (value & MASK32) 131 self.vcc = (self.vcc & ~MASK32 & MASK64) | (value & MASK32)
128 return 132 return
133 if t == "vcc_hi":
134 self.vcc = (self.vcc & MASK32) | ((value & MASK32) << 32)
135 return
129 if t == "exec": 136 if t == "exec":
130 self.exec = value & MASK64 137 self.exec = value & MASK64
131 return 138 return
132 if t == "exec_lo": 139 if t == "exec_lo":
133 self.exec = (self.exec & ~MASK32 & MASK64) | (value & MASK32) 140 self.exec = (self.exec & ~MASK32 & MASK64) | (value & MASK32)
134 return 141 return
142 if t == "exec_hi":
143 if self.wave == 64:
144 self.exec = (self.exec & MASK32) | ((value & MASK32) << 32)
145 return
135 if t == "null": 146 if t == "null":
136 return 147 return
137 raise Unsupported(dst.get("t", k), self.pc, "mask destination is not modelled") 148 raise Unsupported(dst.get("t", k), self.pc, "mask destination is not modelled")
@@ -201,12 +212,12 @@ class WaveMachine(cpu_ref.Machine):
201 return self._vcmp(ins, base) 212 return self._vcmp(ins, base)
202 if base.startswith("s_cmp_"): 213 if base.startswith("s_cmp_"):
203 self._expect(ins, 2) 214 self._expect(ins, 2)
204 _, cc, ty = base.split("_")[1:] 215 cc, _, ty = base[len("s_cmp_"):].partition("_")
216 if cc not in _CMP or ty not in ("u32", "i32"):
217 raise Unsupported(op, self.pc, "compare is not modelled")
205 x, y = self._int_src(a[0], 0, scalar=True), self._int_src(a[1], 0, scalar=True) 218 x, y = self._int_src(a[0], 0, scalar=True), self._int_src(a[1], 0, scalar=True)
206 if ty == "i32": 219 if ty == "i32":
207 x, y = _signed(x), _signed(y) 220 x, y = _signed(x), _signed(y)
208 elif ty != "u32":
209 raise Unsupported(op, self.pc, "compare type is not modelled")
210 self.scc = 1 if _CMP[cc](x, y) else 0 221 self.scc = 1 if _CMP[cc](x, y) else 0
211 return None 222 return None
212 if base.endswith("_saveexec_b32") or base.endswith("_saveexec_b64"): 223 if base.endswith("_saveexec_b32") or base.endswith("_saveexec_b64"):
@@ -227,9 +238,11 @@ class WaveMachine(cpu_ref.Machine):
227 self._expect(ins, 3) 238 self._expect(ins, 3)
228 mask_op = self._touches_mask(a) 239 mask_op = self._touches_mask(a)
229 if parts[2] == "b64" or mask_op: 240 if parts[2] == "b64" or mask_op:
230 self._check_width(base, op) 241 if parts[2] == "b64" or any(x["k"] == "special" and x["t"] in ("exec", "vcc") for x in a):
231 x, y = self._read_mask(a[1]), self._read_mask(a[2]) 242 self._check_width(base, op)
232 r = _SOP2_LOGIC[parts[1]](x, y, self.wmask) & self.wmask 243 mask = MASK64 if parts[2] == "b64" else MASK32
244 x, y = self._read_mask(a[1]) & mask, self._read_mask(a[2]) & mask
245 r = _SOP2_LOGIC[parts[1]](x, y, mask) & mask
233 self._write_mask(a[0], r) 246 self._write_mask(a[0], r)
234 else: 247 else:
235 x, y = self._int_src(a[1], 0, scalar=True), self._int_src(a[2], 0, scalar=True) 248 x, y = self._int_src(a[1], 0, scalar=True), self._int_src(a[2], 0, scalar=True)
diff --git a/tools/f32_fuzz.py b/tools/f32_fuzz.py
index 96f2f317a..7c23a58fd 100644
--- a/tools/f32_fuzz.py
+++ b/tools/f32_fuzz.py
@@ -465,6 +465,9 @@ ALL_OPS = {
465 "v_trunc_f32": _op("f", lambda x: rounding(x, "trunc")), 465 "v_trunc_f32": _op("f", lambda x: rounding(x, "trunc")),
466 "v_rndne_f32": _op("f", lambda x: rounding(x, "rne")), 466 "v_rndne_f32": _op("f", lambda x: rounding(x, "rne")),
467 "v_rcp_f32": _op("t", lambda x: transcendental("v_rcp_f32", x)), 467 "v_rcp_f32": _op("t", lambda x: transcendental("v_rcp_f32", x)),
468 # v_rcp_iflag_f32 is v_rcp_f32 without the FP exception flags: bit-identical on gfx1030 (design.md, "Denormal
469 # flush and special results"), so it shares the model; clamp and omod are what is new here (SHADER-136).
470 "v_rcp_iflag_f32": _op("t", lambda x: transcendental("v_rcp_f32", x)),
468 "v_rsq_f32": _op("t", lambda x: transcendental("v_rsq_f32", x)), 471 "v_rsq_f32": _op("t", lambda x: transcendental("v_rsq_f32", x)),
469 "v_sqrt_f32": _op("t", lambda x: transcendental("v_sqrt_f32", x)), 472 "v_sqrt_f32": _op("t", lambda x: transcendental("v_sqrt_f32", x)),
470 "v_exp_f32": _op("e", lambda x: transcendental("v_exp_f32", x)), 473 "v_exp_f32": _op("e", lambda x: transcendental("v_exp_f32", x)),
@@ -822,8 +825,8 @@ HW_PRIMARY = "flush"
822 825
823# Ops whose omod does not depend on the f32 denormal mode: the transcendental unit and the cube ops flush or select 826# Ops whose omod does not depend on the f32 denormal mode: the transcendental unit and the cube ops flush or select
824# whatever MODE says, and gfx1150 applies their omod with denormals kept (measured, 'omod' table). 827# whatever MODE says, and gfx1150 applies their omod with denormals kept (measured, 'omod' table).
825OMOD_IGNORES_DENORM_MODE = ("v_rcp_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", "v_log_f32", "v_cubeid_f32", 828OMOD_IGNORES_DENORM_MODE = ("v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", "v_log_f32",
826 "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32") 829 "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32")
827 830
828 831
829def omod_active(mode, op=None): 832def omod_active(mode, op=None):
@@ -1140,8 +1143,8 @@ FAMILIES = [
1140 ("f16 convert", ("v_cvt_f32_f16", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32")), 1143 ("f16 convert", ("v_cvt_f32_f16", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32")),
1141 ("v_cvt_pk_u8_f32", ("v_cvt_pk_u8_f32",)), 1144 ("v_cvt_pk_u8_f32", ("v_cvt_pk_u8_f32",)),
1142 ("floor / ceil / trunc / rndne", ("v_floor_f32", "v_ceil_f32", "v_trunc_f32", "v_rndne_f32")), 1145 ("floor / ceil / trunc / rndne", ("v_floor_f32", "v_ceil_f32", "v_trunc_f32", "v_rndne_f32")),
1143 ("rcp / rsq / sqrt / exp / log (exact inputs)", ("v_rcp_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", 1146 ("rcp / rsq / sqrt / exp / log (exact inputs)", ("v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32",
1144 "v_log_f32")), 1147 "v_exp_f32", "v_log_f32")),
1145 ("cube", ("v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32")), 1148 ("cube", ("v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32")),
1146 ("v_cmp_class_f32", ("v_cmp_class_f32",)), 1149 ("v_cmp_class_f32", ("v_cmp_class_f32",)),
1147 ("min / max / med3 (hardware only)", HW_ONLY_OPS), 1150 ("min / max / med3 (hardware only)", HW_ONLY_OPS),
diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py
index ea79e8001..6c18bb7b7 100644
--- a/tools/fspx_unpack.py
+++ b/tools/fspx_unpack.py
@@ -201,7 +201,11 @@ def main(argv=None) -> int:
201 stage = psv_stage(dxbc_parts(container)) if container else None 201 stage = psv_stage(dxbc_parts(container)) if container else None
202 meta["source"] = {"file": os.path.basename(path), "offset": off} 202 meta["source"] = {"file": os.path.basename(path), "offset": off}
203 entry = {"file": name + ".dxbc", "stage": "cs" if stage in (None, STAGE_COMPUTE) else f"psv{stage}", 203 entry = {"file": name + ".dxbc", "stage": "cs" if stage in (None, STAGE_COMPUTE) else f"psv{stage}",
204 "source_offset": off, "threads": meta["threads"], "wave32": meta["wave32"]} 204 "source_offset": off}
205 if "threads" in meta:
206 entry["threads"] = meta["threads"]
207 if "wave32" in meta:
208 entry["wave32"] = meta["wave32"]
205 if container: 209 if container:
206 with open(os.path.join(a.out, name + ".dxbc"), "wb") as f: 210 with open(os.path.join(a.out, name + ".dxbc"), "wb") as f:
207 f.write(container) 211 f.write(container)
diff --git a/tools/gamedata_index.py b/tools/gamedata_index.py
index f82413171..85f4f7023 100644
--- a/tools/gamedata_index.py
+++ b/tools/gamedata_index.py
@@ -41,6 +41,10 @@ XML_CLOSE_TAIL = re.compile(rb"</([A-Za-z_][\w.:-]*)>\s*$")
41# Tag-like text inside these cannot open or close an element. 41# Tag-like text inside these cannot open or close an element.
42XML_NON_TAG = re.compile(rb"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>", re.S) 42XML_NON_TAG = re.compile(rb"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>", re.S)
43MAGIC = {b"MHIU": "MHIU", b"PAMH": "PAMH", b"SPS1Z": "SPS1Z", b"RBF0": "RBF0", b"PSIN": "PSIN"} 43MAGIC = {b"MHIU": "MHIU", b"PAMH": "PAMH", b"SPS1Z": "SPS1Z", b"RBF0": "RBF0", b"PSIN": "PSIN"}
44# A resource whose page directory starts the stream carries "0DRP" at +16 (docs/animation.md, "0DRP page marker").
45# Its first 4 KiB can be over 95% printable, so without this check such a stream reads as text, and as XML when it
46# holds a "<": data.rpf has 337 of them and no XML at all (docs/gamedata.md, "Relationship to data.rpf").
47PAGE_MARKER, PAGE_MARKER_AT = b"0DRP", 16
44 48
45 49
46def printable(data: bytes) -> float: 50def printable(data: bytes) -> float:
@@ -123,6 +127,8 @@ def stream_kind(data: bytes, row: dict) -> str:
123 for magic in MAGIC: 127 for magic in MAGIC:
124 if data.startswith(magic): 128 if data.startswith(magic):
125 return "other" 129 return "other"
130 if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER:
131 return "other"
126 if printable(data) > 0.95: 132 if printable(data) > 0.95:
127 return "text" 133 return "text"
128 return "binary" 134 return "binary"
@@ -132,6 +138,8 @@ def magic_name(data: bytes) -> str:
132 for magic, name in MAGIC.items(): 138 for magic, name in MAGIC.items():
133 if data.startswith(magic): 139 if data.startswith(magic):
134 return name 140 return name
141 if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER:
142 return PAGE_MARKER.decode()
135 return "" 143 return ""
136 144
137 145
@@ -344,7 +352,7 @@ def write_csv(path: str, rows: list) -> None:
344 fields = ["offset", "offset_hex", "stored", "size", "type", "root", "detail", "chunks", 352 fields = ["offset", "offset_hex", "stored", "size", "type", "root", "detail", "chunks",
345 "complete", "header"] 353 "complete", "header"]
346 with open(path, "w", newline="", encoding="utf-8") as f: 354 with open(path, "w", newline="", encoding="utf-8") as f:
347 w = csv.DictWriter(f, fieldnames=fields) 355 w = csv.DictWriter(f, fieldnames=fields, lineterminator="\n")
348 w.writeheader() 356 w.writeheader()
349 w.writerows(rows) 357 w.writerows(rows)
350 358
diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py
index ab91ae7da..02cea8dee 100644
--- a/tools/gamedata_xml.py
+++ b/tools/gamedata_xml.py
@@ -518,7 +518,7 @@ def write_csv(path: str, rows: list) -> None:
518 "parent_path", "parent_file", "xi_include", "type_attrs", "type_values", "content_values", 518 "parent_path", "parent_file", "xi_include", "type_attrs", "type_values", "content_values",
519 "error"] 519 "error"]
520 with open(path, "w", newline="", encoding="utf-8") as f: 520 with open(path, "w", newline="", encoding="utf-8") as f:
521 writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore") 521 writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore", lineterminator="\n")
522 writer.writeheader() 522 writer.writeheader()
523 for row in rows: 523 for row in rows:
524 out = dict(row) 524 out = dict(row)
diff --git a/tools/hashdict.py b/tools/hashdict.py
index cc8da2ace..acf668d79 100644
--- a/tools/hashdict.py
+++ b/tools/hashdict.py
@@ -6,6 +6,7 @@ When multiple names share a hash, the dictionary keeps the lexicographically fir
6 6
7Usage: 7Usage:
8 python -I hashdict.py <carve dir> --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3] 8 python -I hashdict.py <carve dir> --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3]
9 <carve dir> holds one folder per archive (<work>/carve), or is one archive's folder (<work>/carve/common).
9 python -I hashdict.py --lookup <hashes.json> 0x28cca8df ... 10 python -I hashdict.py --lookup <hashes.json> 0x28cca8df ...
10""" 11"""
11import argparse 12import argparse
@@ -91,11 +92,17 @@ def main():
91 what = "is not a folder" if os.path.exists(a.carve) else "does not exist" 92 what = "is not a folder" if os.path.exists(a.carve) else "does not exist"
92 print(f"ERROR: the carve folder {a.carve} {what}", file=sys.stderr) 93 print(f"ERROR: the carve folder {a.carve} {what}", file=sys.stderr)
93 return 2 94 return 2
95 # A folder with its own index.json is one archive's carve (<work>\carve\common, the folder the gamedata_*
96 # tools take): harvest it as that archive. Otherwise each subfolder with an index.json is one archive.
97 if os.path.isfile(os.path.join(a.carve, "index.json")):
98 archives = [(os.path.basename(os.path.normpath(os.path.abspath(a.carve))), a.carve)]
99 else:
100 archives = [(d, os.path.join(a.carve, d)) for d in sorted(os.listdir(a.carve))]
94 # The dictionary is written after the harvest: an --out naming one of the inputs would replace it. 101 # The dictionary is written after the harvest: an --out naming one of the inputs would replace it.
95 # samefile also catches a case-only difference on Windows and macOS's default volume. 102 # samefile also catches a case-only difference on Windows and macOS's default volume.
96 if os.path.exists(a.out): 103 if os.path.exists(a.out):
97 inputs = [x for x in a.extra if os.path.isfile(x)] 104 inputs = [x for x in a.extra if os.path.isfile(x)]
98 inputs += [os.path.join(a.carve, d, "index.json") for d in os.listdir(a.carve)] 105 inputs += [os.path.join(d, "index.json") for _, d in archives]
99 for x in inputs: 106 for x in inputs:
100 try: 107 try:
101 same = os.path.isfile(x) and os.path.samefile(a.out, x) 108 same = os.path.isfile(x) and os.path.samefile(a.out, x)
@@ -108,8 +115,8 @@ def main():
108 strings = set() 115 strings = set()
109 full = set(a.archives.split(",")) 116 full = set(a.archives.split(","))
110 missing = [] # carved blobs an index.json lists that can't be read: skipped, reported 117 missing = [] # carved blobs an index.json lists that can't be read: skipped, reported
111 for arch in sorted(os.listdir(a.carve)): 118 for arch, arch_dir in archives:
112 p = os.path.join(a.carve, arch, "index.json") 119 p = os.path.join(arch_dir, "index.json")
113 if not os.path.isfile(p): 120 if not os.path.isfile(p):
114 continue 121 continue
115 try: 122 try:
@@ -126,7 +133,7 @@ def main():
126 continue 133 continue
127 meta = r["head"].startswith("5053494e") or r["head"].startswith("52424630") 134 meta = r["head"].startswith("5053494e") or r["head"].startswith("52424630")
128 if arch in full or meta: 135 if arch in full or meta:
129 blob = os.path.join(a.carve, arch, f"{r['off']:012x}.bin") 136 blob = os.path.join(arch_dir, f"{r['off']:012x}.bin")
130 try: 137 try:
131 with open(blob, "rb") as f: 138 with open(blob, "rb") as f:
132 data = f.read() 139 data = f.read()
diff --git a/tools/imhex/rbf0.hexpat b/tools/imhex/rbf0.hexpat
new file mode 100644
index 000000000..8d311e099
--- /dev/null
+++ b/tools/imhex/rbf0.hexpat
@@ -0,0 +1,96 @@
1// ImHex pattern for one RBF0 resource: RAGE's binary form of an XML data file.
2//
3// The grammar is the one measured in docs/rbf0.md (section 3) and parsed by tools/rbf0_index.py (parse_rbf0):
4//
5// 0x00 "RBF0"
6// 0x04 FB FF 01 00 optional prologue. With it, integers and floats are 8 bytes ("wide"); without it they are
7// 4 bytes ("narrow") and the records start at 0x04. What the four bytes mean is not established;
8// the width follows them in every measured resource (docs/rbf0.md).
9// records, each a u8 descriptor index and a u8 type:
10// FF FF close the open element
11// FD FF text for the open element: u32 length, then that many bytes
12// index == descriptors so far a new descriptor: u16 name length, then the UTF-8 name, before the payload
13// type 0x00 open an element: u16 0, u16 0, u16 attribute count
14// type 0x10 integer 0x20 true 0x30 false 0x40 float 0x50 three floats
15// type 0x60 string: u16 length, then UTF-8 bytes
16// The stream has no length field and no section table: it ends where the root element closes, and the pattern
17// stops there.
18//
19// Open an inflated, joined resource, not the archive. A resource larger than 64 KiB is split over several zlib
20// streams, with no header on the continuations (docs/rbf0.md section 2); tools/rbf0_index.py joins them.
21
22#pragma description RBF0 record stream (binary XML, docs/rbf0.md)
23#pragma endian little
24#pragma magic [ 52 42 46 30 ] @ 0x00
25// The largest measured resource has 68,398 elements and about twice as many records.
26#pragma array_limit 4194304
27#pragma pattern_limit 33554432
28
29import std.mem;
30import std.io;
31
32bool g_wide = std::mem::size() >= 8 && std::mem::read_unsigned(0x04, 4) == 0x0001FFFB;
33u32 g_descriptors = 0;
34u32 g_depth = 0;
35bool g_done = false;
36
37struct Header {
38 char magic[4];
39 if (g_wide) {
40 u8 prologue[4] [[comment("FB FF 01 00: 8-byte integers and floats follow")]];
41 }
42};
43
44struct Record {
45 u8 index;
46 u8 type;
47 if (index == 0xFF) {
48 if (g_depth > 0) g_depth -= 1;
49 if (g_depth == 0) g_done = true;
50 } else if (index == 0xFD) {
51 u32 text_length;
52 char text[text_length];
53 } else {
54 if (index == g_descriptors) {
55 u16 name_length;
56 char name[name_length] [[comment("new descriptor")]];
57 g_descriptors += 1;
58 }
59 if (type == 0x00) {
60 u16 word0;
61 u16 word1;
62 u16 attribute_count;
63 g_depth += 1;
64 } else if (type == 0x10) {
65 if (g_wide) {
66 u64 value_int;
67 } else {
68 u32 value_int;
69 }
70 } else if (type == 0x40) {
71 if (g_wide) {
72 double value_float;
73 } else {
74 float value_float;
75 }
76 } else if (type == 0x50) {
77 if (g_wide) {
78 double value_vec3[3];
79 } else {
80 float value_vec3[3];
81 }
82 } else if (type == 0x60) {
83 u16 string_length;
84 char value_string[string_length];
85 }
86 }
87} [[format("format_record")]];
88
89fn format_record(Record r) {
90 if (r.index == 0xFF) return "close";
91 if (r.index == 0xFD) return "text";
92 return std::format("descriptor {} type 0x{:02X}", r.index, r.type);
93};
94
95Header header @ 0x00;
96Record records[while(!g_done && !std::mem::eof())] @ sizeof(header);
diff --git a/tools/imhex/rpf9.hexpat b/tools/imhex/rpf9.hexpat
new file mode 100644
index 000000000..0fbc1e450
--- /dev/null
+++ b/tools/imhex/rpf9.hexpat
@@ -0,0 +1,32 @@
1// ImHex pattern for the header of an RPF9 archive.
2//
3// Only measured fields are named (docs/rpf.md "What is readable"; docs/story.md "Signatures actually observed"):
4// 0x00 "9FPR" RPF9 stored little-endian
5// 0x04 data offset u32, where the data area (zlib streams laid end to end) starts
6// 0x08 u32 present in every header; meaning not established
7// 0x0C u32 present in every header; meaning not established
8// Everything from 0x10 to the data offset is the rest of the header and the table of contents. The TOC is
9// encrypted/packed: this pattern shows that range as opaque bytes and decodes nothing in it (no keys, no decryption).
10//
11// This describes the archive's own header at offset 0. Nested RPF9 headers occur inside the data area
12// (docs/story.md); their offsets are not covered here.
13
14#pragma description RPF9 archive header, opaque TOC and data area start (docs/rpf.md)
15#pragma endian little
16#pragma magic [ 39 46 50 52 ] @ 0x00
17
18import std.mem;
19import std.sys;
20
21struct Rpf9Header {
22 char magic[4] [[comment("\"9FPR\": RPF9 stored little-endian")]];
23 u32 data_offset [[comment("start of the data area (docs/rpf.md)")]];
24 u32 u32_08 [[comment("meaning not established")]];
25 u32 u32_0c [[comment("meaning not established")]];
26};
27
28Rpf9Header header @ 0x00;
29std::assert(header.data_offset >= sizeof(header) && header.data_offset <= std::mem::size(),
30 "the data offset is outside the file");
31u8 header_rest_and_toc[header.data_offset - sizeof(header)] @ sizeof(header)
32 [[comment("rest of the header and the table of contents: encrypted/packed, not decoded")]];
diff --git a/tools/int_hw_probe.py b/tools/int_hw_probe.py
new file mode 100644
index 000000000..2e94569bc
--- /dev/null
+++ b/tools/int_hw_probe.py
@@ -0,0 +1,767 @@
1r"""SHADER-137: RDNA2 hardware probe for the integer contract rows checked only on the CPU.
2
3Runs small, self-contained RDNA2 instruction sequences natively on an AMD GPU through tools/hw_oracle (wave32 and
4wave64) and compares every output word with Leonida's live translator (tools/rdna2spirv.py ->
5tests/semantic/spirv_mini_interp.py). Standard library only; no game files.
6
7Groups covered (each references its contract row in docs/design.md):
8 salu_absdiff_mulhi s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (SCC written vs kept)
9 salu_lshl_add s_lshl1..4_add_u32 (64-bit carry / shift-out into SCC)
10 salu_sext_flbit s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32 (SCC kept)
11 salu_cmov_pack s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16 (SCC kept)
12 salu_bfe_past31 s_bfe_u32, s_bfe_i32 with offset + width > 32 and width 0
13 salu_64_data s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64
14 salu_quad_bitrep s_quadmask_b32/b64, s_bitreplicate_b64_b32
15 salu_64_bitwise s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64 on scalar data
16 salu_movrels s_movrels_b32, s_movrels_b64 (M0 indexing, SCC kept)
17 valu_add_nc_clamp v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16 with clamp
18 valu_add_co_clamp v_add/sub/subrev_co[_ci]_u32 with clamp (saturation + carry)
19 valu_mad64 v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and inactive EXEC lane)
20 valu_sad_lerp v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8
21 valu_qsad_mqsad v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8
22 valu_mul24_sh64 v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64
23 valu_mad16 v_mad_u16, v_mad_i16 (clamp, op_sel, kept half)
24 valu_cvt_16 v_cvt_f16_u16/i16, v_cvt_u16/i16_f16 (kept half, op_sel, NaN, inf)
25 valu_cvt_flr_rpi v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 (exact floor(x+0.5), signed NaN)
26 valu_cvt_pknorm v_cvt_pknorm_i16_f32, v_cvt_pknorm_u16_f32 (ties, saturation, NaN)
27
28Usage:
29 python -I tools/int_hw_probe.py # translator side only (CPU)
30 python -I tools/int_hw_probe.py --oracle hw # native AMD GPU only (wave32 + wave64)
31 python -I tools/int_hw_probe.py --oracle both # compare hardware vs translator
32 python -I tools/int_hw_probe.py --oracle both --strict # fail on known translator divergences too
33 python -I tools/int_hw_probe.py --self-test
34
35Exit codes:
36 0 all unexpected comparisons match (and wave32 == wave64 on hardware)
37 1 at least one unexpected mismatch, wave32/64 diff, or known divergence under --strict
38 2 bad CLI arguments or harness error
39 77 hardware oracle requested but unavailable on this machine
40"""
41import argparse
42import json
43import os
44import struct
45import sys
46import tempfile
47import warnings
48
49HERE = os.path.dirname(os.path.abspath(__file__))
50ROOT = os.path.dirname(HERE)
51sys.dont_write_bytecode = True
52for p in (HERE, os.path.join(ROOT, "tests", "semantic")):
53 if p not in sys.path:
54 sys.path.insert(0, p)
55
56import rdna2spirv # noqa: E402
57import spirv_mini_interp # noqa: E402
58
59STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
60SENTINEL = 0x5A5A5A5A
61
62# Live translator divergences confirmed on AMD Radeon 680M (gfx1035, RDNA2, wave32 & wave64).
63# Each entry maps case.name -> (tag, expected_hw_words, reason).
64KNOWN_DIVERGENCES = {
65 "v_add_co_u32_clamp": (
66 "co_clamp_ignored",
67 [0xFFFFFFFF, 0x00000001, 0x00000000, 0x00000001],
68 "translator ignores VOP3 clamp on v_add_co_u32 / v_sub_co_u32",
69 ),
70 "v_subrev_co_u32_clamp": (
71 "co_clamp_ignored",
72 [0x00000000, 0x00000001, 0x00000000, 0x00000001],
73 "translator ignores VOP3 clamp on v_subrev_co_u32 / v_subrev_co_ci_u32",
74 ),
75 "v_add_co_ci_u32_clamp": (
76 "co_clamp_ignored",
77 [0xFFFFFFFF, 0x00000001, 0x00000000, 0x00000001],
78 "translator ignores VOP3 clamp on v_add_co_ci_u32 / v_sub_co_ci_u32",
79 ),
80 "v_cvt_rpi_precision": (
81 "cvt_rpi_exact_half",
82 [0x00000000, 0x00800001, 0x00FFFFFF, 0x00000000],
83 "hardware computes exact floor(x + 0.5); translator rounds x + 0.5 in binary32 first",
84 ),
85 "v_cvt_flr_rpi_nan_inf": (
86 "cvt_flr_rpi_nan_sign",
87 [0x7FFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000000],
88 "hardware saturates NaN by sign (+NaN -> 0x7fffffff, -NaN -> 0x80000000); translator gives 0",
89 ),
90}
91
92
93class Case:
94 """One self-contained 4-word probe. `body` leaves results in v8..v11 and must not clobber s[0:3] or v0.
95 For wave-size-dependent mask instructions, `{vcc}`, `{exec}`, `{smov}`, `{stmp}` expand to wave32/wave64 forms."""
96
97 __slots__ = ("group", "name", "body", "note")
98
99 def __init__(self, group, name, body, note=""):
100 self.group = group
101 self.name = name
102 self.body = tuple(body)
103 self.note = note
104
105 def lines(self, wave=32):
106 vcc = "vcc_lo" if wave == 32 else "vcc"
107 exc = "exec_lo" if wave == 32 else "exec"
108 smov = "s_mov_b32" if wave == 32 else "s_mov_b64"
109 stmp = "s14" if wave == 32 else "s[14:15]"
110 return [ln.format(vcc=vcc, exec=exc, smov=smov, stmp=stmp) for ln in self.body]
111
112
113def _scc_seed(val):
114 return "s_cmp_eq_u32 0, 0" if val else "s_cmp_eq_u32 0, 1"
115
116
117def _salu32_pair(group, name, setup, op_line, note=""):
118 """Run one 32-bit scalar op twice: once with SCC preset to 0 (v8=D, v9=SCC) and once with SCC preset to 1
119 (v10=D, v11=SCC), so 'SCC kept' and 'SCC written' are both directly observed."""
120 body = [
121 *setup, _scc_seed(0), op_line,
122 "s_cselect_b32 s30, 1, 0", "v_mov_b32 v8, s6", "v_mov_b32 v9, s30",
123 *setup, _scc_seed(1), op_line,
124 "s_cselect_b32 s30, 1, 0", "v_mov_b32 v10, s6", "v_mov_b32 v11, s30",
125 ]
126 return Case(group, name, body, note)
127
128
129def _salu64_case(group, name, setup, op_line, scc_in, note=""):
130 """Run one 64-bit scalar op with SCC preset to scc_in; output v8=s6 (lo), v9=s7 (hi), v10=SCC, v11=0."""
131 body = [
132 *setup, _scc_seed(scc_in), op_line,
133 "s_cselect_b32 s30, 1, 0",
134 "v_mov_b32 v8, s6", "v_mov_b32 v9, s7", "v_mov_b32 v10, s30", "v_mov_b32 v11, 0",
135 ]
136 return Case(group, name, body, note)
137
138
139def _valu4_case(group, name, body, note=""):
140 return Case(group, name, body, note)
141
142
143def build_cases():
144 cases = []
145
146 # 1. s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (docs/design.md)
147 cases += [
148 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_basic",
149 ["s_mov_b32 s4, 10", "s_mov_b32 s5, 25"],
150 "s_absdiff_i32 s6, s4, s5", "|10 - 25| = 15, SCC=1"),
151 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_equal",
152 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"],
153 "s_absdiff_i32 s6, s4, s5", "equal -> 0, SCC=0"),
154 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_wrap_max_min",
155 ["s_mov_b32 s4, 0x7fffffff", "s_mov_b32 s5, 0x80000000"],
156 "s_absdiff_i32 s6, s4, s5", "0x7fffffff - 0x80000000 wraps to -1 -> abs 1, SCC=1"),
157 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_int_min",
158 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0"],
159 "s_absdiff_i32 s6, s4, s5", "diff = INT_MIN stays 0x80000000, SCC=1"),
160 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_min_min",
161 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"],
162 "s_mul_hi_i32 s6, s4, s5", "(-2^31)*(-2^31) >> 32 = 0x40000000, SCC kept"),
163 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_neg_pos",
164 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 2"],
165 "s_mul_hi_i32 s6, s4, s5", "(-1)*2 >> 32 = 0xffffffff, SCC kept"),
166 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_u32_max_max",
167 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
168 "s_mul_hi_u32 s6, s4, s5", "(2^32-1)^2 >> 32 = 0xfffffffe, SCC kept"),
169 ]
170
171 # 2. s_lshl1..4_add_u32 (64-bit shift-out + add carry into SCC)
172 for shift in (1, 2, 3, 4):
173 op = f"s_lshl{shift}_add_u32"
174 high_bit = 1 << (32 - shift)
175 cases += [
176 _salu32_pair("salu_lshl_add", f"{op}_no_carry",
177 ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 5"],
178 f"{op} s6, s4, s5", "no shift-out, no add carry -> SCC=0"),
179 _salu32_pair("salu_lshl_add", f"{op}_shift_out_only",
180 [f"s_mov_b32 s4, 0x{high_bit:08x}", "s_mov_b32 s5, 0"],
181 f"{op} s6, s4, s5", "bit shifted out of S0 with S1=0 -> D=0, SCC=1"),
182 _salu32_pair("salu_lshl_add", f"{op}_add_carry_only",
183 ["s_mov_b32 s4, 1", "s_mov_b32 s5, 0xffffffff"],
184 f"{op} s6, s4, s5", "add carry without shift-out -> SCC=1"),
185 ]
186
187 # 3. s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32
188 cases += [
189 _salu32_pair("salu_sext_flbit", "s_sext_i8_neg",
190 ["s_mov_b32 s4, 0x12345680"], "s_sext_i32_i8 s6, s4", "0x80 -> 0xffffff80, SCC kept"),
191 _salu32_pair("salu_sext_flbit", "s_sext_i8_pos",
192 ["s_mov_b32 s4, 0xffffff7f"], "s_sext_i32_i8 s6, s4", "0x7f -> 0x0000007f, SCC kept"),
193 _salu32_pair("salu_sext_flbit", "s_sext_i16_neg",
194 ["s_mov_b32 s4, 0x00008001"], "s_sext_i32_i16 s6, s4", "0x8001 -> 0xffff8001, SCC kept"),
195 _salu32_pair("salu_sext_flbit", "s_sext_i16_pos",
196 ["s_mov_b32 s4, 0xffff7fff"], "s_sext_i32_i16 s6, s4", "0x7fff -> 0x00007fff, SCC kept"),
197 _salu32_pair("salu_sext_flbit", "s_flbit_i32_zero",
198 ["s_mov_b32 s4, 0"], "s_flbit_i32 s6, s4", "0 -> 0xffffffff, SCC kept"),
199 _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg1",
200 ["s_mov_b32 s4, 0xffffffff"], "s_flbit_i32 s6, s4", "-1 -> 0xffffffff, SCC kept"),
201 _salu32_pair("salu_sext_flbit", "s_flbit_i32_pos1",
202 ["s_mov_b32 s4, 1"], "s_flbit_i32 s6, s4", "1 -> 30, SCC kept"),
203 _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg16",
204 ["s_mov_b32 s4, 0xfffffff0"], "s_flbit_i32 s6, s4", "-16 -> 27, SCC kept"),
205 _salu32_pair("salu_sext_flbit", "s_flbit_i32_int_min",
206 ["s_mov_b32 s4, 0x80000000"], "s_flbit_i32 s6, s4", "INT_MIN -> 0, SCC kept"),
207 ]
208
209 # 4. s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16
210 cases += [
211 _salu32_pair("salu_cmov_pack", "s_cmov_b32",
212 ["s_mov_b32 s4, 0x11223344", "s_mov_b32 s6, 0xaabbccdd"],
213 "s_cmov_b32 s6, s4", "SCC=0 keeps D, SCC=1 takes S0, SCC kept"),
214 _salu32_pair("salu_cmov_pack", "s_cmovk_i32_neg",
215 ["s_mov_b32 s6, 0x12345678"],
216 "s_cmovk_i32 s6, -300", "SCC=0 keeps D, SCC=1 sign-extends imm16, SCC kept"),
217 _salu32_pair("salu_cmov_pack", "s_pack_ll",
218 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
219 "s_pack_ll_b32_b16 s6, s4, s5", "{S1.lo, S0.lo} = 0x44442222, SCC kept"),
220 _salu32_pair("salu_cmov_pack", "s_pack_lh",
221 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
222 "s_pack_lh_b32_b16 s6, s4, s5", "{S1.hi, S0.lo} = 0x33332222, SCC kept"),
223 _salu32_pair("salu_cmov_pack", "s_pack_hh",
224 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
225 "s_pack_hh_b32_b16 s6, s4, s5", "{S1.hi, S0.hi} = 0x33331111, SCC kept"),
226 ]
227
228 # 5. s_bfe_u32 / s_bfe_i32 past bit 31
229 cases += [
230 _salu32_pair("salu_bfe_past31", "s_bfe_i32_past31",
231 ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0x7f001c"],
232 "s_bfe_i32 s6, s4, s5", "off=28 width=127 stops at bit 31 -> 0xfffffffd, SCC=1"),
233 _salu32_pair("salu_bfe_past31", "s_bfe_u32_past31",
234 ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0xff7f001c"],
235 "s_bfe_u32 s6, s4, s5", "upper bits ignored, stops at bit 31 -> 0x0000000d, SCC=1"),
236 _salu32_pair("salu_bfe_past31", "s_bfe_i32_width0",
237 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0x00000005"],
238 "s_bfe_i32 s6, s4, s5", "width=0 -> 0, SCC=0"),
239 ]
240
241 # 6. 64-bit scalar data ops (s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64)
242 cases += [
243 _salu64_case("salu_64_data", "s_brev_b64_scc1",
244 ["s_mov_b32 s4, 0x80000001", "s_mov_b32 s5, 0x12345678"],
245 "s_brev_b64 s[6:7], s[4:5]", 1, "bit-reverse 64-bit pair, SCC kept"),
246 _salu64_case("salu_64_data", "s_bfe_u64_cross_past63",
247 ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"],
248 "s_bfe_u64 s[6:7], s[4:5], s8", 0, "off=60 width=127 stops at bit 63 -> 0xd, SCC=1"),
249 _salu64_case("salu_64_data", "s_bfe_i64_past63",
250 ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"],
251 "s_bfe_i64 s[6:7], s[4:5], s8", 0, "off=60 width=127 sign-extends 0xd -> -3, SCC=1"),
252 _salu64_case("salu_64_data", "s_bfe_u64_width0",
253 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff", "s_mov_b32 s8, 0x00000010"],
254 "s_bfe_u64 s[6:7], s[4:5], s8", 1, "width=0 -> 0, SCC=0"),
255 _salu64_case("salu_64_data", "s_bitset0_b64_hi",
256 ["s_mov_b32 s6, 0xffffffff", "s_mov_b32 s7, 0xffffffff", "s_mov_b32 s8, 63"],
257 "s_bitset0_b64 s[6:7], s8", 1, "clear bit 63, SCC kept"),
258 _salu64_case("salu_64_data", "s_bitset1_b64_mod64",
259 ["s_mov_b32 s6, 0", "s_mov_b32 s7, 0", "s_mov_b32 s8, 97"],
260 "s_bitset1_b64 s[6:7], s8", 0, "set bit 97 & 63 = 33 (hi bit 1), SCC kept"),
261 _salu32_pair("salu_64_data", "s_flbit_i32_b64_zero",
262 ["s_mov_b32 s4, 0", "s_mov_b32 s5, 0"],
263 "s_flbit_i32_b64 s6, s[4:5]", "0 -> -1, SCC kept"),
264 _salu32_pair("salu_64_data", "s_flbit_i32_b64_lo",
265 ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 0"],
266 "s_flbit_i32_b64 s6, s[4:5]", "bit 16 -> 47 leading zeros, SCC kept"),
267 _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg",
268 ["s_mov_b32 s4, 0xfffffff0", "s_mov_b32 s5, 0xffffffff"],
269 "s_flbit_i32_i64 s6, s[4:5]", "-16 -> 59 sign bits, SCC kept"),
270 _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg1",
271 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
272 "s_flbit_i32_i64 s6, s[4:5]", "-1 -> -1, SCC kept"),
273 ]
274
275 # 7. s_quadmask_b32/b64, s_bitreplicate_b64_b32
276 cases += [
277 _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_nz",
278 ["s_mov_b32 s4, 0x10080041"],
279 "s_quadmask_b32 s6, s4", "quads 0,1,4,7 set -> 0x93, SCC=1"),
280 _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_zero",
281 ["s_mov_b32 s4, 0"],
282 "s_quadmask_b32 s6, s4", "0 -> 0, SCC=0"),
283 _salu64_case("salu_quad_bitrep", "s_quadmask_b64_hi",
284 ["s_mov_b32 s4, 0x00000000", "s_mov_b32 s5, 0x80000001"],
285 "s_quadmask_b64 s[6:7], s[4:5]", 0, "quads 8,15 -> lo=0x8100 hi=0, SCC=1"),
286 _salu64_case("salu_quad_bitrep", "s_bitreplicate_b64_b32",
287 ["s_mov_b32 s4, 0x80010005"],
288 "s_bitreplicate_b64_b32 s[6:7], s4", 1, "each bit doubled, SCC kept"),
289 ]
290
291 # 8. 64-bit scalar bitwise ops on scalar data
292 for op in ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64",
293 "s_nand_b64", "s_nor_b64", "s_xnor_b64"):
294 cases.append(_salu64_case(
295 "salu_64_bitwise", f"{op}_data",
296 ["s_mov_b32 s4, 0xf0f000ff", "s_mov_b32 s5, 0x12345678",
297 "s_mov_b32 s8, 0x0ff0ff00", "s_mov_b32 s9, 0x87654321"],
298 f"{op} s[6:7], s[4:5], s[8:9]", 0, f"{op} on 64-bit scalar data + SCC",
299 ))
300 cases.append(_salu64_case(
301 "salu_64_bitwise", "s_not_b64_all_ones",
302 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
303 "s_not_b64 s[6:7], s[4:5]", 1, "~(-1) = 0, SCC=0",
304 ))
305
306 # 9. s_movrels_b32 / s_movrels_b64
307 cases += [
308 _salu32_pair("salu_movrels", "s_movrels_b32_m0_2",
309 ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222",
310 "s_mov_b32 s12, 0x33333333", "s_mov_b32 m0, 2"],
311 "s_movrels_b32 s6, s10", "SGPR[10+2] = 0x33333333, SCC kept"),
312 _salu64_case("salu_movrels", "s_movrels_b64_m0_2",
313 ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222",
314 "s_mov_b32 s12, 0x33333333", "s_mov_b32 s13, 0x44444444", "s_mov_b32 m0, 2"],
315 "s_movrels_b64 s[6:7], s[10:11]", 1, "SGPR[12:13], SCC kept"),
316 ]
317
318 # 10. Integer clamp on v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16
319 cases += [
320 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u32_clamp", [
321 "v_mov_b32 v1, 0xfffffff0", "v_mov_b32 v2, 0x30",
322 "v_add_nc_u32_e64 v8, v1, v2 clamp", # saturates to 0xffffffff
323 "v_sub_nc_u32_e64 v9, v2, v1 clamp", # saturates to 0
324 "v_subrev_nc_u32_e64 v10, v1, v2 clamp", # v2 - v1 -> saturates to 0
325 "v_subrev_nc_u32_e64 v11, v2, v1 clamp", # v1 - v2 = 0xffffffc0
326 ], "u32 nc add/sub/subrev with clamp"),
327 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_i32_clamp", [
328 "v_mov_b32 v1, 0x7ffffff0", "v_mov_b32 v2, 0x30",
329 "v_mov_b32 v3, 0x80000010", "v_mov_b32 v4, 0x30",
330 "v_add_nc_i32_e64 v8, v1, v2 clamp", # +overflow -> 0x7fffffff
331 "v_sub_nc_i32_e64 v9, v3, v4 clamp", # -overflow -> 0x80000000
332 "v_add_nc_i32_e64 v10, v3, v3 clamp", # neg+neg overflow -> 0x80000000
333 "v_sub_nc_i32_e64 v11, v1, v3 clamp", # pos-neg overflow -> 0x7fffffff
334 ], "i32 nc add/sub with clamp"),
335 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u16_clamp", [
336 "v_mov_b32 v1, 0x1234fff0", "v_mov_b32 v2, 0x56780030",
337 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
338 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
339 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
340 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
341 "v_add_nc_u16_e64 v8, v1, v2 clamp", # lo saturates 0xffff, hi kept
342 "v_sub_nc_u16_e64 v9, v2, v1 clamp", # lo saturates 0x0000, hi kept
343 "v_add_nc_u16_e64 v10, v1, v2 op_sel:[0,0,1] clamp", # write hi saturates 0xffff, lo kept
344 "v_sub_nc_u16_e64 v11, v1, v2 op_sel:[1,1,0] clamp", # 0x1234 - 0x5678 -> 0x0000, hi kept
345 ], "u16 nc add/sub with clamp and op_sel (untouched half kept)"),
346 ]
347
348 # 11. v_add/sub/subrev_co[_ci]_u32 with clamp (known divergence: translator ignores clamp)
349 cases += [
350 _valu4_case("valu_add_co_clamp", "v_add_co_u32_clamp", [
351 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
352 "v_add_co_u32 v8, {vcc}, v1, v2 clamp",
353 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
354 "v_mov_b32 v3, 5", "v_mov_b32 v4, 10",
355 "v_sub_co_u32 v10, {vcc}, v3, v4 clamp",
356 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
357 ], "v_add_co_u32 / v_sub_co_u32 clamp: hardware saturates D and reports real carry/borrow"),
358 _valu4_case("valu_add_co_clamp", "v_subrev_co_u32_clamp", [
359 "v_mov_b32 v1, 10", "v_mov_b32 v2, 5",
360 "v_subrev_co_u32 v8, {vcc}, v1, v2 clamp",
361 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
362 "v_mov_b32 v3, 0", "v_mov_b32 v4, 0",
363 "{smov} {vcc}, -1",
364 "v_subrev_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp",
365 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
366 ], "v_subrev_co_u32 / v_subrev_co_ci_u32 clamp: hardware saturates D to 0 and reports borrow=1"),
367 _valu4_case("valu_add_co_clamp", "v_add_co_ci_u32_clamp", [
368 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0",
369 "{smov} {vcc}, -1",
370 "v_add_co_ci_u32_e64 v8, {vcc}, v1, v2, {vcc} clamp",
371 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
372 "v_mov_b32 v3, 0", "v_mov_b32 v4, 0",
373 "{smov} {vcc}, -1",
374 "v_sub_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp",
375 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
376 ], "v_add_co_ci_u32 / v_sub_co_ci_u32 clamp: carry-in overflow saturates D and sets carry-out"),
377 ]
378
379 # 12. v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and EXEC masking)
380 cases += [
381 _valu4_case("valu_mad64", "v_mad_u64_u32_carry", [
382 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
383 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff",
384 "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]",
385 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
386 "v_mov_b32 v11, 0",
387 ], "u64 max*max + max64 -> carry=1"),
388 _valu4_case("valu_mad64", "v_mad_i64_i32_pos_overflow", [
389 "v_mov_b32 v1, 0x80000000", "v_mov_b32 v2, 0x80000000",
390 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0x7fffffff",
391 "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]",
392 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
393 "v_mov_b32 v11, 0",
394 ], "(-2^31)^2 + INT64_MAX > 0 (signed overflow, positive exact sum -> sdst=0)"),
395 _valu4_case("valu_mad64", "v_mad_i64_i32_neg_sum", [
396 "v_mov_b32 v1, 0xfffffffe", "v_mov_b32 v2, 3",
397 "v_mov_b32 v4, 0", "v_mov_b32 v5, 0",
398 "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]",
399 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
400 "v_mov_b32 v11, 0",
401 ], "(-2)*3 + 0 = -6 -> sdst=1 (bit 64 sign of exact 65-bit sum)"),
402 _valu4_case("valu_mad64", "v_mad_u64_u32_inactive_lane", [
403 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
404 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff",
405 "v_mov_b32 v8, 0x11111111", "v_mov_b32 v9, 0x22222222",
406 "{smov} {vcc}, -1",
407 "{smov} {stmp}, {exec}",
408 "{smov} {exec}, 0",
409 "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]",
410 "{smov} {exec}, {stmp}",
411 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
412 "v_mov_b32 v11, 0",
413 ], "inactive EXEC lane: D untouched and sdst bit cleared to 0"),
414 ]
415
416 # 13. v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8
417 cases += [
418 _valu4_case("valu_sad_lerp", "v_sad_ops", [
419 "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x0080f002", "v_mov_b32 v3, 0xffffff00",
420 "v_sad_u8 v8, v1, v2, v3", # wraps 32-bit
421 "v_sad_hi_u8 v9, v1, v2, v3", # (byte_sad << 16) + S2
422 "v_sad_u16 v10, v1, v2, v3", # 2x16-bit SAD + S2
423 "v_sad_u32 v11, v1, v2, v3", # |v1 - v2| + S2
424 ], "v_sad_u8 / v_sad_hi_u8 / v_sad_u16 / v_sad_u32 with 32-bit wrap"),
425 _valu4_case("valu_sad_lerp", "v_msad_and_lerp", [
426 "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x00800005", "v_mov_b32 v3, 100",
427 "v_msad_u8 v8, v1, v2, v3", # skips bytes 1 and 3 where S1 byte == 0
428 "v_mov_b32 v4, 0xff030200", "v_mov_b32 v5, 0xff040301", "v_mov_b32 v6, 0x01000100",
429 "v_lerp_u8 v9, v4, v5, v6", # per-byte (a+b+(c&1))>>1
430 "v_mov_b32 v7, 0x00feffff",
431 "v_lerp_u8 v10, v4, v5, v7", # upper bits of S2 bytes ignored
432 "v_mov_b32 v11, 0",
433 ], "v_msad_u8 zero-byte mask and v_lerp_u8 rounding/no-carry"),
434 ]
435
436 # 14. v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8
437 cases += [
438 _valu4_case("valu_qsad_mqsad", "v_qsad_mqsad_pk_u16", [
439 "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050",
440 "v_mov_b32 v4, 0x00150025", # S1 has two zero bytes for mqsad
441 "v_mov_b32 v6, 0xfffe0005", "v_mov_b32 v7, 0xfff00100",
442 "v_qsad_pk_u16_u8 v[8:9], v[2:3], v4, v[6:7]",
443 "v_mqsad_pk_u16_u8 v[10:11], v[2:3], v4, v[6:7]",
444 ], "v_qsad_pk_u16_u8 and v_mqsad_pk_u16_u8 with 16-bit wrap and zero S1 bytes"),
445 _valu4_case("valu_qsad_mqsad", "v_mqsad_u32_u8", [
446 "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050",
447 "v_mov_b32 v4, 0x00150025",
448 "v_mov_b32 v12, 0xfffffffe", "v_mov_b32 v13, 10",
449 "v_mov_b32 v14, 20", "v_mov_b32 v15, 0xffffffff",
450 "v_mqsad_u32_u8 v[8:11], v[2:3], v4, v[12:15]",
451 ], "v_mqsad_u32_u8 four 32-bit accumulators with wrap"),
452 ]
453
454 # 15. v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64
455 cases += [
456 _valu4_case("valu_mul24_sh64", "v_mul_hi_24", [
457 "v_mov_b32 v1, 0xabffffff", "v_mov_b32 v2, 0xcdffffff",
458 "v_mul_hi_u32_u24 v8, v1, v2", # upper 8 bits ignored
459 "v_mul_hi_i32_i24 v9, v1, v2", # (-1)*(-1) >> 32 = 0
460 "v_mov_b32 v3, 0x12800000", "v_mov_b32 v4, 0x347fffff",
461 "v_mul_hi_i32_i24 v10, v3, v4", # (-2^23)*(2^23-1) >> 32
462 "v_mul_hi_u32_u24 v11, v3, v4",
463 ], "v_mul_hi_u32_u24 and v_mul_hi_i32_i24 (upper 8 bits ignored)"),
464 _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64", [
465 "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321",
466 "v_mov_b32 v1, 36",
467 "v_lshrrev_b64 v[8:9], v1, v[2:3]",
468 "v_ashrrev_i64 v[10:11], v1, v[2:3]",
469 ], "v_lshrrev_b64 and v_ashrrev_i64 shift=36"),
470 _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64_mod64", [
471 "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321",
472 "v_mov_b32 v1, 68", # 68 & 63 = 4
473 "v_lshrrev_b64 v[8:9], v1, v[2:3]",
474 "v_ashrrev_i64 v[10:11], v1, v[2:3]",
475 ], "v_lshrrev_b64 and v_ashrrev_i64 shift masked to 6 bits"),
476 ]
477
478 # 16. v_mad_u16 / v_mad_i16 (clamp, op_sel, kept half)
479 cases += [
480 _valu4_case("valu_mad16", "v_mad_u16_i16_clamp_opsel", [
481 "v_mov_b32 v1, 0x80000300", "v_mov_b32 v2, 0x00020200", "v_mov_b32 v3, 0x00010010",
482 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
483 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
484 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
485 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
486 "v_mad_u16 v8, v1, v2, v3 clamp", # 0x300*0x200+0x10 = 0x60010 -> 0xffff
487 "v_mad_u16 v9, v1, v2, v3", # wraps to 0x0010, hi kept
488 "v_mad_i16 v10, v1, v2, v3 op_sel:[1,1,1,0] clamp", # (-32768)*2 + 1 = -65535 -> 0x8000
489 "v_mad_i16 v11, v1, v2, v3 op_sel:[0,0,0,1] clamp", # 0x300*0x200+0x10 -> 0x7fff in hi, lo kept
490 ], "v_mad_u16 / v_mad_i16 clamp, op_sel and untouched destination half"),
491 ]
492
493 # 17. v_cvt_f16_u16 / v_cvt_f16_i16 / v_cvt_u16_f16 / v_cvt_i16_f16 (kept half, NaN, inf)
494 cases += [
495 _valu4_case("valu_cvt_16", "v_cvt_u16_i16_f16_e64_nan_inf", [
496 "v_mov_b32 v1, 0x00007e00", # +qNaN
497 "v_mov_b32 v2, 0x0000fe00", # -qNaN
498 "v_mov_b32 v3, 0x00007c00", # +inf
499 "v_mov_b32 v4, 0x0000fc00", # -inf
500 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
501 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
502 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
503 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
504 "v_cvt_u16_f16_e64 v8, v1", # +qNaN -> 0, check high half
505 "v_cvt_i16_f16_e64 v9, v2", # -qNaN -> 0, check high half
506 "v_cvt_u16_f16_e64 v10, v3", # +inf -> 0xffff, check high half
507 "v_cvt_i16_f16_e64 v11, v4", # -inf -> 0x8000, check high half
508 ], "v_cvt_u16/i16_f16_e64 on +-qNaN and +-inf (high half behavior)"),
509 _valu4_case("valu_cvt_16", "v_cvt_f16_u16_i16_e64_keep", [
510 "v_mov_b32 v1, 0x0000fff0", # 65520 -> +inf (0x7c00)
511 "v_mov_b32 v2, 0x00008000", # -32768 -> -32768.0 (0xf800)
512 "v_mov_b32 v3, 0x0000002a", # 42 -> 42.0 (0x5140)
513 "v_mov_b32 v4, 0x00007fff", # 32767 -> 32768.0 (0x7800)
514 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
515 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
516 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
517 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
518 "v_cvt_f16_u16_e64 v8, v1",
519 "v_cvt_f16_i16_e64 v9, v2",
520 "v_cvt_f16_u16_e64 v10, v3",
521 "v_cvt_f16_i16_e64 v11, v4",
522 ], "v_cvt_f16_u16/i16_e64 overflow to +inf and high half behavior"),
523 ]
524
525 # 18. v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 (exact floor(x+0.5) + signed NaN; v_cvt_i32_f32 control)
526 cases += [
527 _valu4_case("valu_cvt_flr_rpi", "v_cvt_rpi_precision", [
528 "v_mov_b32 v1, 0x3effffff", # 0.49999997 (f32(x+0.5)==1.0, exact floor(x+0.5)==0)
529 "v_mov_b32 v2, 0x4b000001", # 8388609.0 (f32(x+0.5)==8388610.0, exact==8388609)
530 "v_mov_b32 v3, 0x4b7fffff", # 16777215.0 (f32(x+0.5)==16777216.0, exact==16777215)
531 "v_mov_b32 v4, 0xbf000000", # -0.5 -> floor(-0.5 + 0.5) = 0
532 "v_cvt_rpi_i32_f32 v8, v1",
533 "v_cvt_rpi_i32_f32 v9, v2",
534 "v_cvt_rpi_i32_f32 v10, v3",
535 "v_cvt_rpi_i32_f32 v11, v4",
536 ], "v_cvt_rpi_i32_f32 exact floor(x+0.5) vs binary32 x+0.5"),
537 _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_rpi_nan_inf", [
538 "v_mov_b32 v1, 0x7fc00000", # +qNaN
539 "v_mov_b32 v2, 0xffc00000", # -qNaN
540 "v_cvt_flr_i32_f32 v8, v1",
541 "v_cvt_flr_i32_f32 v9, v2",
542 "v_cvt_rpi_i32_f32 v10, v1",
543 "v_cvt_rpi_i32_f32 v11, v2",
544 ], "v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 on +qNaN and -qNaN"),
545 _valu4_case("valu_cvt_flr_rpi", "v_cvt_i32_f32_nan_control", [
546 "v_mov_b32 v1, 0x7fc00000", # +qNaN
547 "v_mov_b32 v2, 0xffc00000", # -qNaN
548 "v_mov_b32 v3, 0x7f800001", # +sNaN
549 "v_mov_b32 v4, 0xff800001", # -sNaN
550 "v_cvt_i32_f32 v8, v1",
551 "v_cvt_i32_f32 v9, v2",
552 "v_cvt_i32_f32 v10, v3",
553 "v_cvt_i32_f32 v11, v4",
554 ], "control: v_cvt_i32_f32 returns 0 for every NaN"),
555 _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_edges", [
556 "v_mov_b32 v1, 0xbf800001", # -1.0000001 -> -2
557 "v_mov_b32 v2, 0x7f800000", # +inf -> INT_MAX
558 "v_mov_b32 v3, 0xff800000", # -inf -> INT_MIN
559 "v_mov_b32 v4, 0x4f000000", # +2^31 -> INT_MAX
560 "v_cvt_flr_i32_f32 v8, v1",
561 "v_cvt_flr_i32_f32 v9, v2",
562 "v_cvt_flr_i32_f32 v10, v3",
563 "v_cvt_flr_i32_f32 v11, v4",
564 ], "v_cvt_flr_i32_f32 negative fraction, infinities and 2^31 saturation"),
565 ]
566
567 # 19. v_cvt_pknorm_i16_f32 / v_cvt_pknorm_u16_f32 (NaN, inf, out-of-range, ties)
568 cases += [
569 _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_nan_inf", [
570 "v_mov_b32 v1, 0x7fc00000", # +qNaN
571 "v_mov_b32 v2, 0xffc00000", # -qNaN
572 "v_mov_b32 v3, 0x7f800000", # +inf
573 "v_mov_b32 v4, 0xff800000", # -inf
574 "v_cvt_pknorm_i16_f32 v8, v1, v2",
575 "v_cvt_pknorm_u16_f32 v9, v1, v2",
576 "v_cvt_pknorm_i16_f32 v10, v3, v4",
577 "v_cvt_pknorm_u16_f32 v11, v3, v4",
578 ], "v_cvt_pknorm_i16/u16_f32 on +-qNaN and +-inf"),
579 _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_ties", [
580 "v_mov_b32 v1, 0x3f000000", # 0.5 -> 0.5*32767 = 16383.5 (RNE=16384), 0.5*65535 = 32767.5 (RNE=32768)
581 "v_mov_b32 v2, 0xbf000000", # -0.5 -> -16383.5 (RNE=-16384), u16 -> 0
582 "v_mov_b32 v3, 0x3f800000", # 1.0 -> 32767 / 65535
583 "v_mov_b32 v4, 0xbf800000", # -1.0 -> -32767 (0x8001) / 0
584 "v_cvt_pknorm_i16_f32 v8, v1, v2",
585 "v_cvt_pknorm_u16_f32 v9, v1, v2",
586 "v_cvt_pknorm_i16_f32 v10, v3, v4",
587 "v_cvt_pknorm_u16_f32 v11, v3, v4",
588 ], "v_cvt_pknorm_i16/u16_f32 ties at +-0.5 and +-1.0 endpoints"),
589 ]
590
591 return cases
592
593
594def _translate_case(work, case):
595 os.makedirs(os.path.join(work, "disasm"), exist_ok=True)
596 name = f"ps_int_hw_{case.name}"
597 src = os.path.join(work, "disasm", name + ".s")
598 body = case.lines(wave=32) + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"]
599 with open(src, "w", encoding="utf-8", newline="\n") as f:
600 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body))
601 with open(os.path.join(work, name + ".dxbc"), "wb") as f:
602 f.write(STUB_DXBC)
603 with warnings.catch_warnings():
604 warnings.simplefilter("ignore", ResourceWarning)
605 spv = rdna2spirv.translate(src)
606 return list(spirv_mini_interp.run_fragment(spv)["%out_mrt0"])
607
608
609def run_translator(cases):
610 out = {}
611 with tempfile.TemporaryDirectory(prefix="int_hw_probe_") as work:
612 for case in cases:
613 try:
614 out[case.name] = _translate_case(work, case)
615 except Exception as e:
616 out[case.name] = f"error: {type(e).__name__}: {e}"
617 return out
618
619
620def run_hw(cases, arch=None, waves=(32, 64)):
621 from hw_oracle import asm, runner # noqa: E402
622 oracle = runner.open_oracle(arch=arch)
623 try:
624 device = oracle.device
625 per_wave = {}
626 for wave in waves:
627 kernels = [asm.Kernel(case.lines(wave=wave), wave=wave, threads=1, words=4) for case in cases]
628 res = oracle.run(kernels, words=4)
629 per_wave[wave] = {case.name: r for case, r in zip(cases, res)}
630 return device, per_wave
631 finally:
632 oracle.close()
633
634
635def _fmt_words(w):
636 if isinstance(w, list):
637 return " ".join(f"0x{x:08x}" for x in w)
638 return str(w)
639
640
641def self_test():
642 cases = build_cases()
643 names = [c.name for c in cases]
644 assert len(names) == len(set(names)), "duplicate case names"
645 for name in KNOWN_DIVERGENCES:
646 assert name in names, f"unknown KNOWN_DIVERGENCES key: {name}"
647 res = run_translator(cases)
648 errors = {k: v for k, v in res.items() if not isinstance(v, list)}
649 assert not errors, f"translator errors: {errors}"
650 print(f"self-test: {len(cases)} cases across {len({c.group for c in cases})} groups translated and ran on CPU OK")
651 return 0
652
653
654def main(argv=None):
655 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
656 ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator")
657 ap.add_argument("--wave", choices=("32", "64", "both"), default="both")
658 ap.add_argument("--group", action="append", default=[], help="run only named group(s)")
659 ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle")
660 ap.add_argument("--list-groups", action="store_true")
661 ap.add_argument("--strict", action="store_true", help="treat known translator divergences as failures")
662 ap.add_argument("--json", dest="json_out", default=None, help="write raw results to a JSON file")
663 ap.add_argument("--self-test", action="store_true")
664 args = ap.parse_args(argv)
665
666 if args.self_test:
667 return self_test()
668
669 cases = build_cases()
670 groups = []
671 for c in cases:
672 if c.group not in groups:
673 groups.append(c.group)
674 if args.list_groups:
675 for g in groups:
676 n = sum(1 for c in cases if c.group == g)
677 print(f"{g:<22} ({n} cases)")
678 return 0
679
680 if args.group:
681 unknown = [g for g in args.group if g not in groups]
682 if unknown:
683 print(f"unknown group(s): {', '.join(unknown)}", file=sys.stderr)
684 return 2
685 want = set(args.group)
686 cases = [c for c in cases if c.group in want]
687
688 waves = (32, 64) if args.wave == "both" else (int(args.wave),)
689 tr_res = run_translator(cases) if args.oracle in ("translator", "both") else None
690 hw_device, hw_res = None, None
691 if args.oracle in ("hw", "both"):
692 from hw_oracle import runner # noqa: E402
693 try:
694 hw_device, hw_res = run_hw(cases, arch=args.hw_arch, waves=waves)
695 except runner.Unavailable as e:
696 print(f"hardware oracle unavailable: {e}", file=sys.stderr)
697 return 77
698 print(f"hardware oracle: {hw_device} (waves: {','.join(str(w) for w in waves)})")
699
700 mismatches = 0
701 known_diffs = 0
702 wave_diffs = 0
703 records = []
704 for c in cases:
705 tr = tr_res[c.name] if tr_res is not None else None
706 h32 = hw_res[32][c.name] if hw_res and 32 in hw_res else None
707 h64 = hw_res[64][c.name] if hw_res and 64 in hw_res else None
708 hw_ref = h32 if h32 is not None else h64
709 status = "OK"
710 tag = None
711 if h32 is not None and h64 is not None and h32 != h64:
712 status = "WAVE_DIFF"
713 wave_diffs += 1
714 elif (tr is not None and not isinstance(tr, list)) or (hw_ref is not None and not isinstance(hw_ref, list)):
715 status = "ERROR"
716 mismatches += 1
717 elif tr is not None and hw_ref is not None and tr != hw_ref:
718 known = KNOWN_DIVERGENCES.get(c.name)
719 if known and hw_ref == known[1]:
720 status = "KNOWN_DIFF"
721 tag = known[0]
722 known_diffs += 1
723 else:
724 status = "MISMATCH"
725 mismatches += 1
726 records.append({
727 "group": c.group, "name": c.name, "note": c.note, "status": status, "known_tag": tag,
728 "translator": tr, "hw_w32": h32, "hw_w64": h64,
729 })
730 if status != "OK" or args.oracle != "both":
731 label = f"{status}:{tag}" if tag else status
732 print(f"[{label:<22}] {c.group}/{c.name}: {c.note}")
733 if h32 is not None:
734 print(f" hw_w32: {_fmt_words(h32)}")
735 if h64 is not None and h64 != h32:
736 print(f" hw_w64: {_fmt_words(h64)}")
737 if tr is not None:
738 print(f" transl: {_fmt_words(tr)}")
739
740 total = len(cases)
741 matched = total - mismatches - known_diffs - wave_diffs
742 print(f"summary: {total} cases: {matched} match, {known_diffs} known divergence, "
743 f"{mismatches} unexpected mismatch, {wave_diffs} wave32/64 diff")
744
745 if args.json_out:
746 out_path = os.path.abspath(args.json_out)
747 if os.path.isdir(out_path):
748 print(f"ERROR: --json path is a directory: {out_path}", file=sys.stderr)
749 return 2
750 parent = os.path.dirname(out_path)
751 if parent:
752 os.makedirs(parent, exist_ok=True)
753 with open(out_path, "w", encoding="utf-8", newline="\n") as f:
754 json.dump({"device": hw_device, "waves": list(waves), "cases": records}, f, indent=2)
755 f.write("\n")
756
757 if mismatches or wave_diffs or (args.strict and known_diffs):
758 return 1
759 return 0
760
761
762if __name__ == "__main__":
763 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
764 sys.stdout.reconfigure(errors="replace")
765 except (AttributeError, ValueError, OSError):
766 pass
767 sys.exit(main())
diff --git a/tools/manifest.py b/tools/manifest.py
index 9c39d9030..d1ac69ba4 100644
--- a/tools/manifest.py
+++ b/tools/manifest.py
@@ -22,7 +22,7 @@ DEFAULT = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.jso
22 22
23 23
24class ManifestError(Exception): 24class ManifestError(Exception):
25 """A manifest that isn't valid JSON or doesn't have the layout create() writes.""" 25 """An input or manifest error that the CLI reports without a traceback."""
26 26
27 27
28def default_jobs() -> int: 28def default_jobs() -> int:
@@ -52,12 +52,32 @@ def below_normal() -> None:
52 k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS 52 k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS
53 53
54 54
55def sha256(path: str) -> str: 55def _file_stamp(st: os.stat_result) -> tuple[int, int, int]:
56 return st.st_size, st.st_mtime_ns, st.st_ctime_ns
57
58
59def _hash_file(path: str, *, expected_size: int | None = None) -> tuple[int, str]:
60 """Return the size and digest of the same open file, or fail if it changes."""
56 h = hashlib.sha256() 61 h = hashlib.sha256()
57 with open(path, "rb", buffering=0) as f: 62 with open(path, "rb", buffering=0) as f:
58 while chunk := f.read(CHUNK): 63 before = os.fstat(f.fileno())
64 size = before.st_size
65 if expected_size is not None and size != expected_size:
66 raise ManifestError(f"{path}: file size changed before hashing")
67 remaining = size
68 while remaining and (chunk := f.read(min(CHUNK, remaining))):
59 h.update(chunk) 69 h.update(chunk)
60 return h.hexdigest() 70 remaining -= len(chunk)
71 # Compare timestamps from the same handle. Windows can report different times by path.
72 # Compare the path by identity so a replacement of the open file is detected too.
73 if (remaining or _file_stamp(os.fstat(f.fileno())) != _file_stamp(before)
74 or not os.path.samestat(before, os.stat(path))):
75 raise ManifestError(f"{path}: file changed while hashing")
76 return size, h.hexdigest()
77
78
79def sha256(path: str) -> str:
80 return _hash_file(path)[1]
61 81
62 82
63def same_output_path(first: str, second: str) -> bool: 83def same_output_path(first: str, second: str) -> bool:
@@ -114,7 +134,8 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
114 if same_output_path(out, path): 134 if same_output_path(out, path):
115 raise ManifestError(f"--out would overwrite the input {path}; " 135 raise ManifestError(f"--out would overwrite the input {path}; "
116 "choose a manifest path that is not one of the hashed files") 136 "choose a manifest path that is not one of the hashed files")
117 total = sum(os.path.getsize(p) for _, p in files) 137 sizes = {path: os.path.getsize(path) for _, path in files}
138 total = sum(sizes.values())
118 entries = {} 139 entries = {}
119 done = count = 0 140 done = count = 0
120 t0 = time.time() 141 t0 = time.time()
@@ -131,7 +152,8 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
131 print(f"[{pct:6.1%}] {count}/{len(files)} files {rate:7.0f} MiB/s", flush=True) 152 print(f"[{pct:6.1%}] {count}/{len(files)} files {rate:7.0f} MiB/s", flush=True)
132 153
133 def work(rel: str, path: str) -> tuple[str, int, str]: 154 def work(rel: str, path: str) -> tuple[str, int, str]:
134 return rel, os.path.getsize(path), sha256(path) 155 size, digest = _hash_file(path, expected_size=sizes[path])
156 return rel, size, digest
135 157
136 if jobs == 1: 158 if jobs == 1:
137 for rel, p in files: 159 for rel, p in files:
diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py
index 3832a8590..7571c2ae9 100644
--- a/tools/navmesh_decode.py
+++ b/tools/navmesh_decode.py
@@ -927,7 +927,7 @@ def _make_parent(path):
927def write_csv(path, rows): 927def write_csv(path, rows):
928 _make_parent(path) 928 _make_parent(path)
929 with open(path, "w", newline="", encoding="utf-8") as f: 929 with open(path, "w", newline="", encoding="utf-8") as f:
930 w = csv.DictWriter(f, fieldnames=COLUMNS, extrasaction="ignore") 930 w = csv.DictWriter(f, fieldnames=COLUMNS, extrasaction="ignore", lineterminator="\n")
931 w.writeheader() 931 w.writeheader()
932 for r in rows: 932 for r in rows:
933 w.writerow({k: ("" if r.get(k) is None else r.get(k)) for k in COLUMNS}) 933 w.writerow({k: ("" if r.get(k) is None else r.get(k)) for k in COLUMNS})
diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py
index 4867f7c84..0fa6c7f83 100644
--- a/tools/navmesh_index.py
+++ b/tools/navmesh_index.py
@@ -204,7 +204,7 @@ def write_outputs(rows, summary, out_path, csv_path):
204 if csv_path: 204 if csv_path:
205 _make_parent(csv_path) 205 _make_parent(csv_path)
206 with open(csv_path, "w", newline="", encoding="utf-8") as f: 206 with open(csv_path, "w", newline="", encoding="utf-8") as f:
207 w = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore") 207 w = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore", lineterminator="\n")
208 w.writeheader() 208 w.writeheader()
209 w.writerows(rows) 209 w.writerows(rows)
210 written.append(csv_path) 210 written.append(csv_path)
@@ -258,8 +258,14 @@ def is_scanned_input(path, input_path, pattern):
258 return False 258 return False
259 root = parent 259 root = parent
260 pattern = pattern or "*.bin" 260 pattern = pattern or "*.bin"
261 return (fnmatch.fnmatch(os.path.relpath(target, root), pattern) 261 if (fnmatch.fnmatch(os.path.relpath(target, root), pattern)
262 or fnmatch.fnmatch(os.path.basename(target), pattern)) 262 or fnmatch.fnmatch(os.path.basename(target), pattern)):
263 return True
264 # The spelling may not match while the file is still one the scan reads: fnmatch folds case only on Windows,
265 # so CARVE/PAGE.BIN on a case-insensitive macOS or Linux volume, or a hard link, slips past the pattern. Ask
266 # the scan's own glob whether any file it reads is this one.
267 return any(same_report_path(target, scanned)
268 for scanned in glob.iglob(os.path.join(input_path, "**", pattern), recursive=True))
263 269
264 270
265def main() -> int: 271def main() -> int:
diff --git a/tools/opus_tags.py b/tools/opus_tags.py
index a1395e6ef..51986d3a0 100644
--- a/tools/opus_tags.py
+++ b/tools/opus_tags.py
@@ -4,7 +4,7 @@ awc_opus.py writes <out>/<bank>/<stream id>.ogg with an empty OpusTags header. T
4from two local work products: 4from two local work products:
5 5
6``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file 6``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file
7 name) and its bank (the folder path below the Opus folder; if that has no match, the path with its 7 name; awc_opus.py's ``<id>~2.ogg`` for a second stream with the same id gets the same name) and its bank (the folder path below the Opus folder; if that has no match, the path with its
8 leading folders removed one at a time, so the Opus folder may hold several archives' outputs). 8 leading folders removed one at a time, so the Opus folder may hold several archives' outputs).
9``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_<lang> ...). A named stream whose name is 9``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_<lang> ...). A named stream whose name is
10 a dialogue wave gets that line's label, speaker and subtitles. 10 a dialogue wave gets that line's label, speaker and subtitles.
@@ -40,7 +40,7 @@ from awc_opus import ogg_page, write_file # noqa: E402
40VENDOR = b"leonida " 40VENDOR = b"leonida "
41MARKUP = re.compile(r"~[^~]*~") 41MARKUP = re.compile(r"~[^~]*~")
42SPACES = re.compile(r"\s+") 42SPACES = re.compile(r"\s+")
43STREAM_FILE = re.compile(r"^([0-9A-Fa-f]{8})\.ogg$") 43STREAM_FILE = re.compile(r"^([0-9A-Fa-f]{8})(?:~\d+)?\.ogg$") # <id>~2 ...: a later stream with the same id
44MAX_PACKET = 255 * 255 - 1 # lacing values of one page: 254 full segments and a final short one 44MAX_PACKET = 255 * 255 - 1 # lacing values of one page: 254 full segments and a final short one
45 45
46 46
diff --git a/tools/page_index.py b/tools/page_index.py
index fac172670..41d9f3783 100644
--- a/tools/page_index.py
+++ b/tools/page_index.py
@@ -322,7 +322,7 @@ def write_json(path, pages, summary):
322 322
323def write_csv(path, pages): 323def write_csv(path, pages):
324 with open(path, "w", newline="", encoding="utf-8") as f: 324 with open(path, "w", newline="", encoding="utf-8") as f:
325 w = csv.DictWriter(f, fieldnames=COLUMNS) 325 w = csv.DictWriter(f, fieldnames=COLUMNS, lineterminator="\n")
326 w.writeheader() 326 w.writeheader()
327 for page in pages: 327 for page in pages:
328 records = page["q38_records"] 328 records = page["q38_records"]
diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py
index 148318c15..dbe8f75a8 100644
--- a/tools/pe_inspect.py
+++ b/tools/pe_inspect.py
@@ -78,7 +78,9 @@ class PeImage:
78 magic = struct.unpack_from("<H", data, opt)[0] 78 magic = struct.unpack_from("<H", data, opt)[0]
79 if magic not in (0x10B, 0x20B): 79 if magic not in (0x10B, 0x20B):
80 raise PeFormatError(f"unknown optional header magic 0x{magic:x}") 80 raise PeFormatError(f"unknown optional header magic 0x{magic:x}")
81 if opt + 72 > len(data): # the fixed fields read below end with DllCharacteristics at +70 81 # The declared optional header must contain every fixed field we read,
82 # and the complete declared header must fit inside the file.
83 if opt_size < 72 or opt + opt_size > len(data):
82 raise PeFormatError("truncated optional header") 84 raise PeFormatError("truncated optional header")
83 self.is64 = magic == 0x20B 85 self.is64 = magic == 0x20B
84 self.entry_rva = struct.unpack_from("<I", data, opt + 16)[0] 86 self.entry_rva = struct.unpack_from("<I", data, opt + 16)[0]
diff --git a/tools/rbf0_index.py b/tools/rbf0_index.py
index f257963eb..c13122afa 100644
--- a/tools/rbf0_index.py
+++ b/tools/rbf0_index.py
@@ -468,7 +468,7 @@ def write_output(path, records, summary, all_strings=False):
468 json.dump({"summary": summary, "files": docs}, f, indent=1) 468 json.dump({"summary": summary, "files": docs}, f, indent=1)
469 return 469 return
470 with open(path, "w", encoding="utf-8", newline="") as f: 470 with open(path, "w", encoding="utf-8", newline="") as f:
471 writer = csv.writer(f) 471 writer = csv.writer(f, lineterminator="\n")
472 writer.writerow(COLUMNS) 472 writer.writerow(COLUMNS)
473 for r in records: 473 for r in records:
474 sample = "; ".join(r["sample"]) 474 sample = "; ".join(r["sample"])
diff --git a/tools/rbf0_tree.py b/tools/rbf0_tree.py
index 44a6b37db..f4533009a 100644
--- a/tools/rbf0_tree.py
+++ b/tools/rbf0_tree.py
@@ -600,7 +600,7 @@ def write_csv(path, docs):
600 The rows carry names and payloads, so the file is game data and must stay local. 600 The rows carry names and payloads, so the file is game data and must stay local.
601 """ 601 """
602 with open(path, "w", encoding="utf-8", newline="") as f: 602 with open(path, "w", encoding="utf-8", newline="") as f:
603 writer = csv.writer(f) 603 writer = csv.writer(f, lineterminator="\n")
604 writer.writerow(CSV_COLUMNS) 604 writer.writerow(CSV_COLUMNS)
605 for doc in docs: 605 for doc in docs:
606 root = doc["tree"] 606 root = doc["tree"]
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 26d8ff9d1..6806a4b1b 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -64,11 +64,14 @@ MESH_COMPUTE = False
64# `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high 64# `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high
65# halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The 65# halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The
66# interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the 66# interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the
67# device's interpolator instead of by explicit arithmetic. The halves sit below location F16_HALF_TOP (30: 31 67# device's interpolator instead of by explicit arithmetic. The halves count down from location F16_HALF_TOP (param 0's
68# locations is MoltenVK's limit, 124 components), counting down from param 0, so a producer with params 0..P-1 has 68# high halves, its low halves one below), so a producer with params 0..P-1 has room for the halves of params
69# room for the halves of params 0..(29 - P) / 2; Gen.export skips the ones that would land on its own params. 69# 0..(28 - P) / 2; Gen.export skips the ones that would land on its own params. The top is 29, not 30 (SHADER-291):
70# MoltenVK's maxVertexOutputComponents is 124 because Metal counts gl_Position in its 128 vertex-output scalars, and
71# the validation layer counts it too (VUID-RuntimeSpirv-Location-06272), so (29 + 1) * 4 + 4 = 124 is the most a VS
72# can use there.
70F16_HALVES = False 73F16_HALVES = False
71F16_HALF_TOP = 30 74F16_HALF_TOP = 29
72 75
73 76
74def f16_half_location(n, half): 77def f16_half_location(n, half):
@@ -182,6 +185,7 @@ class Gen:
182 self.uses_wave_bits = False # a whole lane mask gathered from the wave (OpGroupNonUniformBitwiseOr) 185 self.uses_wave_bits = False # a whole lane mask gathered from the wave (OpGroupNonUniformBitwiseOr)
183 self.uses_quad = False # s_wqm on a lane mask (OpGroupNonUniformQuadSwap) 186 self.uses_quad = False # s_wqm on a lane mask (OpGroupNonUniformQuadSwap)
184 self.lane_masks = {} # id(instruction) -> registers holding a lane mask there (lane_masks.py) 187 self.lane_masks = {} # id(instruction) -> registers holding a lane mask there (lane_masks.py)
188 self.ever_mask = set() # SGPRs that held a lane mask anywhere in the shader (conservative)
185 self.cur_masks = {} 189 self.cur_masks = {}
186 self.mask_writes = set() # id(instruction) of the ones that write a lane mask to a VGPR 190 self.mask_writes = set() # id(instruction) of the ones that write a lane mask to a VGPR
187 self.write_all_lanes = False 191 self.write_all_lanes = False
@@ -278,6 +282,19 @@ class Gen:
278 self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(r)}") 282 self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(r)}")
279 self.emit(f"OpStore {p} {val}") 283 self.emit(f"OpStore {p} {val}")
280 284
285 def imm_val(self, a):
286 """Integer literal value if 'a' is an immediate or known SGPR constant, else None."""
287 if a.get("abs") or a.get("neg"):
288 return None
289 k = a.get("k")
290 if k == "imm":
291 return a["v"] & 0xFFFFFFFF
292 if k == "sgpr" and a.get("n", 1) == 1 and a.get("r") in self.sgpr_imm:
293 return self.sgpr_imm[a["r"]] & 0xFFFFFFFF
294 if k == "special" and a.get("t") == "null":
295 return 0
296 return None
297
281 def src_u(self, a): 298 def src_u(self, a):
282 k = a["k"] 299 k = a["k"]
283 if k in ("vgpr", "sgpr"): 300 if k in ("vgpr", "sgpr"):
@@ -414,7 +431,10 @@ class Gen:
414 selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") 431 selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]")
415 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] 432 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")]
416 hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] 433 hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")]
417 return [self.f16_in(src, sb[i]) if hb[i] else self.src_f(src) for i, src in enumerate(a[1:4])] 434 # An f32 operand reads as a zero of its sign when it is denormal: the game's MODE flushes f32 denormals
435 # (denorm_mode_32 = 0), measured on gfx1036 for 0x00000001, 0x807fffff and the integer inline constants 1 and
436 # 64 used as f32 operands (@Sanonymous01, SHADER-298). The f16 operands widen to normal f32 values.
437 return [self.f16_in(src, sb[i]) if hb[i] else self.flush_f32(self.src_f(src)) for i, src in enumerate(a[1:4])]
418 438
419 def f16_bits(self, f, rtz=False): 439 def f16_bits(self, f, rtz=False):
420 """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56). 440 """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56).
@@ -931,15 +951,20 @@ class Gen:
931 return 951 return
932 if d["k"] != "sgpr" or d.get("n") != 2: 952 if d["k"] != "sgpr" or d.get("n") != 2:
933 raise Unsupported("s_mov_b64 destination") 953 raise Unsupported("s_mov_b64 destination")
954 lit_lo = lit_hi = None
934 if s["k"] == "special" and s["t"] == "exec": 955 if s["k"] == "special" and s["t"] == "exec":
935 lo = hi = self.exec_value() 956 lo = hi = self.exec_value()
936 elif s["k"] == "sgpr" and s.get("n") == 2: 957 elif s["k"] == "sgpr" and s.get("n") == 2:
958 lit_lo = self.sgpr_imm.get(s["r"])
959 lit_hi = self.sgpr_imm.get(s["r"] + 1)
937 lo, hi = self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", s["r"] + 1) 960 lo, hi = self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", s["r"] + 1)
938 elif s["k"] == "imm": 961 elif s["k"] == "imm":
939 v = s["v"] & 0xFFFFFFFFFFFFFFFF 962 v = s["v"] & 0xFFFFFFFFFFFFFFFF
940 if s["v"] < 0: 963 if s["v"] < 0:
941 v = s["v"] & 0xFFFFFFFFFFFFFFFF 964 v = s["v"] & 0xFFFFFFFFFFFFFFFF
942 lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) 965 lit_lo = v & 0xFFFFFFFF
966 lit_hi = (v >> 32) & 0xFFFFFFFF
967 lo, hi = self.cu(lit_lo), self.cu(lit_hi)
943 elif s["k"] == "special" and s["t"] == "vcc": 968 elif s["k"] == "special" and s["t"] == "vcc":
944 lo = hi = self.tmp() # this lane's bit in both halves, as for EXEC 969 lo = hi = self.tmp() # this lane's bit in both halves, as for EXEC
945 self.emit(f"{lo} = OpLoad %uint %vcc") 970 self.emit(f"{lo} = OpLoad %uint %vcc")
@@ -947,6 +972,11 @@ class Gen:
947 raise Unsupported("s_mov_b64 source") 972 raise Unsupported("s_mov_b64 source")
948 self.store_reg("sgpr", d["r"], lo) 973 self.store_reg("sgpr", d["r"], lo)
949 self.store_reg("sgpr", d["r"] + 1, hi) 974 self.store_reg("sgpr", d["r"] + 1, hi)
975 if self.desc_cache_ok():
976 if lit_lo is not None:
977 self.sgpr_imm[d["r"]] = lit_lo
978 if lit_hi is not None:
979 self.sgpr_imm[d["r"] + 1] = lit_hi
950 980
951 def compare(self, op, a, scalar, exec_only=False, mods=()): 981 def compare(self, op, a, scalar, exec_only=False, mods=()):
952 """v_cmp_* / s_cmp_*: lane result into VCC/SGPR mask (vector), SCC (scalar), or EXEC (v_cmpx).""" 982 """v_cmp_* / s_cmp_*: lane result into VCC/SGPR mask (vector), SCC (scalar), or EXEC (v_cmpx)."""
@@ -1235,13 +1265,12 @@ class Gen:
1235 # GFX10 buffer formats (from Mesa src/amd/registers/gfx10-rsrc.json, GFX10_FORMAT): 1265 # GFX10 buffer formats (from Mesa src/amd/registers/gfx10-rsrc.json, GFX10_FORMAT):
1236 # code: (bytes, kind, component bit widths from bit 0) 1266 # code: (bytes, kind, component bit widths from bit 0)
1237 # The names list the widths from the top bit down, so 2_10_10_10 (50) is R10G10B10A2. 1267 # The names list the widths from the top bit down, so 2_10_10_10 (50) is R10G10B10A2.
1238 # A 32-bit SINT component holds the same bits as UINT (no conversion, nothing to clamp at full width), so the 1268 # Full-width SINT and UINT preserve the same raw dwords. Keep separate kinds for signed D16 conversion.
1239 # *_SINT codes 21/63/73/76 share the raw-dword "u32" path with their UINT twins 20/62/72/75.
1240 FORMATS = {22: (4, "f32", (32,)), 64: (8, "f32", (32, 32)), 74: (12, "f32", (32, 32, 32)), 1269 FORMATS = {22: (4, "f32", (32,)), 64: (8, "f32", (32, 32)), 74: (12, "f32", (32, 32, 32)),
1241 77: (16, "f32", (32, 32, 32, 32)), 20: (4, "u32", (32,)), 62: (8, "u32", (32, 32)), 1270 77: (16, "f32", (32, 32, 32, 32)), 20: (4, "u32", (32,)), 62: (8, "u32", (32, 32)),
1242 72: (12, "u32", (32, 32, 32)), 75: (16, "u32", (32, 32, 32, 32)), 1271 72: (12, "u32", (32, 32, 32)), 75: (16, "u32", (32, 32, 32, 32)),
1243 21: (4, "u32", (32,)), 63: (8, "u32", (32, 32)), 73: (12, "u32", (32, 32, 32)), 1272 21: (4, "i32", (32,)), 63: (8, "i32", (32, 32)), 73: (12, "i32", (32, 32, 32)),
1244 76: (16, "u32", (32, 32, 32, 32)), 13: (2, "f16", (16,)), 29: (4, "f16", (16, 16)), 1273 76: (16, "i32", (32, 32, 32, 32)), 13: (2, "f16", (16,)), 29: (4, "f16", (16, 16)),
1245 71: (8, "f16", (16, 16, 16, 16)), 1: (1, "unorm", (8,)), 14: (2, "unorm", (8, 8)), 1274 71: (8, "f16", (16, 16, 16, 16)), 1: (1, "unorm", (8,)), 14: (2, "unorm", (8, 8)),
1246 56: (4, "unorm", (8, 8, 8, 8)), 57: (4, "snorm", (8, 8, 8, 8)), 60: (4, "uint", (8, 8, 8, 8)), 1275 56: (4, "unorm", (8, 8, 8, 8)), 57: (4, "snorm", (8, 8, 8, 8)), 60: (4, "uint", (8, 8, 8, 8)),
1247 7: (2, "unorm", (16,)), 23: (4, "unorm", (16, 16)), 24: (4, "snorm", (16, 16)), 1276 7: (2, "unorm", (16,)), 23: (4, "unorm", (16, 16)), 24: (4, "snorm", (16, 16)),
@@ -1252,14 +1281,14 @@ class Gen:
1252 1281
1253 def encode_format(self, fcomps, icomps, code): 1282 def encode_format(self, fcomps, icomps, code):
1254 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one 1283 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one
1255 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integers (u32/uint).""" 1284 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns (u32/i32/uint)."""
1256 try: 1285 try:
1257 size, kind, widths = self.FORMATS[code] 1286 size, kind, widths = self.FORMATS[code]
1258 except KeyError: 1287 except KeyError:
1259 raise Unsupported(f"format {code} (not in FORMATS)") 1288 raise Unsupported(f"format {code} (not in FORMATS)")
1260 if kind == "f32": 1289 if kind == "f32":
1261 return list(fcomps[:len(widths)]) 1290 return list(fcomps[:len(widths)])
1262 if kind == "u32": 1291 if kind in ("u32", "i32"):
1263 return list(icomps[:len(widths)]) 1292 return list(icomps[:len(widths)])
1264 words = [self.cu(0)] * max(1, (size + 3) // 4) 1293 words = [self.cu(0)] * max(1, (size + 3) // 4)
1265 bit = 0 1294 bit = 0
@@ -1348,7 +1377,7 @@ class Gen:
1348 return result 1377 return result
1349 1378
1350 def decode_format(self, words, code, *, fixed: bool = False): 1379 def decode_format(self, words, code, *, fixed: bool = False):
1351 """Decode one element of format `code` from raw dwords -> 4 uint ids holding f32 bits (or uint for *_UINT/uint). 1380 """Decode one element of format `code` from raw dwords -> 4 uint ids holding f32 or integer bits.
1352 1381
1353 Missing channels repeat the format's own (component c = c mod n): measured on RX 6700 for SHADER-86. 1382 Missing channels repeat the format's own (component c = c mod n): measured on RX 6700 for SHADER-86.
1354 UNORM/SNORM give the correctly rounded quotient, as the RX 6700 does, built with integer ops (norm_bits): 1383 UNORM/SNORM give the correctly rounded quotient, as the RX 6700 does, built with integer ops (norm_bits):
@@ -1357,7 +1386,7 @@ class Gen:
1357 size, kind, widths = self.FORMATS[code] 1386 size, kind, widths = self.FORMATS[code]
1358 except KeyError: 1387 except KeyError:
1359 raise Unsupported(f"format {code} (not in FORMATS)") 1388 raise Unsupported(f"format {code} (not in FORMATS)")
1360 if kind in ("f32", "u32"): 1389 if kind in ("f32", "u32", "i32"):
1361 n = len(widths) 1390 n = len(widths)
1362 vals = list(words[:n]) 1391 vals = list(words[:n])
1363 while len(vals) < 4: 1392 while len(vals) < 4:
@@ -1429,8 +1458,9 @@ class Gen:
1429 old_d = self.load_reg("vgpr", vdst["r"]) if vdst is not None else self.cu(0) 1458 old_d = self.load_reg("vgpr", vdst["r"]) if vdst is not None else self.cu(0)
1430 lbl_do, lbl_end, res, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp(), self.tmp() 1459 lbl_do, lbl_end, res, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp(), self.tmp()
1431 pre = self.current_label_placeholder() 1460 pre = self.current_label_placeholder()
1461 act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch
1432 self.emit(f"OpSelectionMerge {lbl_end} None") 1462 self.emit(f"OpSelectionMerge {lbl_end} None")
1433 self.emit(f"OpBranchConditional {self.active_b()} {lbl_do} {lbl_end}") 1463 self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}")
1434 self.emit(f"{lbl_do} = OpLabel") 1464 self.emit(f"{lbl_do} = OpLabel")
1435 ptr, p = self.tmp(), self.tmp() 1465 ptr, p = self.tmp(), self.tmp()
1436 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") 1466 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
@@ -1462,8 +1492,9 @@ class Gen:
1462 spv = self.BUF_ATOMICS[kind][0] 1492 spv = self.BUF_ATOMICS[kind][0]
1463 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" 1493 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end"
1464 pre = self.current_label_placeholder() 1494 pre = self.current_label_placeholder()
1495 act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch
1465 self.emit(f"OpSelectionMerge {lbl_end} None") 1496 self.emit(f"OpSelectionMerge {lbl_end} None")
1466 self.emit(f"OpBranchConditional {self.active_b()} {lbl_do} {lbl_end}") 1497 self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}")
1467 self.emit(f"{lbl_do} = OpLabel") 1498 self.emit(f"{lbl_do} = OpLabel")
1468 ptr = self.tmp() 1499 ptr = self.tmp()
1469 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") 1500 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
@@ -1736,13 +1767,17 @@ class Gen:
1736 else: 1767 else:
1737 comps = self.format_decode_call(fmt, words) 1768 comps = self.format_decode_call(fmt, words)
1738 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W. 1769 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W.
1739 is_int_fmt = "%false" 1770 is_int_fmt, is_signed = "%false", "%false"
1740 for code_v, (_, kind, _) in self.FORMATS.items(): 1771 for code_v, (_, kind, _) in self.FORMATS.items():
1741 if kind in ("u32", "uint"): 1772 if kind in ("u32", "i32", "uint"):
1742 e, o = self.tmp(), self.tmp() 1773 e, o = self.tmp(), self.tmp()
1743 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") 1774 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
1744 self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}") 1775 self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}")
1745 is_int_fmt = o 1776 is_int_fmt = o
1777 if d16 and kind == "i32":
1778 signed = self.tmp()
1779 self.emit(f"{signed} = OpLogicalOr %bool {is_signed} {e}")
1780 is_signed = signed
1746 dst1 = self.tmp() 1781 dst1 = self.tmp()
1747 self.emit(f"{dst1} = OpSelect %uint {is_int_fmt} {self.cu(1)} {self.cu(0x3F800000)}") 1782 self.emit(f"{dst1} = OpSelect %uint {is_int_fmt} {self.cu(1)} {self.cu(0x3F800000)}")
1748 outs = [] 1783 outs = []
@@ -1762,33 +1797,32 @@ class Gen:
1762 else: 1797 else:
1763 self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, rb) 1798 self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, rb)
1764 if d16: 1799 if d16:
1765 # d16: two 16-bit results per register (x | y << 16, z | w << 16): f16 for float/normalized formats, 1800 # D16 packs two results per register, saturating integer formats according to signedness.
1766 # saturating unsigned conversion for integer formats (FORMATS kinds u32/uint). 1801 def int_half(word):
1767 is_int = "%false" 1802 unsigned = self.saturate_int16(word, signed=False)
1768 for code_v, (_, kind, _) in self.FORMATS.items(): 1803 signed = self.saturate_int16(word, signed=True)
1769 if kind in ("u32", "uint"): 1804 half = self.tmp()
1770 e, o = self.tmp(), self.tmp() 1805 self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}")
1771 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") 1806 return half
1772 self.emit(f"{o} = OpLogicalOr %bool {is_int} {e}") 1807
1773 is_int = o
1774 for i in range(0, len(outs), 2): 1808 for i in range(0, len(outs), 2):
1775 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1} 1809 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1}
1776 lo = outs[i] 1810 lo = outs[i]
1777 il = self.saturate_int16(lo, signed=False) 1811 il = int_half(lo)
1778 r = self.tmp() 1812 r = self.tmp()
1779 if i + 1 == len(outs): 1813 if i + 1 == len(outs):
1780 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits. 1814 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits.
1781 fl = self.f16_bits(self.tof(lo)) 1815 fl = self.f16_bits(self.tof(lo))
1782 self.emit(f"{r} = OpSelect %uint {is_int} {il} {fl}") 1816 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}")
1783 self.write_lo16(dest, r) 1817 self.write_lo16(dest, r)
1784 continue 1818 continue
1785 hi = outs[i + 1] 1819 hi = outs[i + 1]
1786 ph = self.pack_f16_pair_int(self.tof(lo), self.tof(hi)) 1820 ph = self.pack_f16_pair_int(self.tof(lo), self.tof(hi))
1787 ih, pi = self.tmp(), self.tmp() 1821 ih, pi = self.tmp(), self.tmp()
1788 high_half = self.saturate_int16(hi, signed=False) 1822 high_half = int_half(hi)
1789 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}") 1823 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}")
1790 self.emit(f"{pi} = OpBitwiseOr %uint {il} {ih}") 1824 self.emit(f"{pi} = OpBitwiseOr %uint {il} {ih}")
1791 self.emit(f"{r} = OpSelect %uint {is_int} {pi} {ph}") 1825 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {pi} {ph}")
1792 self.dst(dest, r) 1826 self.dst(dest, r)
1793 1827
1794 def global_address(self, op, vaddr, saddr, mods): 1828 def global_address(self, op, vaddr, saddr, mods):
@@ -2344,6 +2378,13 @@ class Gen:
2344 self.emit(f"{red} = OpSelect %uint {bgra} {unorm_rgba[2]} {unorm_rgba[0]}") 2378 self.emit(f"{red} = OpSelect %uint {bgra} {unorm_rgba[2]} {unorm_rgba[0]}")
2345 self.emit(f"{blue} = OpSelect %uint {bgra} {unorm_rgba[0]} {unorm_rgba[2]}") 2379 self.emit(f"{blue} = OpSelect %uint {bgra} {unorm_rgba[0]} {unorm_rgba[2]}")
2346 unorm_view = [red, unorm_rgba[1], blue, unorm_rgba[3]] 2380 unorm_view = [red, unorm_rgba[1], blue, unorm_rgba[3]]
2381 signed_ic = ic
2382 if d16:
2383 signed_ic = []
2384 for component in ic[:n]:
2385 extended = self.tmp()
2386 self.emit(f"{extended} = OpBitFieldSExtract %int {self.as_int(component)} {self.cu(0)} {self.cu(16)}")
2387 signed_ic.append(self.tou(extended))
2347 for code, (size, kind, widths) in self.FORMATS.items(): 2388 for code, (size, kind, widths) in self.FORMATS.items():
2348 e = self.tmp() 2389 e = self.tmp()
2349 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}") 2390 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}")
@@ -2356,7 +2397,8 @@ class Gen:
2356 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2397 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2357 if code in (50, 56): 2398 if code in (50, 56):
2358 fcs = unorm_view 2399 fcs = unorm_view
2359 ics = ic[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2400 integer_source = signed_ic if kind == "i32" else ic
2401 ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2360 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code) 2402 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code)
2361 if size >= 4: 2403 if size >= 4:
2362 for k, w in enumerate(words[:size // 4]): 2404 for k, w in enumerate(words[:size // 4]):
@@ -2609,6 +2651,26 @@ class Gen:
2609 olds.append(old) 2651 olds.append(old)
2610 for k, old in enumerate(olds): # every exchange before the first write (vdst may alias) 2652 for k, old in enumerate(olds): # every exchange before the first write (vdst may alias)
2611 self.dst({"k": "vgpr", "r": d["r"] + k, "n": 1}, old) 2653 self.dst({"k": "vgpr", "r": d["r"] + k, "n": 1}, old)
2654 elif name in ("ds_and_b64", "ds_or_b64", "ds_xor_b64"):
2655 # M = M op D on a 64-bit LDS element (the dwords at ADDR and ADDR + 4, low first); the _rtn_ form returns
2656 # the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so one 32-bit atomic per dword
2657 # leaves exactly the memory a 64-bit atomic would, with no Int64 atomics on Workgroup memory (optional in
2658 # Vulkan). The returned pair is two reads, so a 64-bit op from another lane on the same element between
2659 # them could be seen half done; the memory result is exact either way.
2660 d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1])
2661 if dat["k"] != "vgpr" or dat.get("n") != 2 or (d is not None and (d["k"] != "vgpr" or d.get("n") != 2)):
2662 raise Unsupported(op + " operands")
2663 k = {"ds_and_b64": "OpAtomicAnd", "ds_or_b64": "OpAtomicOr", "ds_xor_b64": "OpAtomicXor"}[name]
2664 addr = self.src_u(ad)
2665 vals = [self.load_reg("vgpr", dat["r"] + w) for w in range(2)]
2666 olds = []
2667 for w in range(2):
2668 old = self.tmp()
2669 self.emit(f"{old} = {k} %uint {self.lds_ptr(addr, off + 4 * w)} {sc} {sem} {vals[w]}")
2670 olds.append(old)
2671 if d is not None:
2672 for w in range(2):
2673 self.dst({"k": "vgpr", "r": d["r"] + w, "n": 1}, olds[w])
2612 elif op in ("ds_cmpst_rtn_b32", "ds_cmpst_b32"): 2674 elif op in ("ds_cmpst_rtn_b32", "ds_cmpst_b32"):
2613 # tmp = M[A]; M[A] = (tmp == DATA) ? DATA2 : tmp; the _rtn_ form returns tmp, ds_cmpst_b32 drops it. 2675 # tmp = M[A]; M[A] = (tmp == DATA) ? DATA2 : tmp; the _rtn_ form returns tmp, ds_cmpst_b32 drops it.
2614 d, ad, cmp_, src = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2]) 2676 d, ad, cmp_, src = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2])
@@ -2762,13 +2824,17 @@ class Gen:
2762 """On hardware a wave's lanes run each instruction together: every lane's access of one instruction comes 2824 """On hardware a wave's lanes run each instruction together: every lane's access of one instruction comes
2763 before every lane's access of the next. Two halves of an emulated wave can be in different subgroups, so an 2825 before every lane's access of the next. Two halves of an emulated wave can be in different subgroups, so an
2764 access that conflicts with an earlier one of the same segment (read after write, write after read, write 2826 access that conflicts with an earlier one of the same segment (read after write, write after read, write
2765 after write, on the same memory) waits for the next round, whose barrier orders the memory. Not ordered: 2827 after write, on the same memory) waits for the next round, whose barrier orders the memory. A scalar load
2766 scalar loads (s_load / s_buffer_load) of memory the wave wrote, and sampling an image it wrote.""" 2828 (s_load / s_buffer_load) is a read of the same memory as the vector ops: on hardware every lane's earlier
2829 store is done before the wave issues it, but here the other half could load before this half has stored
2830 (#1587: valu_fuzz --family mem --emulate, lanes 32-63 read the fill pattern). Not ordered: sampling an
2831 image the wave wrote."""
2767 if op in ("ds_swizzle_b32", "ds_bpermute_b32", "ds_permute_b32"): 2832 if op in ("ds_swizzle_b32", "ds_bpermute_b32", "ds_permute_b32"):
2768 return 2833 return
2769 if op.startswith("ds_"): 2834 if op.startswith("ds_"):
2770 kind = "lds" 2835 kind = "lds"
2771 elif op.startswith(("buffer_", "tbuffer_", "global_", "flat_", "image_load", "image_store", "image_atomic")): 2836 elif op.startswith(("buffer_", "tbuffer_", "global_", "flat_", "image_load", "image_store", "image_atomic",
2837 "s_load_", "s_buffer_load_")):
2772 kind = "mem" 2838 kind = "mem"
2773 else: 2839 else:
2774 return 2840 return
@@ -2992,6 +3058,9 @@ class Gen:
2992 """Run the lane-mask analysis and give every VGPR lane a mask is fetched back from a slot of its own, 3058 """Run the lane-mask analysis and give every VGPR lane a mask is fetched back from a slot of its own,
2993 after the real registers in the %sgpr array (the array grows by as many).""" 3059 after the real registers in the %sgpr array (the array grows by as many)."""
2994 self.lane_masks, self.mask_writes = lane_masks.analyse(*blocks) 3060 self.lane_masks, self.mask_writes = lane_masks.analyse(*blocks)
3061 # lane_masks merges a mask on one path with plain data on another by dropping the register,
3062 # so "not in cur_masks" does not prove it is data on every path. Keep a conservative set.
3063 self.ever_mask = {r for m in self.lane_masks.values() for r in m if isinstance(r, int)}
2995 slots = lane_masks.parked(blocks[0], self.lane_masks) 3064 slots = lane_masks.parked(blocks[0], self.lane_masks)
2996 self.parked = {slot: self.SGPRS + i for i, slot in enumerate(slots)} 3065 self.parked = {slot: self.SGPRS + i for i, slot in enumerate(slots)}
2997 3066
@@ -3041,6 +3110,18 @@ class Gen:
3041 (t == "vcc_hi" and self.wave64 and "vcc" in self.cur_masks) 3110 (t == "vcc_hi" and self.wave64 and "vcc" in self.cur_masks)
3042 return a["k"] == "sgpr" and all(a["r"] + i in self.cur_masks for i in range(a.get("n", 1))) 3111 return a["k"] == "sgpr" and all(a["r"] + i in self.cur_masks for i in range(a.get("n", 1)))
3043 3112
3113 def any_mask_word(self, a):
3114 """Whether any dword of an SGPR pair is a lane mask (EITHER constants are data here).
3115
3116 holds_lane_mask() needs every dword, but a pair with one mask word and one
3117 zero/-1 word is a zero-extended mask: selecting it as data would read this lane's bit.
3118 """
3119 return a["k"] == "sgpr" and any(a["r"] + i in self.cur_masks for i in range(a.get("n", 1)))
3120
3121 def any_ever_mask_word(self, a):
3122 """Whether any dword of an SGPR pair held a lane mask on any path, even earlier in the shader."""
3123 return a["k"] == "sgpr" and any(a["r"] + i in self.ever_mask for i in range(a.get("n", 1)))
3124
3044 def wave_mask(self, a): 3125 def wave_mask(self, a):
3045 """The whole wave's lane mask in operand `a` as real bits: (lanes 0-31, lanes 32-63). A register holds 3126 """The whole wave's lane mask in operand `a` as real bits: (lanes 0-31, lanes 32-63). A register holds
3046 only this lane's bit (all ones or zero), so each lane puts its bit at its own position and the subgroup 3127 only this lane's bit (all ones or zero), so each lane puts its bit at its own position and the subgroup
@@ -3379,20 +3460,20 @@ class Gen:
3379 return v 3460 return v
3380 3461
3381 def turn_angle(self, x): 3462 def turn_angle(self, x):
3382 """Reduce a turn count to [-0.5, 0.5) before scaling by 2*pi. 3463 """Reduce a turn count to [-0.5, 0.5] before scaling by 2*pi (SHADER-88).
3383 3464
3384 RDNA's v_sin/v_cos take turns and range-reduce in turns. Scaling first loses the fractional part for large 3465 RDNA's v_sin/v_cos take turns and range-reduce in turns. Scaling first loses the fractional part for large
3385 inputs (one f32 ulp at 255 turns is ~1.2e-4 rad) and leaves Sin outside the [-pi, pi] range where Vulkan 3466 inputs (one f32 ulp at 255 turns is ~1.2e-4 rad) and leaves Sin outside the [-pi, pi] range where Vulkan
3386 guarantees its precision. Fract first; keep -0 as -0 so Sin's sign survives. NaN and infinity stay NaN 3467 guarantees its precision. x - RoundEven(x) is exact in binary32 for every finite x, unlike Fract(x) (rounds
3387 through Fract/compare/select. 3468 1 - |x| for a negative x: -2**-26 became +0, and -0.1 was ~1.7e-7 off). RoundEven rather than Round so +-0.5
3469 reduce symmetrically. A zero keeps its sign (x - RoundEven(x) would turn -0 into +0). NaN and infinity stay
3470 NaN through the subtraction.
3388 """ 3471 """
3389 frac, gt, adj, sel, zero, t, arg = (self.tmp() for _ in range(7)) 3472 rnd, d, zero, t, arg = (self.tmp() for _ in range(5))
3390 self.emit(f"{frac} = OpExtInst %float %glsl Fract {x}") 3473 self.emit(f"{rnd} = OpExtInst %float %glsl RoundEven {x}")
3391 self.emit(f"{gt} = OpFOrdGreaterThan %bool {frac} {self.fconst(0.5)}") 3474 self.emit(f"{d} = OpFSub %float {x} {rnd}")
3392 self.emit(f"{adj} = OpFSub %float {frac} {self.fconst(1.0)}")
3393 self.emit(f"{sel} = OpSelect %float {gt} {adj} {frac}")
3394 self.emit(f"{zero} = OpFOrdEqual %bool {x} {self.fconst(0.0)}") 3475 self.emit(f"{zero} = OpFOrdEqual %bool {x} {self.fconst(0.0)}")
3395 self.emit(f"{t} = OpSelect %float {zero} {x} {sel}") 3476 self.emit(f"{t} = OpSelect %float {zero} {x} {d}")
3396 self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}") 3477 self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}")
3397 return arg 3478 return arg
3398 3479
@@ -3800,9 +3881,15 @@ class Gen:
3800 self.exec_half_write(0 if a[0]["t"] == "exec_lo" else 1, None if const is not None else self.src_u(src), 3881 self.exec_half_write(0 if a[0]["t"] == "exec_lo" else 1, None if const is not None else self.src_u(src),
3801 const) 3882 const)
3802 elif op == "v_mov_b32" or op == "s_mov_b32": 3883 elif op == "v_mov_b32" or op == "s_mov_b32":
3884 lit_val = None
3885 if op == "s_mov_b32" and a[0]["k"] == "sgpr" and self.desc_cache_ok():
3886 if a[1]["k"] == "imm":
3887 lit_val = a[1]["v"] & 0xFFFFFFFF # a literal S# word, see gather_addr_modes
3888 elif a[1]["k"] == "sgpr":
3889 lit_val = self.sgpr_imm.get(a[1]["r"])
3803 self.dst(a[0], self.src_u(a[1])) 3890 self.dst(a[0], self.src_u(a[1]))
3804 if op == "s_mov_b32" and a[0]["k"] == "sgpr" and a[1]["k"] == "imm" and self.desc_cache_ok(): 3891 if lit_val is not None:
3805 self.sgpr_imm[a[0]["r"]] = a[1]["v"] & 0xFFFFFFFF # a literal S# word, see gather_addr_modes 3892 self.sgpr_imm[a[0]["r"]] = lit_val
3806 elif op == "s_mov_b64": 3893 elif op == "s_mov_b64":
3807 self.mov64(a[0], a[1]) 3894 self.mov64(a[0], a[1])
3808 elif op in ("v_max3_f32", "v_min3_f32"): 3895 elif op in ("v_max3_f32", "v_min3_f32"):
@@ -4105,6 +4192,10 @@ class Gen:
4105 self.dst(a[0], r) 4192 self.dst(a[0], r)
4106 elif op == "v_pack_b32_f16": 4193 elif op == "v_pack_b32_f16":
4107 # dst = f16(src0) | f16(src1) << 16, each taken from the low half (op_sel picks high halves). 4194 # dst = f16(src0) | f16(src1) << 16, each taken from the low half (op_sel picks high halves).
4195 # neg/abs act on the selected 16-bit half of each source as plain bit moves, abs (clear bit 15) first and
4196 # neg (xor bit 15) second: on a Radeon 680M (gfx1036) ``-v0`` turned 0x7c01 into 0xfc01 under IEEE 0 and
4197 # 0xfe01 under IEEE 1, in either half and with op_sel (#1548 SHADER-260). abs rests on the ISA's sign
4198 # clear, it was not measured on this instruction. Only the IEEE 1 sNaN quieting is open (SHADER-190).
4108 sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") 4199 sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]")
4109 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] 4200 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")]
4110 halves = [] 4201 halves = []
@@ -4116,6 +4207,12 @@ class Gen:
4116 u = s 4207 u = s
4117 m = self.tmp() 4208 m = self.tmp()
4118 self.emit(f"{m} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") 4209 self.emit(f"{m} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
4210 if src.get("abs"):
4211 # The ISA defines ABS on a float operand as |S|, a clear of the sign bit, and it is applied before
4212 # neg; no hardware run of this instruction with `abs` exists yet.
4213 a_ = self.tmp()
4214 self.emit(f"{a_} = OpBitwiseAnd %uint {m} {self.cu(0x7FFF)}")
4215 m = a_
4119 if src.get("neg"): 4216 if src.get("neg"):
4120 # SHADER-260, measured on gfx1036: a `neg` on this instruction flips the sign bit of the half it 4217 # SHADER-260, measured on gfx1036: a `neg` on this instruction flips the sign bit of the half it
4121 # packs, before any quieting (0x7c01 -> 0xfc01 in IEEE mode 0, -> 0xfe01 in mode 1), in either 4218 # packs, before any quieting (0x7c01 -> 0xfc01 in IEEE mode 0, -> 0xfe01 in mode 1), in either
@@ -4124,10 +4221,6 @@ class Gen:
4124 self.emit(f"{n} = OpBitwiseXor %uint {m} {self.cu(0x8000)}") 4221 self.emit(f"{n} = OpBitwiseXor %uint {m} {self.cu(0x8000)}")
4125 m = n 4222 m = n
4126 halves.append(m) 4223 halves.append(m)
4127 if any(src.get("abs") for src in a[1:3]):
4128 # `neg` is measured; `abs` on this instruction is not (SHADER-260), so it stays a refusal rather than
4129 # a guessed sign clear.
4130 raise Unsupported("v_pack_b32_f16 abs modifier")
4131 hi, r = self.tmp(), self.tmp() 4224 hi, r = self.tmp(), self.tmp()
4132 self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") 4225 self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}")
4133 self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") 4226 self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}")
@@ -4744,18 +4837,33 @@ class Gen:
4744 elif op == "v_alignbyte_b32": 4837 elif op == "v_alignbyte_b32":
4745 # (({src0, src1} as 64 bits) >> (8 * (src2 & 3))) low 32 bits 4838 # (({src0, src1} as 64 bits) >> (8 * (src2 & 3))) low 32 bits
4746 # (32 - b) & 31 keeps the left shift below 32 when b == 0; that result is discarded by the OpSelect. 4839 # (32 - b) & 31 keeps the left shift below 32 when b == 0; that result is discarded by the OpSelect.
4747 hi_, lo_, sh = (self.src_u(t) for t in a[1:4]) 4840 sh_val = self.imm_val(a[3])
4748 m, b, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(9)) 4841 if sh_val is not None:
4749 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(3)}") 4842 sel = sh_val & 3
4750 self.emit(f"{b} = OpShiftLeftLogical %uint {m} {self.cu(3)}") 4843 if sel == 0:
4751 self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {b}") 4844 self.dst(a[0], self.src_u(a[2]))
4752 self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}") 4845 else:
4753 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {b}") 4846 hi_, lo_ = self.src_u(a[1]), self.src_u(a[2])
4754 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}") 4847 b = sel * 8
4755 self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}") 4848 inv = 32 - b
4756 self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}") 4849 a1, b1, r = self.tmp(), self.tmp(), self.tmp()
4757 self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}") 4850 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {self.cu(b)}")
4758 self.dst(a[0], r) 4851 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {self.cu(inv)}")
4852 self.emit(f"{r} = OpBitwiseOr %uint {a1} {b1}")
4853 self.dst(a[0], r)
4854 else:
4855 hi_, lo_, sh = (self.src_u(t) for t in a[1:4])
4856 m, b, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(9))
4857 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(3)}")
4858 self.emit(f"{b} = OpShiftLeftLogical %uint {m} {self.cu(3)}")
4859 self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {b}")
4860 self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}")
4861 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {b}")
4862 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}")
4863 self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}")
4864 self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}")
4865 self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}")
4866 self.dst(a[0], r)
4759 elif op == "v_swap_b32": 4867 elif op == "v_swap_b32":
4760 # exchange two VGPRs (active lanes only, through dst) 4868 # exchange two VGPRs (active lanes only, through dst)
4761 x, y = self.src_u(a[0]), self.src_u(a[1]) 4869 x, y = self.src_u(a[0]), self.src_u(a[1])
@@ -4830,17 +4938,31 @@ class Gen:
4830 elif op == "v_alignbit_b32": 4938 elif op == "v_alignbit_b32":
4831 # (({src0, src1} as 64 bits) >> (src2 & 31)) low 32 bits 4939 # (({src0, src1} as 64 bits) >> (src2 & 31)) low 32 bits
4832 # (32 - m) & 31 keeps the left shift below 32 when m == 0; that result is discarded by the OpSelect. 4940 # (32 - m) & 31 keeps the left shift below 32 when m == 0; that result is discarded by the OpSelect.
4833 hi_, lo_, sh = (self.src_u(t) for t in a[1:4]) 4941 sh_val = self.imm_val(a[3])
4834 m, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(8)) 4942 if sh_val is not None:
4835 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") 4943 m_val = sh_val & 31
4836 self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {m}") 4944 if m_val == 0:
4837 self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}") 4945 self.dst(a[0], self.src_u(a[2]))
4838 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {m}") 4946 else:
4839 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}") 4947 hi_, lo_ = self.src_u(a[1]), self.src_u(a[2])
4840 self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}") 4948 inv_val = 32 - m_val
4841 self.emit(f"{nz} = OpINotEqual %bool {m} {self.cu(0)}") 4949 a1, b1, r = self.tmp(), self.tmp(), self.tmp()
4842 self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}") 4950 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {self.cu(m_val)}")
4843 self.dst(a[0], r) 4951 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {self.cu(inv_val)}")
4952 self.emit(f"{r} = OpBitwiseOr %uint {a1} {b1}")
4953 self.dst(a[0], r)
4954 else:
4955 hi_, lo_, sh = (self.src_u(t) for t in a[1:4])
4956 m, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(8))
4957 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}")
4958 self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {m}")
4959 self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}")
4960 self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {m}")
4961 self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}")
4962 self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}")
4963 self.emit(f"{nz} = OpINotEqual %bool {m} {self.cu(0)}")
4964 self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}")
4965 self.dst(a[0], r)
4844 elif op in ("v_lshlrev_b64", "v_lshrrev_b64", "v_ashrrev_i64"): 4966 elif op in ("v_lshlrev_b64", "v_lshrrev_b64", "v_ashrrev_i64"):
4845 # v[d:d+1] = v[s:s+1] << / >> (src0 & 63): logical left, logical right, or arithmetic right (the sign 4967 # v[d:d+1] = v[s:s+1] << / >> (src0 & 63): logical left, logical right, or arithmetic right (the sign
4846 # bit 63 is copied in). 4968 # bit 63 is copied in).
@@ -5007,6 +5129,57 @@ class Gen:
5007 self.dst(a[0], v) 5129 self.dst(a[0], v)
5008 else: 5130 else:
5009 self.write_lo16(a[0], lo) 5131 self.write_lo16(a[0], lo)
5132 elif op in ("v_min3_i16", "v_min3_u16", "v_max3_i16", "v_max3_u16", "v_med3_i16", "v_med3_u16"):
5133 # Three-operand 16-bit integer min/max/median on the low halves (op_sel bits 0..2 pick the high half of
5134 # S0..S2, bit 3 writes the high half of D); VOP3-only, so the other half of D is kept (RDNA2 ISA; Mesa
5135 # ACO can_use_opsel). clamp is not modelled on integer min/max/med3.
5136 if "clamp" in mods:
5137 raise Unsupported(op + " clamp")
5138 sb, dhi = self.opsel_bits(mods, 3)
5139 if dhi and a[0]["k"] != "vgpr":
5140 raise Unsupported("op_sel destination")
5141 signed = op.endswith("_i16")
5142 vals = []
5143 for k, s_ in enumerate(a[1:4]):
5144 u = self.src_u(s_)
5145 if sb[k]:
5146 t = self.tmp()
5147 self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}")
5148 u = t
5149 h = self.tmp()
5150 if signed:
5151 self.emit(f"{h} = OpBitFieldSExtract %int {self.as_int(u)} {self.cu(0)} {self.cu(16)}")
5152 else:
5153 self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
5154 vals.append(h)
5155 x, y, z = vals
5156 ty, pfx = ("%int", "S") if signed else ("%uint", "U")
5157 if "med3" in op:
5158 lo_, hi_, m = self.tmp(), self.tmp(), self.tmp()
5159 self.emit(f"{lo_} = OpExtInst {ty} %glsl {pfx}Min {x} {y}")
5160 self.emit(f"{hi_} = OpExtInst {ty} %glsl {pfx}Max {x} {y}")
5161 self.emit(f"{m} = OpExtInst {ty} %glsl {pfx}Clamp {z} {lo_} {hi_}")
5162 else:
5163 m0, m = self.tmp(), self.tmp()
5164 fn = pfx + ("Min" if "min3" in op else "Max")
5165 self.emit(f"{m0} = OpExtInst {ty} %glsl {fn} {x} {y}")
5166 self.emit(f"{m} = OpExtInst {ty} %glsl {fn} {m0} {z}")
5167 if signed:
5168 r = self.tmp()
5169 self.emit(f"{r} = OpBitcast %uint {m}")
5170 else:
5171 r = m
5172 lo = self.tmp()
5173 self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}")
5174 if dhi:
5175 old, keep, sh16, v = (self.tmp() for _ in range(4))
5176 self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}")
5177 self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}")
5178 self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}")
5179 self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}")
5180 self.dst(a[0], v)
5181 else:
5182 self.write_lo16(a[0], lo)
5010 elif op == "v_bcnt_u32_b32": 5183 elif op == "v_bcnt_u32_b32":
5011 x, acc = self.src_u(a[1]), self.src_u(a[2]) 5184 x, acc = self.src_u(a[1]), self.src_u(a[2])
5012 c, r = self.tmp(), self.tmp() 5185 c, r = self.tmp(), self.tmp()
@@ -5100,7 +5273,8 @@ class Gen:
5100 elif op in ("s_movrels_b32", "s_movrels_b64"): 5273 elif op in ("s_movrels_b32", "s_movrels_b64"):
5101 # Relative SGPR read through M0 (RDNA2 ISA SOP1): D = SGPR[S0 + M0] (the b64 form reads the pair at 5274 # Relative SGPR read through M0 (RDNA2 ISA SOP1): D = SGPR[S0 + M0] (the b64 form reads the pair at
5102 # S0 + M0 and S0 + M0 + 1). The SGPR file is an array, so this is a dynamic load, as v_movrels is for 5275 # S0 + M0 and S0 + M0 + 1). The SGPR file is an array, so this is a dynamic load, as v_movrels is for
5103 # VGPRs. The index wraps to the 128 array slots, so it can't reach the lane-mask parking slots past them; 5276 # VGPRs. The index wraps to the 128 array slots, so it can't reach the lane-mask parking slots past them
5277 # (an SGPR that holds a lane mask is handled below);
5104 # the hardware's own range check (and reads past s105 landing on VCC and the other specials) is not 5278 # the hardware's own range check (and reads past s105 landing on VCC and the other specials) is not
5105 # modelled. SCC is not written. s_movreld (a dynamic SGPR write) stays Unsupported: the translator keeps 5279 # modelled. SCC is not written. s_movreld (a dynamic SGPR write) stays Unsupported: the translator keeps
5106 # translate-time knowledge of SGPR values (literal S# words, descriptor caches) a dynamic write would 5280 # translate-time knowledge of SGPR values (literal S# words, descriptor caches) a dynamic write would
@@ -5109,6 +5283,17 @@ class Gen:
5109 d, src = a[0], a[1] 5283 d, src = a[0], a[1]
5110 if d["k"] != "sgpr" or src["k"] != "sgpr" or d.get("n", 1) != n or src.get("n", 1) != n: 5284 if d["k"] != "sgpr" or src["k"] != "sgpr" or d.get("n", 1) != n or src.get("n", 1) != n:
5111 raise Unsupported(op + " operands") 5285 raise Unsupported(op + " operands")
5286 # An SGPR that lane_masks.py marks as a lane mask holds only this lane's bit, so a plain load would copy
5287 # that bit as data (a saved EXEC of 5 read back as 0xffffffff in lanes 0 and 2, 0 elsewhere). For each
5288 # such SGPR the whole wave's mask word is collected first (wave_mask, as for s_bcnt1) and replaces the
5289 # load when the index lands on it. D then holds the mask as data, which is what lane_masks.py assumes
5290 # for an s_movrels destination. The index is dynamic, so every mask SGPR here is a candidate (#1548,
5291 # SHADER-284).
5292 mask_words = []
5293 for r in sorted(k for k in self.cur_masks if isinstance(k, int) and k < self.SGPRS):
5294 reg = {"k": "sgpr", "r": r, "n": 1}
5295 lo, hi = self.wave_mask(reg)
5296 mask_words.append((r, hi if self.mask_half(reg) == "hi" else lo))
5112 m0 = self.tmp() 5297 m0 = self.tmp()
5113 self.emit(f"{m0} = OpLoad %uint %m0") 5298 self.emit(f"{m0} = OpLoad %uint %m0")
5114 vals = [] 5299 vals = []
@@ -5118,9 +5303,42 @@ class Gen:
5118 self.emit(f"{j} = OpBitwiseAnd %uint {i} {self.cu(self.SGPRS - 1)}") 5303 self.emit(f"{j} = OpBitwiseAnd %uint {i} {self.cu(self.SGPRS - 1)}")
5119 self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %sgpr {j}") 5304 self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %sgpr {j}")
5120 self.emit(f"{v} = OpLoad %uint {ptr}") 5305 self.emit(f"{v} = OpLoad %uint {ptr}")
5306 for r, word in mask_words:
5307 hit, sel = self.tmp(), self.tmp()
5308 self.emit(f"{hit} = OpIEqual %bool {j} {self.cu(r)}")
5309 self.emit(f"{sel} = OpSelect %uint {hit} {word} {v}")
5310 v = sel
5121 vals.append(v) 5311 vals.append(v)
5122 for w, v in enumerate(vals): # every read before the first write (D may overlap the source) 5312 for w, v in enumerate(vals): # every read before the first write (D may overlap the source)
5123 self.store_reg("sgpr", d["r"] + w, v) 5313 self.store_reg("sgpr", d["r"] + w, v)
5314 elif op == "v_swaprel_b32":
5315 # GFX10 VOP1 (opcode 104): swap VGPR[D + M0[25:16]] and VGPR[S0 + M0[9:0]], the fields v_movrelsd_2_b32
5316 # uses (RDNA2 ISA: tmp = VGPR[D + M0[25:16]]; VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]];
5317 # VGPR[S0 + M0[9:0]] = tmp). Both registers are read before either is written; inactive lanes keep both.
5318 # As for v_movrel*, the hardware's range check against the VGPR allocation is not modelled.
5319 d, s0 = a[0], a[1]
5320 if d["k"] != "vgpr" or s0["k"] != "vgpr":
5321 raise Unsupported(op + " operands")
5322 m0, lo, hi, md = (self.tmp() for _ in range(4))
5323 self.emit(f"{m0} = OpLoad %uint %m0")
5324 self.emit(f"{lo} = OpBitwiseAnd %uint {m0} {self.cu(0x3FF)}")
5325 self.emit(f"{hi} = OpShiftRightLogical %uint {m0} {self.cu(16)}")
5326 self.emit(f"{md} = OpBitwiseAnd %uint {hi} {self.cu(0x3FF)}")
5327 ptrs, vals = [], []
5328 for reg, off in ((d["r"], md), (s0["r"], lo)):
5329 i, p_, v = self.tmp(), self.tmp(), self.tmp()
5330 self.emit(f"{i} = OpIAdd %uint {self.cu(reg)} {off}")
5331 self.emit(f"{p_} = OpAccessChain %_ptr_Function_uint %vgpr {i}")
5332 self.emit(f"{v} = OpLoad %uint {p_}")
5333 ptrs.append(p_)
5334 vals.append(v)
5335 act = self.active_b()
5336 # D's slot gets S0's value, then S0's slot gets D's old value: when both name one register the second
5337 # store writes back its own value, so the register is unchanged, as a swap with itself is.
5338 for p_, new, old in ((ptrs[0], vals[1], vals[0]), (ptrs[1], vals[0], vals[1])):
5339 sel = self.tmp()
5340 self.emit(f"{sel} = OpSelect %uint {act} {new} {old}")
5341 self.emit(f"OpStore {p_} {sel}")
5124 elif op in ("v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"): 5342 elif op in ("v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"):
5125 # Relative VGPR indexing through M0: movrels reads VGPR[src + M0], movreld writes VGPR[dst + M0], 5343 # Relative VGPR indexing through M0: movrels reads VGPR[src + M0], movreld writes VGPR[dst + M0],
5126 # movrelsd does both. The register file is an array, so these become dynamic array accesses. 5344 # movrelsd does both. The register file is an array, so these become dynamic array accesses.
@@ -5153,10 +5371,16 @@ class Gen:
5153 self.emit(f"OpStore {dp} {sel}") 5371 self.emit(f"OpStore {dp} {sel}")
5154 else: 5372 else:
5155 self.dst(d, v) 5373 self.dst(d, v)
5156 elif op == "v_med3_f16": 5374 elif op in ("v_med3_f16", "v_min3_f16", "v_max3_f16"):
5157 sel, dhi = self.opsel_bits(mods, 3) # op_sel:[src0,src1,src2,dst] 5375 sel, dhi = self.opsel_bits(mods, 3) # op_sel:[src0,src1,src2,dst]
5158 vals = [self.f16_in(s, sel[i]) for i, s in enumerate(a[1:4])] 5376 vals = [self.f16_in(s, sel[i]) for i, s in enumerate(a[1:4])]
5159 r = self.med3_f(vals, a[1:4], sel) 5377 if op == "v_med3_f16":
5378 r = self.med3_f(vals, a[1:4], sel)
5379 else:
5380 f = "NMax" if "max" in op else "NMin" # a NaN operand gives the other one (docs/design.md)
5381 m, r = self.tmp(), self.tmp()
5382 self.emit(f"{m} = OpExtInst %float %glsl {f} {vals[0]} {vals[1]}")
5383 self.emit(f"{r} = OpExtInst %float %glsl {f} {m} {vals[2]}")
5160 r = self.clamp_mods(r, mods) 5384 r = self.clamp_mods(r, mods)
5161 self.f16_out(a[0], r, dhi) # opsel-capable VOP3: keeps the other half (Mesa ACO can_use_opsel) 5385 self.f16_out(a[0], r, dhi) # opsel-capable VOP3: keeps the other half (Mesa ACO can_use_opsel)
5162 elif op in ("v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8"): 5386 elif op in ("v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8"):
@@ -5411,13 +5635,20 @@ class Gen:
5411 else: 5635 else:
5412 self.mask_dst(d, r) 5636 self.mask_dst(d, r)
5413 elif op == "s_not_b32": 5637 elif op == "s_not_b32":
5414 x = self.src_u(a[1]) 5638 x_val = self.imm_val(a[1])
5415 r = self.tmp() 5639 if x_val is not None:
5416 self.emit(f"{r} = OpNot %uint {x}") 5640 val = (~x_val) & 0xFFFFFFFF
5417 self.dst(a[0], r) 5641 r = self.cu(val)
5418 z = self.tmp() 5642 self.dst(a[0], r)
5419 self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") 5643 self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}")
5420 self.emit(f"OpStore %scc {z}") 5644 else:
5645 x = self.src_u(a[1])
5646 r = self.tmp()
5647 self.emit(f"{r} = OpNot %uint {x}")
5648 self.dst(a[0], r)
5649 z = self.tmp()
5650 self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}")
5651 self.emit(f"OpStore %scc {z}")
5421 elif op in ("s_cmp_eq_u64", "s_cmp_lg_u64"): 5652 elif op in ("s_cmp_eq_u64", "s_cmp_lg_u64"):
5422 # 64-bit compare of masks/pointers: equal iff both halves are equal. 5653 # 64-bit compare of masks/pointers: equal iff both halves are equal.
5423 m0, m1 = self.holds_lane_mask(a[0]), self.holds_lane_mask(a[1]) 5654 m0, m1 = self.holds_lane_mask(a[0]), self.holds_lane_mask(a[1])
@@ -5661,6 +5892,16 @@ class Gen:
5661 self.cu(3), self.cu(4) 5892 self.cu(3), self.cu(4)
5662 elif op in ("s_add_i32", "s_sub_i32", "s_min_u32", "s_max_u32", "s_xor_b32", "s_andn2_b32", 5893 elif op in ("s_add_i32", "s_sub_i32", "s_min_u32", "s_max_u32", "s_xor_b32", "s_andn2_b32",
5663 "s_cselect_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): 5894 "s_cselect_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"):
5895 if op == "s_xor_b32":
5896 x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2])
5897 writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec")
5898 is_mask = not self.wave64 and (writes_exec or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2]))
5899 if x_val is not None and y_val is not None and not is_mask:
5900 val = (x_val ^ y_val) & 0xFFFFFFFF
5901 r = self.cu(val)
5902 self.dst(a[0], r)
5903 self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}")
5904 return
5664 x, y = self.src_u(a[1]), self.src_u(a[2]) 5905 x, y = self.src_u(a[1]), self.src_u(a[2])
5665 r = self.tmp() 5906 r = self.tmp()
5666 if op == "s_cselect_b32": 5907 if op == "s_cselect_b32":
@@ -5889,7 +6130,10 @@ class Gen:
5889 self.dst(a[0], self.tou(f)) 6130 self.dst(a[0], self.tou(f))
5890 elif op == "s_movk_i32": 6131 elif op == "s_movk_i32":
5891 v = a[1]["v"] & 0xFFFF 6132 v = a[1]["v"] & 0xFFFF
5892 self.dst(a[0], self.cu(v - 0x10000 if v & 0x8000 else v)) 6133 val = (v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF
6134 self.dst(a[0], self.cu(val))
6135 if a[0]["k"] == "sgpr" and self.desc_cache_ok():
6136 self.sgpr_imm[a[0]["r"]] = val
5893 elif op in ("s_cmov_b32", "s_cmovk_i32"): 6137 elif op in ("s_cmov_b32", "s_cmovk_i32"):
5894 # D = SCC ? S0 : D (s_cmovk_i32: S0 is the 16-bit immediate, sign-extended). SCC is read, not written. 6138 # D = SCC ? S0 : D (s_cmovk_i32: S0 is the 16-bit immediate, sign-extended). SCC is read, not written.
5895 if a[0]["k"] != "sgpr": 6139 if a[0]["k"] != "sgpr":
@@ -5904,6 +6148,26 @@ class Gen:
5904 self.emit(f"{c} = OpLoad %uint %scc") 6148 self.emit(f"{c} = OpLoad %uint %scc")
5905 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(c)} {x} {old}") 6149 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(c)} {x} {old}")
5906 self.dst(a[0], r) 6150 self.dst(a[0], r)
6151 elif op == "s_cmov_b64":
6152 # RDNA2 ISA SOP1: D = SCC ? S0 : D, SCC read and not written (LLVM AMDGPU SOPInstructions.td:
6153 # S_CMOV_B64 : SOP1_64 under Uses = [SCC]). Plain 64-bit data only: a lane-mask pair holds one
6154 # lane's bit here, so selecting it as data would silently read a bool instead of the wave's mask
6155 # (issue #210). Those operands keep failing loudly.
6156 if self.is_mask_op(a[1]) or self.any_mask_word(a[1]) or self.any_ever_mask_word(a[1]):
6157 raise Unsupported("s_cmov_b64 lane-mask source")
6158 if a[0]["k"] != "sgpr" or a[0].get("n") != 2:
6159 raise Unsupported("s_cmov_b64 destination")
6160 if self.holds_lane_mask(a[0]) or self.any_mask_word(a[0]) or self.any_ever_mask_word(a[0]):
6161 raise Unsupported("s_cmov_b64 lane-mask destination")
6162 (xlo, xhi) = self.src64_data(a[1], op)
6163 # Read both old dwords before any store, so D overlapping S0 stays exact.
6164 oldlo, oldhi = self.load_reg("sgpr", a[0]["r"]), self.load_reg("sgpr", a[0]["r"] + 1)
6165 c, rlo, rhi = self.tmp(), self.tmp(), self.tmp()
6166 self.emit(f"{c} = OpLoad %uint %scc")
6167 b = self.tmp_bool_nz(c)
6168 self.emit(f"{rlo} = OpSelect %uint {b} {xlo} {oldlo}")
6169 self.emit(f"{rhi} = OpSelect %uint {b} {xhi} {oldhi}")
6170 self.dst64_data(a[0], rlo, rhi, op)
5907 elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class") and not op.endswith(("_u64", "_i64")): 6171 elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class") and not op.endswith(("_u64", "_i64")):
5908 self.compare(op, a, scalar=False, mods=mods) 6172 self.compare(op, a, scalar=False, mods=mods)
5909 elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class") and not op.endswith(("_u64", "_i64")): 6173 elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class") and not op.endswith(("_u64", "_i64")):
@@ -6159,16 +6423,7 @@ class Gen:
6159 self.scc_nonzero(r) 6423 self.scc_nonzero(r)
6160 elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): 6424 elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"):
6161 vals = self.fma_mix_srcs(a, mods) 6425 vals = self.fma_mix_srcs(a, mods)
6162 r = self.tmp() 6426 r = self.fma_mix_odd(*vals)
6163 self.emit_fma(r, vals[0], vals[1], vals[2])
6164 if self.round_mode:
6165 # Toward zero the hardware rounds the exact fma once, to f16; round-to-odd at f32 narrows exactly.
6166 # Nearest even keeps the f32 Fma then narrow (unchanged).
6167 ro, m, isz, rs = self.fma_mix_odd(*vals), self.tmp(), self.tmp(), self.tmp()
6168 self.emit(f"{m} = OpLoad %uint %mode_r16")
6169 self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}")
6170 self.emit(f"{rs} = OpSelect %float {isz} {ro} {r}")
6171 r = rs
6172 r = self.clamp_mods(r, mods) 6427 r = self.clamp_mods(r, mods)
6173 self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16")) 6428 self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16"))
6174 elif op == "v_cvt_pk_u8_f32": 6429 elif op == "v_cvt_pk_u8_f32":
@@ -6423,19 +6678,49 @@ class Gen:
6423 self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}") 6678 self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}")
6424 self.dst(a[0], result) 6679 self.dst(a[0], result)
6425 elif op in U2 or op in S2: 6680 elif op in U2 or op in S2:
6426 x, y = self.src_u(a[1]), self.src_u(a[2]) 6681 if op in S2:
6682 x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2])
6683 writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec")
6684 is_mask = not self.wave64 and (writes_exec or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2]))
6685 if x_val is not None and y_val is not None and not is_mask:
6686 folded = None
6687 if op == "s_and_b32":
6688 folded = (x_val & y_val) & 0xFFFFFFFF
6689 elif op == "s_or_b32":
6690 folded = (x_val | y_val) & 0xFFFFFFFF
6691 elif op == "s_lshl_b32":
6692 folded = (x_val << (y_val & 31)) & 0xFFFFFFFF
6693 elif op == "s_lshr_b32":
6694 folded = (x_val >> (y_val & 31)) & 0xFFFFFFFF
6695 elif op == "s_mul_i32":
6696 folded = (x_val * y_val) & 0xFFFFFFFF
6697 if folded is not None:
6698 r = self.cu(folded)
6699 self.dst(a[0], r)
6700 if op in ("s_and_b32", "s_or_b32", "s_lshl_b32", "s_lshr_b32"):
6701 self.emit(f"OpStore %scc {self.cu(1 if folded != 0 else 0)}")
6702 return
6427 r = self.tmp() 6703 r = self.tmp()
6428 kind = U2.get(op) or S2.get(op) 6704 kind = U2.get(op) or S2.get(op)
6429 if kind == "mul24": 6705 if kind == "mul24":
6706 x, y = self.src_u(a[1]), self.src_u(a[2])
6430 xm, ym = self.tmp(), self.tmp() 6707 xm, ym = self.tmp(), self.tmp()
6431 self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}") 6708 self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}")
6432 self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}") 6709 self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}")
6433 self.emit(f"{r} = OpIMul %uint {xm} {ym}") 6710 self.emit(f"{r} = OpIMul %uint {xm} {ym}")
6434 else: 6711 else:
6435 if op in ("s_lshl_b32", "s_lshr_b32"): 6712 if op in ("s_lshl_b32", "s_lshr_b32"):
6436 m = self.tmp() 6713 y_val = self.imm_val(a[2])
6437 self.emit(f"{m} = OpBitwiseAnd %uint {y} {self.cu(31)}") 6714 if y_val is not None:
6438 y = m 6715 y = self.cu(y_val & 31)
6716 else:
6717 y_raw = self.src_u(a[2])
6718 m = self.tmp()
6719 self.emit(f"{m} = OpBitwiseAnd %uint {y_raw} {self.cu(31)}")
6720 y = m
6721 else:
6722 y = self.src_u(a[2])
6723 x = self.src_u(a[1])
6439 self.emit(f"{r} = {kind} %uint {x} {y}") 6724 self.emit(f"{r} = {kind} %uint {x} {y}")
6440 self.dst(a[0], r) 6725 self.dst(a[0], r)
6441 if op in ("s_and_b32", "s_or_b32"): 6726 if op in ("s_and_b32", "s_or_b32"):
@@ -6443,18 +6728,41 @@ class Gen:
6443 elif op in ("s_lshl_b32", "s_lshr_b32"): 6728 elif op in ("s_lshl_b32", "s_lshr_b32"):
6444 self.scc_nonzero(r) 6729 self.scc_nonzero(r)
6445 elif op in SHIFT_REV: 6730 elif op in SHIFT_REV:
6446 sh, x = self.src_u(a[1]), self.src_u(a[2]) 6731 sh_val = self.imm_val(a[1])
6447 m, r = self.tmp(), self.tmp() 6732 if sh_val is not None:
6448 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") 6733 m = self.cu(sh_val & 31)
6734 else:
6735 sh = self.src_u(a[1])
6736 m = self.tmp()
6737 self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}")
6738 x = self.src_u(a[2])
6739 r = self.tmp()
6449 self.emit(f"{r} = {SHIFT_REV[op]} %uint {x} {m}") 6740 self.emit(f"{r} = {SHIFT_REV[op]} %uint {x} {m}")
6450 self.dst(a[0], r) 6741 self.dst(a[0], r)
6451 elif op in ("v_bfe_u32", "v_bfe_i32"): 6742 elif op in ("v_bfe_u32", "v_bfe_i32"):
6452 # offset and width are taken mod 32 (a width of 0 gives 0) 6743 # offset and width are taken mod 32 (a width of 0 gives 0)
6453 x, o, w = (self.src_u(t) for t in a[1:4]) 6744 o_val, w_val = self.imm_val(a[2]), self.imm_val(a[3])
6454 om, wm, r = self.tmp(), self.tmp(), self.tmp() 6745 if o_val is not None and w_val is not None:
6455 self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}") 6746 off = o_val & 31
6456 self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}") 6747 wid = min(w_val & 31, 32 - off)
6457 wc = self.bfe_width(om, wm) 6748 om = self.cu(off)
6749 wc = self.cu(wid)
6750 else:
6751 if o_val is not None:
6752 om = self.cu(o_val & 31)
6753 else:
6754 o = self.src_u(a[2])
6755 om = self.tmp()
6756 self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}")
6757 if w_val is not None:
6758 wm = self.cu(w_val & 31)
6759 else:
6760 w = self.src_u(a[3])
6761 wm = self.tmp()
6762 self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}")
6763 wc = self.bfe_width(om, wm)
6764 x = self.src_u(a[1])
6765 r = self.tmp()
6458 f = "OpBitFieldSExtract" if op.endswith("i32") else "OpBitFieldUExtract" 6766 f = "OpBitFieldSExtract" if op.endswith("i32") else "OpBitFieldUExtract"
6459 self.emit(f"{r} = {f} %uint {x} {om} {wc}") 6767 self.emit(f"{r} = {f} %uint {x} {om} {wc}")
6460 self.dst(a[0], r) 6768 self.dst(a[0], r)
@@ -6534,6 +6842,24 @@ class Gen:
6534 self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}") 6842 self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}")
6535 self.emit(f"{r} = OpIAdd %uint {m} {self.src_u(a[3])}") 6843 self.emit(f"{r} = OpIAdd %uint {m} {self.src_u(a[3])}")
6536 self.dst(a[0], r) 6844 self.dst(a[0], r)
6845 elif op in ("v_dot4_i32_i8", "v_dot4c_i32_i8"):
6846 # The four products of the signed bytes of two dwords, summed, plus an addend: the third source for
6847 # v_dot4_i32_i8 (VOP3P), the destination's old value for v_dot4c_i32_i8 (VOP2). The sum wraps at 32 bits.
6848 # Measured on RDNA2 hardware (docs/design.md, "Signed-byte dot products"), where clamp saturates
6849 # v_dot4_i32_i8 to a signed 32-bit value and op_sel picks the 16-bit half of a source each half of the
6850 # product reads. llvm-mc prints neither for the programs measured, so both forms are refused, not guessed.
6851 if "clamp" in mods or any(m.startswith("op_sel") for m in mods):
6852 raise Unsupported(op + (" clamp" if "clamp" in mods else " op_sel"))
6853 x, y = self.src_u(a[1]), self.src_u(a[2])
6854 acc = self.src_u(a[3]) if op == "v_dot4_i32_i8" else self.src_u(a[0])
6855 for i in range(4):
6856 xb, yb, prod, total = (self.tmp() for _ in range(4))
6857 self.emit(f"{xb} = OpBitFieldSExtract %uint {x} {self.cu(8 * i)} {self.cu(8)}")
6858 self.emit(f"{yb} = OpBitFieldSExtract %uint {y} {self.cu(8 * i)} {self.cu(8)}")
6859 self.emit(f"{prod} = OpIMul %uint {xb} {yb}")
6860 self.emit(f"{total} = OpIAdd %uint {acc} {prod}")
6861 acc = total
6862 self.dst(a[0], acc)
6537 elif op == "v_mad_u32_u24": 6863 elif op == "v_mad_u32_u24":
6538 x, y, z = (self.src_u(t) for t in a[1:4]) 6864 x, y, z = (self.src_u(t) for t in a[1:4])
6539 xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() 6865 xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp()
@@ -6602,8 +6928,12 @@ class Gen:
6602 except ValueError: 6928 except ValueError:
6603 raise Unsupported(f"{op} offset:{inst[0]}") from None 6929 raise Unsupported(f"{op} offset:{inst[0]}") from None
6604 reg = None 6930 reg = None
6931 off_val = self.imm_val(off)
6605 if off["k"] == "imm": 6932 if off["k"] == "imm":
6606 imm = off["v"] # immediate-only form 6933 imm = off["v"] # immediate-only form
6934 elif off_val is not None:
6935 off_trunc = off_val & ~3
6936 imm = (imm & ~3) + off_trunc
6607 else: 6937 else:
6608 reg = self.src_u(off) 6938 reg = self.src_u(off)
6609 if sbuf: 6939 if sbuf:
@@ -6634,21 +6964,36 @@ class Gen:
6634 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") 6964 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
6635 self.uses_psb = True 6965 self.uses_psb = True
6636 lim = None 6966 lim = None
6967 lim_val = None
6637 if sbuf: 6968 if sbuf:
6638 # limit = NUM_RECORDS * stride, or NUM_RECORDS when stride is 0 (bytes, 64-bit so the product can't wrap) 6969 # limit = NUM_RECORDS * stride, or NUM_RECORDS when stride is 0 (bytes, 64-bit so the product can't wrap)
6639 stride, nr64, st64, prod, raw, lim = (self.tmp() for _ in range(6)) 6970 lit1 = self.sgpr_imm.get(base["r"] + 1)
6640 nr = self.load_reg("sgpr", base["r"] + 2) 6971 lit2 = self.sgpr_imm.get(base["r"] + 2)
6641 self.emit(f"{stride} = OpBitFieldUExtract %uint {word1} {self.cu(16)} {self.cu(14)}") 6972 if lit1 is not None and lit2 is not None:
6642 self.emit(f"{nr64} = OpUConvert %ulong {nr}") 6973 stride = (lit1 >> 16) & 0x3FFF
6643 self.emit(f"{st64} = OpUConvert %ulong {stride}") 6974 lim_val = lit2 if stride == 0 else lit2 * stride
6644 self.emit(f"{prod} = OpIMul %ulong {nr64} {st64}") 6975 lim = self.cl(lim_val)
6645 self.emit(f"{raw} = OpIEqual %bool {stride} {self.cu(0)}") 6976 else:
6646 self.emit(f"{lim} = OpSelect %ulong {raw} {nr64} {prod}") 6977 stride, nr64, st64, prod, raw, lim = (self.tmp() for _ in range(6))
6978 nr = self.load_reg("sgpr", base["r"] + 2)
6979 self.emit(f"{stride} = OpBitFieldUExtract %uint {word1} {self.cu(16)} {self.cu(14)}")
6980 self.emit(f"{nr64} = OpUConvert %ulong {nr}")
6981 self.emit(f"{st64} = OpUConvert %ulong {stride}")
6982 self.emit(f"{prod} = OpIMul %ulong {nr64} {st64}")
6983 self.emit(f"{raw} = OpIEqual %bool {stride} {self.cu(0)}")
6984 self.emit(f"{lim} = OpSelect %ulong {raw} {nr64} {prod}")
6647 for i in range(n): 6985 for i in range(n):
6648 p, v = self.tmp(), self.tmp() 6986 p, v = self.tmp(), self.tmp()
6649 if lim is None: 6987 if lim is None:
6650 self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") 6988 self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}")
6651 self.emit(f"{v} = OpLoad %uint {p} Aligned 4") 6989 self.emit(f"{v} = OpLoad %uint {p} Aligned 4")
6990 elif lim_val is not None and reg is None:
6991 end_val = imm + 4 * i + 4
6992 if lim_val >= end_val:
6993 self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}")
6994 self.emit(f"{v} = OpLoad %uint {p} Aligned 4")
6995 else:
6996 v = self.cu(0)
6652 else: 6997 else:
6653 # dword i is in range when off + 4*i + 4 <= limit; outside it memory is not read and the result is 0 6998 # dword i is in range when off + 4*i + 4 <= limit; outside it memory is not read and the result is 0
6654 end, ok, got = self.tmp(), self.tmp(), self.tmp() 6999 end, ok, got = self.tmp(), self.tmp(), self.tmp()
@@ -8489,7 +8834,11 @@ def dedupe_types(text):
8489 (%v4uint for r32ui storage, %v4uint_st for typed stores, %v4uint_in for vertex inputs): keep the first 8834 (%v4uint for r32ui storage, %v4uint_st for typed stores, %v4uint_in for vertex inputs): keep the first
8490 declaration of each OpTypeVector / OpTypePointer and rename the others everywhere.""" 8835 declaration of each OpTypeVector / OpTypePointer and rename the others everywhere."""
8491 alias, seen, out = {}, {}, [] 8836 alias, seen, out = {}, {}, []
8492 for line in text.split("\n"): 8837 lines = text.split("\n")
8838 for i, line in enumerate(lines):
8839 if " = OpFunction " in line:
8840 out.extend(lines[i:])
8841 break
8493 m = _TYPE_DECL.match(line) 8842 m = _TYPE_DECL.match(line)
8494 if m: 8843 if m:
8495 name, opc, rest = m.groups() 8844 name, opc, rest = m.groups()
@@ -8501,7 +8850,8 @@ def dedupe_types(text):
8501 out.append(line) 8850 out.append(line)
8502 if not alias: 8851 if not alias:
8503 return text 8852 return text
8504 return "\n".join(_ID_REF.sub(lambda t: alias.get(t.group(0), t.group(0)), l) for l in out) 8853 pattern = re.compile(r"(?:" + "|".join(re.escape(k) for k in sorted(alias, key=len, reverse=True)) + r")\b")
8854 return pattern.sub(lambda m: alias[m.group(0)], "\n".join(out))
8505 8855
8506 8856
8507def mesh_compute_epilogue(gen): 8857def mesh_compute_epilogue(gen):
@@ -8683,6 +9033,11 @@ def assemble(gen):
8683 used = set(gen.inputs.values()) 9033 used = set(gen.inputs.values())
8684 if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute 9034 if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute
8685 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") 9035 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute")
9036 # The producer fills both halves of every attribute in f16_halves (the index's f16_halves lists the pair), so a
9037 # raw attribute at the location of a half this shader doesn't read is overwritten all the same.
9038 reserved = {f16_half_location(n, h) for n in gen.f16_halves for h in (0, 1)}
9039 if any(not k.startswith("%in_f16h") and v in reserved for k, v in gen.inputs.items()):
9040 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute")
8686 gen.bary_location = next(n for n in range(len(used) + 1) if n not in used) if bary and BARY_FALLBACK else None 9041 gen.bary_location = next(n for n in range(len(used) + 1) if n not in used) if bary and BARY_FALLBACK else None
8687 bary_builtin = bary and gen.bary_location is None 9042 bary_builtin = bary and gen.bary_location is None
8688 if gen.frag_inputs or bary: 9043 if gen.frag_inputs or bary:
@@ -9636,7 +9991,7 @@ def read_before_write_vgprs(insns):
9636 regs += range(x["r"], x["r"] + x.get("n", 1)) 9991 regs += range(x["r"], x["r"] + x.get("n", 1))
9637 elif x["k"] == "vlist": 9992 elif x["k"] == "vlist":
9638 regs += x["r"] 9993 regs += x["r"]
9639 if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16") or 9994 if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8") or
9640 (op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half 9995 (op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half
9641 regs.append(a[0]["r"]) 9996 regs.append(a[0]["r"])
9642 for r in regs: 9997 for r in regs:
@@ -9864,7 +10219,7 @@ def reg_reads_writes(insns):
9864 regs += range(x["r"], x["r"] + x.get("n", 1)) 10219 regs += range(x["r"], x["r"] + x.get("n", 1))
9865 elif x["k"] == "vlist": 10220 elif x["k"] == "vlist":
9866 regs += x["r"] 10221 regs += x["r"]
9867 if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_fmac_f16") and a[0]["k"] == "vgpr": 10222 if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_fmac_f16", "v_dot4c_i32_i8") and a[0]["k"] == "vgpr":
9868 regs.append(a[0]["r"]) 10223 regs.append(a[0]["r"])
9869 rr.update(regs) 10224 rr.update(regs)
9870 if not reads_all and a[0]["k"] == "vgpr": 10225 if not reads_all and a[0]["k"] == "vgpr":
@@ -10091,6 +10446,10 @@ def translate(path):
10091 if stage not in ("vs", "ps", "cs", "ms", "gs"): 10446 if stage not in ("vs", "ps", "cs", "ms", "gs"):
10092 raise Unsupported(f"stage {stage}") 10447 raise Unsupported(f"stage {stage}")
10093 insns = info["insns"] 10448 insns = info["insns"]
10449 if not insns:
10450 # parse_file only reads tab-indented instructions, so a hand-written or re-indented .s parses to nothing
10451 # and used to translate to a module that passes spirv-val and does no work at all. Refuse it instead.
10452 raise Unsupported("no instructions (nothing tab-indented?)")
10094 if info["invalid"]: 10453 if info["invalid"]:
10095 # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to 10454 # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to
10096 # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then 10455 # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then
@@ -10814,8 +11173,12 @@ def shader_meta(g, asm, src_path=None, fssm_path=None):
10814 "features": sorted({feats[c] for c in caps if c in feats and not feats[c].startswith(("core", "shaderImage1D"))}), 11173 "features": sorted({feats[c] for c in caps if c in feats and not feats[c].startswith(("core", "shaderImage1D"))}),
10815 "bindings": binds, "push_constant_bytes": 4 * USER_SGPRS + 16, 11174 "bindings": binds, "push_constant_bytes": 4 * USER_SGPRS + 16,
10816 "subgroup_size": 64 if g.wave64 else 32, 11175 "subgroup_size": 64 if g.wave64 else 32,
10817 # 64-wide subgroups can only be requested for compute/mesh on RADV and NVIDIA; VS/PS/GS wave64 11176 # Which stages can ask for a 64-wide subgroup is the driver's requiredSubgroupSizeStages, not a fixed rule:
10818 # shaders must be treated as emulated (per-32-lane halves) until cross-half ops go through LDS. 11177 # the AMD Windows driver (FRAGMENT | COMPUTE | TASK | MESH) and Mesa RADV on GFX10+ (COMPUTE | FRAGMENT |
11178 # task/mesh) allow a wave64 PS to request 64, so it is exact there; NVIDIA has no 64 at all, and no driver
11179 # lists VERTEX or GEOMETRY. The runtime decides per device (runtime/src/subgroup_size.h) from `wave64`,
11180 # `subgroup_size` and `wave64_exchange`. This field stays true for VS/PS/GS wave64 (consumers rely on it):
11181 # it says the shader has no cross-half exchange, so it is per-subgroup, not that it must run 2x32.
10819 "wave64_emulated": bool(g.wave64 and (g.stage in ("vs", "ps", "gs") or g.emulate))} 11182 "wave64_emulated": bool(g.wave64 and (g.stage in ("vs", "ps", "gs") or g.emulate))}
10820 if g.w64g: 11183 if g.w64g:
10821 # SHADER-10: partition invariance on 32-wide subgroups. A and B are exact there (B: aggregated atomics up to 11184 # SHADER-10: partition invariance on 32-wide subgroups. A and B are exact there (B: aggregated atomics up to
@@ -11051,15 +11414,25 @@ def main():
11051 why, ok, valid = Counter(), 0, 0 11414 why, ok, valid = Counter(), 0, 0
11052 meta = {} 11415 meta = {}
11053 invalid = set() 11416 invalid = set()
11417
11418 def drop_stale(name):
11419 # A shader that no longer translates must not stay published from an earlier run: remove its old
11420 # module, and the index merge below drops its entry, exactly like a spirv-as/val rejection. The
11421 # .spvasm text stays for diagnosis, as it does on a rejection.
11422 Path(os.path.join(a.out, name + ".spv")).unlink(missing_ok=True)
11423 invalid.add(name)
11424
11054 for p in files: 11425 for p in files:
11055 name = os.path.splitext(os.path.basename(p))[0] 11426 name = os.path.splitext(os.path.basename(p))[0]
11056 try: 11427 try:
11057 asm = translate(p) 11428 asm = translate(p)
11058 except Unsupported as e: 11429 except Unsupported as e:
11059 why[str(e)] += 1 11430 why[str(e)] += 1
11431 drop_stale(name)
11060 continue 11432 continue
11061 except (IndexError, KeyError, ValueError) as e: 11433 except (IndexError, KeyError, ValueError) as e:
11062 why[f"translator error {type(e).__name__}"] += 1 11434 why[f"translator error {type(e).__name__}"] += 1
11435 drop_stale(name)
11063 continue 11436 continue
11064 ok += 1 11437 ok += 1
11065 sa = os.path.join(a.out, name + ".spvasm") 11438 sa = os.path.join(a.out, name + ".spvasm")
@@ -11075,7 +11448,7 @@ def main():
11075 except Exception as e: # noqa: BLE001 - metadata must never cost a translation 11448 except Exception as e: # noqa: BLE001 - metadata must never cost a translation
11076 meta[name] = {"error": f"{type(e).__name__}: {e}"} 11449 meta[name] = {"error": f"{type(e).__name__}: {e}"}
11077 else: 11450 else:
11078 invalid.add(name) 11451 drop_stale(name)
11079 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1 11452 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1
11080 if a.no_asm and os.path.exists(sa): 11453 if a.no_asm and os.path.exists(sa):
11081 os.remove(sa) 11454 os.remove(sa)
diff --git a/tools/restofworld_index.py b/tools/restofworld_index.py
index a784e4281..c890cf65b 100644
--- a/tools/restofworld_index.py
+++ b/tools/restofworld_index.py
@@ -326,7 +326,7 @@ def write_output(path, rows, summary):
326 json.dump({"summary": summary, "files": rows}, f, indent=1) 326 json.dump({"summary": summary, "files": rows}, f, indent=1)
327 return 327 return
328 with open(path, "w", encoding="utf-8", newline="") as f: 328 with open(path, "w", encoding="utf-8", newline="") as f:
329 writer = csv.writer(f) 329 writer = csv.writer(f, lineterminator="\n")
330 writer.writerow(COLUMNS) 330 writer.writerow(COLUMNS)
331 for row in rows: 331 for row in rows:
332 writer.writerow([f"0x{row['offset']:x}" if i == 0 else ("" if row[c] is None else row[c]) 332 writer.writerow([f"0x{row['offset']:x}" if i == 0 else ("" if row[c] is None else row[c])
diff --git a/tools/rsc8_audio.py b/tools/rsc8_audio.py
index 0998f29db..28f9c6709 100644
--- a/tools/rsc8_audio.py
+++ b/tools/rsc8_audio.py
@@ -1498,7 +1498,7 @@ def write_report(path, records, summary):
1498 ext = os.path.splitext(path)[1].lower() 1498 ext = os.path.splitext(path)[1].lower()
1499 if ext == ".csv": 1499 if ext == ".csv":
1500 def _write_csv(f): 1500 def _write_csv(f):
1501 w = csv.writer(f) 1501 w = csv.writer(f, lineterminator="\n")
1502 w.writerow(CSV_COLUMNS) 1502 w.writerow(CSV_COLUMNS)
1503 for r in records: 1503 for r in records:
1504 row = [] 1504 row = []
diff --git a/tools/salu_diff.py b/tools/salu_diff.py
index 244bee384..e34c5c96f 100644
--- a/tools/salu_diff.py
+++ b/tools/salu_diff.py
@@ -71,7 +71,8 @@ OUT_SCC = 30 # s_cselect_b32 s30, 1, 0 observes SCC at the end
71BFE_ANY = False # any s_bfe_* control word (--bfe-any), not only offset + width <= 32 71BFE_ANY = False # any s_bfe_* control word (--bfe-any), not only offset + width <= 32
72INLINE64 = False # inline constants in 64-bit positions (--inline64); the translator reads those as lane masks 72INLINE64 = False # inline constants in 64-bit positions (--inline64); the translator reads those as lane masks
73 73
74LANE_MASK_OPS = ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_not_b64", "s_wqm_b64", 74LANE_MASK_OPS = ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_nand_b64", "s_nor_b64",
75 "s_xnor_b64", "s_not_b64", "s_wqm_b64",
75 "s_wqm_b32", "s_cselect_b64", "s_bfm_b64") 76 "s_wqm_b32", "s_cselect_b64", "s_bfm_b64")
76 77
77INTERESTING = (0, 1, 2, 3, 31, 32, 33, 63, 64, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE, 78INTERESTING = (0, 1, 2, 3, 31, 32, 33, 63, 64, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE,
@@ -172,7 +173,9 @@ def _sop2():
172def _sop2_64(): 173def _sop2_64():
173 ops = {} 174 ops = {}
174 for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b), 175 for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b),
175 ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b)): 176 ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b),
177 ("nand", lambda a, b: ~(a & b)), ("nor", lambda a, b: ~(a | b)),
178 ("xnor", lambda a, b: ~(a ^ b))):
176 ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0))) 179 ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0)))
177 ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None)) 180 ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None))
178 ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0))) 181 ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0)))
diff --git a/tools/shader_link_check.py b/tools/shader_link_check.py
new file mode 100644
index 000000000..901fb2949
--- /dev/null
+++ b/tools/shader_link_check.py
@@ -0,0 +1,313 @@
1"""Check user-defined varying interfaces between translated graphics stages.
2
3Run `python -I tools/shader_link_check.py --help` for standalone pairs, batch checks,
4and reflection of a single SPIR-V module.
5"""
6from __future__ import annotations
7
8import argparse
9from dataclasses import asdict, dataclass
10import json
11import os
12from pathlib import Path
13import re
14import sys
15import tempfile
16
17sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
18from file_mode import published_mode # noqa: E402
19from spirv_interface import (Address, Declaration, InterfaceError, NumericType, # noqa: E402
20 StageInterface, reflect_module)
21
22
23STAGES = ("vs", "gs", "ms", "ps")
24CHAINS = {("vs", "ps"), ("vs", "gs", "ps"), ("ms", "ps"), ("vs", "gs")}
25STEM = re.compile(r"[a-zA-Z0-9_][a-zA-Z0-9_.-]*\Z")
26
27
28@dataclass(frozen=True)
29class ModulePath:
30 path: Path
31 stage: str
32 entry: str = "main"
33
34
35@dataclass(frozen=True)
36class Pipeline:
37 name: str
38 modules: tuple[ModulePath, ...]
39
40
41@dataclass(frozen=True)
42class Problem:
43 kind: str
44 consumer: str
45 message: str
46 producer: str | None = None
47 location: Address | None = None
48
49 def display(self):
50 stages = f"{self.producer} -> {self.consumer}" if self.producer else self.consumer
51 where = f" at {self.location.describe()}" if self.location is not None else ""
52 return f"{stages}{where} [{self.kind}] {self.message}"
53
54
55@dataclass
56class PipelineResult:
57 name: str
58 status: str
59 links_checked: int
60 problems: list[Problem]
61
62
63def wider_vector_compatible(producer, consumer, allow):
64 if not allow or producer.structure or consumer.structure:
65 return False
66 if producer.indexed_by_vertex_or_primitive or consumer.indexed_by_vertex_or_primitive:
67 return False
68 p, c = producer.varyings[0].type, consumer.varyings[0].type
69 # maintenance4 relaxes the length of vector variables. Scalar vs vector, nested types,
70 # and arrays which were unwrapped for a stage's invocation index still need exact types.
71 return (isinstance(p, NumericType) and isinstance(c, NumericType)
72 and p.kind == c.kind and p.width == c.width and p.components > c.components >= 2)
73
74
75def compare_stages(producer: StageInterface, consumer: StageInterface, maintenance4=False):
76 """Check consumer declarations against the preceding stage's output declarations."""
77 output_slots = {slot: declaration
78 for declaration in producer.outputs
79 for varying in declaration.varyings
80 for slot in varying.occupied()}
81 problems = []
82 for expected in consumer.inputs:
83 anchor = expected.varyings[0].address
84 actual = output_slots.get(anchor)
85
86 def problem(kind, message):
87 return Problem(kind, consumer.stage, message, producer.stage, anchor)
88
89 if actual is None:
90 problems.append(problem("missing-output", f"consumer expects {expected.describe()}"))
91 continue
92 if actual.structure != expected.structure or actual.block != expected.block:
93 problems.append(problem("structure-mismatch", f"{actual.describe()} cannot match {expected.describe()}"))
94 continue
95 if tuple(v.address for v in actual.varyings) != tuple(v.address for v in expected.varyings):
96 problems.append(problem("location-mismatch",
97 f"{actual.describe()} starts or places its members differently from "
98 f"{expected.describe()}"))
99 continue
100 if tuple(v.per_primitive for v in actual.varyings) != tuple(v.per_primitive for v in expected.varyings):
101 problems.append(problem("per-primitive-mismatch",
102 f"producer declares {actual.describe()}, consumer expects {expected.describe()}"))
103 continue
104 if tuple(v.type for v in actual.varyings) != tuple(v.type for v in expected.varyings):
105 if wider_vector_compatible(actual, expected, maintenance4):
106 continue
107 hint = (" (a wider output vector requires maintenance4)"
108 if wider_vector_compatible(actual, expected, True) else "")
109 problems.append(problem("type-mismatch",
110 f"producer declares {actual.describe()}, consumer expects {expected.describe()}"
111 f"{hint}"))
112 return problems
113
114
115def stage_chain(refs):
116 stages = tuple(stage for stage in STAGES if stage in refs)
117 if stages not in CHAINS:
118 raise ValueError("expected vs+ps, vs+gs, vs+gs+ps, or ms+ps")
119 return stages
120
121
122def load_pipeline_manifest(path: Path, shader_dir: Path):
123 try:
124 with path.open(encoding="utf-8") as source:
125 doc = json.load(source)
126 except (OSError, ValueError) as exc:
127 raise ValueError(f"{path}: {exc}") from exc
128 if (not isinstance(doc, dict) or set(doc) - {"pipelines", "version"}
129 or type(doc.get("version", 1)) is not int or doc.get("version", 1) != 1):
130 raise ValueError("expected a version 1 object with a pipelines list")
131 if not isinstance(doc.get("pipelines"), list) or not doc["pipelines"]:
132 raise ValueError("pipelines must be a nonempty list")
133 names = set()
134 pipelines = []
135 for number, row in enumerate(doc["pipelines"], 1):
136 try:
137 if not isinstance(row, dict) or set(row) - {"name", *STAGES}:
138 raise ValueError("unexpected pipeline field")
139 name = row.get("name")
140 if not isinstance(name, str) or not name.strip() or any(ord(ch) < 32 for ch in name):
141 raise ValueError("expected one printable, nonempty pipeline name")
142 if name in names:
143 raise ValueError(f"duplicate pipeline name {name!r}")
144 stages = stage_chain(row)
145 modules = tuple(manifest_module(row[stage], shader_dir, stage) for stage in stages)
146 names.add(name)
147 pipelines.append(Pipeline(name, modules))
148 except ValueError as exc:
149 raise ValueError(f"pipelines[{number - 1}]: {exc}") from exc
150 return pipelines
151
152
153def manifest_module(reference, shader_dir, stage):
154 entry = "main"
155 if isinstance(reference, dict):
156 if set(reference) - {"shader", "entry"}:
157 raise ValueError(f"{stage}: unexpected shader reference field")
158 entry, reference = reference.get("entry", entry), reference.get("shader")
159 if not isinstance(reference, str) or not STEM.fullmatch(reference):
160 raise ValueError(f"{stage}: expected a shader name without directories")
161 if not isinstance(entry, str) or not entry or "\x00" in entry:
162 raise ValueError(f"{stage}: expected a nonempty entry-point name")
163 return ModulePath(shader_dir / (reference + ".spv"), stage, entry)
164
165
166class InterfaceCache:
167 def __init__(self):
168 self.modules = {}
169
170 def load(self, module):
171 if module not in self.modules:
172 try:
173 self.modules[module] = reflect_module(module.path.read_bytes(), module.stage, module.entry)
174 except (OSError, InterfaceError) as exc:
175 self.modules[module] = InterfaceError(f"{module.path}: {exc}")
176 result = self.modules[module]
177 if isinstance(result, InterfaceError):
178 raise result
179 return result
180
181
182def check_pipeline(pipeline, cache, maintenance4=False):
183 interfaces = {}
184 problems = []
185 for module in pipeline.modules:
186 try:
187 interfaces[module.stage] = cache.load(module)
188 except (OSError, InterfaceError) as exc:
189 problems.append(Problem("module-error", module.stage, str(exc)))
190 links = 0
191 invalid = bool(problems)
192 for producer, consumer in zip(pipeline.modules, pipeline.modules[1:]):
193 if producer.stage in interfaces and consumer.stage in interfaces:
194 links += 1
195 problems.extend(compare_stages(interfaces[producer.stage], interfaces[consumer.stage], maintenance4))
196 status = "invalid" if invalid else ("incompatible" if problems else "compatible")
197 return PipelineResult(pipeline.name, status, links, problems)
198
199
200def write_report(path: Path, doc):
201 path = path.absolute()
202 temporary = None
203 try:
204 with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", delete=False,
205 dir=path.parent, prefix=".shader-link-", suffix=".tmp") as target:
206 temporary = Path(target.name)
207 json.dump(doc, target, indent=2, ensure_ascii=False)
208 target.write("\n")
209 os.chmod(temporary, published_mode(path))
210 os.replace(temporary, path)
211 finally:
212 if temporary is not None:
213 temporary.unlink(missing_ok=True)
214
215
216def ensure_report_is_separate(output, inputs):
217 if output is None:
218 return
219 out = output.resolve()
220 for source in dict.fromkeys(inputs):
221 if out == source.resolve() or (out.exists() and source.exists() and out.samefile(source)):
222 raise ValueError(f"report would overwrite an input file: {source}")
223
224
225def inspect(args):
226 ensure_report_is_separate(args.report, [args.module])
227 interface = reflect_module(args.module.read_bytes(), args.stage, args.entry)
228 doc = {
229 "stage": interface.stage,
230 "entry": interface.entry,
231 "inputs": [declaration_row(item) for item in interface.inputs],
232 "outputs": [declaration_row(item) for item in interface.outputs],
233 }
234 if args.report:
235 write_report(args.report, doc)
236 else:
237 print(json.dumps(doc, indent=2))
238 return 0
239
240
241def declaration_row(declaration):
242 return {
243 "id": declaration.symbol,
244 "structure": declaration.structure,
245 "block": declaration.block,
246 "indexed_by_vertex_or_primitive": declaration.indexed_by_vertex_or_primitive,
247 "varyings": [{**asdict(varying.address), "type": varying.type.describe(),
248 "per_primitive": varying.per_primitive} for varying in declaration.varyings],
249 }
250
251
252def run_checks(args):
253 extra_inputs = []
254 if args.command == "batch":
255 pipelines = load_pipeline_manifest(args.manifest, args.shader_dir)
256 extra_inputs = [args.manifest]
257 else:
258 refs = {stage: getattr(args, stage) for stage in STAGES if getattr(args, stage) is not None}
259 pipelines = [Pipeline("pipeline", tuple(ModulePath(refs[stage], stage, args.entry)
260 for stage in stage_chain(refs)))]
261 ensure_report_is_separate(args.report, [*extra_inputs,
262 *(module.path for pipeline in pipelines for module in pipeline.modules)])
263 cache = InterfaceCache()
264 results = [check_pipeline(pipeline, cache, args.maintenance4) for pipeline in pipelines]
265 summary = {state: sum(result.status == state for result in results)
266 for state in ("compatible", "incompatible", "invalid")}
267 if args.report:
268 write_report(args.report, {"version": 1, "maintenance4": args.maintenance4, "summary": summary,
269 "pipelines": [asdict(result) for result in results]})
270 for result in results:
271 if args.quiet and not result.problems:
272 continue
273 print(f"{result.name}: {result.status} ({result.links_checked} links checked)")
274 for problem in result.problems:
275 print(f" {problem.display()}")
276 print(", ".join(f"{count} {state}" for state, count in summary.items()))
277 if summary["invalid"]:
278 return 2
279 return int(bool(summary["incompatible"]))
280
281
282def main(argv=None):
283 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
284 commands = parser.add_subparsers(dest="command", required=True)
285 direct = commands.add_parser("check", help="check one graphics pipeline from SPIR-V file paths")
286 for stage in STAGES:
287 direct.add_argument("--" + stage, type=Path, metavar="SPV")
288 direct.add_argument("--entry", default="main", help="entry-point name used by all direct paths")
289 batch = commands.add_parser("batch", help="check a JSON list of pipelines sharing a shader directory")
290 batch.add_argument("manifest", type=Path)
291 batch.add_argument("--shader-dir", type=Path, required=True, help="directory holding the named .spv files")
292 for command in (direct, batch):
293 command.add_argument("--maintenance4", action="store_true",
294 help="allow wider output vectors when the pipeline enables maintenance4")
295 command.add_argument("--quiet", action="store_true", help="display diagnostics and the summary")
296 command.add_argument("--report", type=Path, help="write structured results to JSON")
297 single = commands.add_parser("inspect", help="show the reflected user inputs and outputs of one entry point")
298 single.add_argument("module", type=Path)
299 single.add_argument("--stage", choices=STAGES, help="select a stage when multiple entry points share a name")
300 single.add_argument("--entry", default="main")
301 single.add_argument("--report", type=Path, help="write the reflection to JSON")
302 args = parser.parse_args(argv)
303 try:
304 return inspect(args) if args.command == "inspect" else run_checks(args)
305 except (OSError, ValueError) as exc:
306 print(f"shader_link_check: error: {exc}", file=sys.stderr)
307 return 2
308
309
310if __name__ == "__main__":
311 if hasattr(sys.stdout, "reconfigure"):
312 sys.stdout.reconfigure(errors="replace")
313 sys.exit(main())
diff --git a/tools/spirv_gs_to_compute.py b/tools/spirv_gs_to_compute.py
index 3caaa15a7..afb9edba6 100644
--- a/tools/spirv_gs_to_compute.py
+++ b/tools/spirv_gs_to_compute.py
@@ -297,15 +297,21 @@ def rewrite(text):
297 return "\n".join(out) + "\n", public 297 return "\n".join(out) + "\n", public
298 298
299 299
300USAGE = "\n".join(__doc__.strip().splitlines()[-2:])
301
302
300def main(argv): 303def main(argv):
301 args = argv[1:] 304 args = argv[1:]
305 if args and args[0] in ("-h", "--help"):
306 print(USAGE)
307 return 0
302 lay_path = None 308 lay_path = None
303 if "--layout" in args: 309 if "--layout" in args:
304 i = args.index("--layout") 310 i = args.index("--layout")
305 lay_path = args[i + 1] 311 lay_path = args[i + 1]
306 del args[i:i + 2] 312 del args[i:i + 2]
307 if len(args) != 2: 313 if len(args) != 2:
308 print("usage: spirv_gs_to_compute.py in.spv out.spv [--layout out.json]", file=sys.stderr) 314 print(USAGE, file=sys.stderr)
309 return 2 315 return 2
310 dis = os.environ.get("SPIRV_DIS", "spirv-dis") 316 dis = os.environ.get("SPIRV_DIS", "spirv-dis")
311 asm = os.environ.get("SPIRV_AS", "spirv-as") 317 asm = os.environ.get("SPIRV_AS", "spirv-as")
diff --git a/tools/spirv_interface.py b/tools/spirv_interface.py
new file mode 100644
index 000000000..a9ecfa397
--- /dev/null
+++ b/tools/spirv_interface.py
@@ -0,0 +1,522 @@
1"""Reflect the user-defined graphics interfaces in a binary SPIR-V module.
2
3This reader is deliberately limited to declarations used for Vulkan stage linking. It does not
4validate shader instructions, device features, or resource bindings. IDs and debug names are local
5to each module; the result uses normalized types and Location/Component decorations instead.
6"""
7from __future__ import annotations
8
9from array import array
10from collections import defaultdict
11from dataclasses import dataclass
12import struct
13
14
15class InterfaceError(ValueError):
16 """The module's requested interface could not be reflected."""
17
18
19SPIRV_MAGIC = 0x07230203
20SPIRV_MAGIC_SWAPPED = 0x03022307
21
22# SPIR-V core grammar. The NV/EXT spelling of PerPrimitive uses the same enumerant.
23OP_ENTRY_POINT = 15
24OP_TYPE_INT = 21
25OP_TYPE_FLOAT = 22
26OP_TYPE_VECTOR = 23
27OP_TYPE_MATRIX = 24
28OP_TYPE_ARRAY = 28
29OP_TYPE_STRUCT = 30
30OP_TYPE_POINTER = 32
31OP_CONSTANT = 43
32OP_VARIABLE = 59
33OP_DECORATE = 71
34OP_MEMBER_DECORATE = 72
35OP_DECORATION_GROUP = 73
36OP_GROUP_DECORATE = 74
37OP_GROUP_MEMBER_DECORATE = 75
38
39TYPE_OPS = {OP_TYPE_INT, OP_TYPE_FLOAT, OP_TYPE_VECTOR, OP_TYPE_MATRIX,
40 OP_TYPE_ARRAY, OP_TYPE_STRUCT, OP_TYPE_POINTER}
41DECLARATION_OPS = TYPE_OPS | {OP_ENTRY_POINT, OP_CONSTANT, OP_VARIABLE, OP_DECORATE,
42 OP_MEMBER_DECORATE, OP_DECORATION_GROUP, OP_GROUP_DECORATE,
43 OP_GROUP_MEMBER_DECORATE}
44TYPE_OPERANDS = {OP_TYPE_INT: 3, OP_TYPE_FLOAT: 2, OP_TYPE_VECTOR: 3, OP_TYPE_MATRIX: 3,
45 OP_TYPE_ARRAY: 3, OP_TYPE_POINTER: 3}
46EXECUTION_STAGES = {0: "vs", 3: "gs", 4: "ps", 5365: "ms"}
47STORAGE_INPUT = 1
48STORAGE_OUTPUT = 3
49DEC_BLOCK = 2
50DEC_BUILTIN = 11
51DEC_PATCH = 15
52DEC_LOCATION = 30
53DEC_COMPONENT = 31
54DEC_INDEX = 32
55DEC_PASSTHROUGH_NV = 5250
56DEC_PER_PRIMITIVE = 5271
57DEC_PER_VERTEX = 5285
58DECORATION_NAMES = {DEC_BLOCK: "Block", DEC_BUILTIN: "BuiltIn", DEC_PATCH: "Patch",
59 DEC_LOCATION: "Location", DEC_COMPONENT: "Component", DEC_INDEX: "Index",
60 DEC_PASSTHROUGH_NV: "PassthroughNV", DEC_PER_PRIMITIVE: "PerPrimitiveEXT",
61 DEC_PER_VERTEX: "PerVertexKHR"}
62VALUE_DECORATIONS = {DEC_BUILTIN, DEC_LOCATION, DEC_COMPONENT, DEC_INDEX}
63
64# Bound expansion of arrays from malformed modules. This is far beyond the varying space of the
65# graphics stages on current Vulkan drivers. Type and layout recursion has a separate depth limit.
66MAX_EXPANDED_LOCATIONS = 16384
67MAX_TYPE_DEPTH = 64
68
69
70@dataclass(frozen=True)
71class NumericType:
72 kind: str
73 width: int
74 components: int = 1
75
76 def describe(self):
77 scalar = f"{self.kind}{self.width}"
78 return scalar if self.components == 1 else f"vec{self.components}<{scalar}>"
79
80 def location_masks(self, component):
81 slots = self.components * (self.width // 32 if self.width >= 32 else 1)
82 if self.width == 64 and component % 2:
83 raise InterfaceError("a 64-bit varying starts on an odd Component")
84 if self.width != 64 and component + slots > 4:
85 raise InterfaceError("a 16-bit or 32-bit varying extends beyond its Location")
86 if self.width == 64 and slots > 4 and component:
87 raise InterfaceError("a 64-bit vector spanning two locations needs Component 0")
88 mask = ((1 << slots) - 1) << component
89 if mask <= 0xf:
90 return (mask,)
91 return (mask & 0xf, mask >> 4)
92
93
94@dataclass(frozen=True)
95class AggregateType:
96 kind: str
97 items: tuple[NumericType | "AggregateType", ...]
98 count: int = 1
99
100 def describe(self):
101 if self.kind == "struct":
102 return "struct{" + ", ".join(item.describe() for item in self.items) + "}"
103 return f"{self.kind}[{self.count}]<{self.items[0].describe()}>"
104
105 def location_masks(self, component):
106 if self.kind == "struct":
107 if component:
108 raise InterfaceError("a structure cannot start at a nonzero Component")
109 masks = []
110 for member in self.items:
111 member_masks = member.location_masks(0)
112 if len(masks) + len(member_masks) > MAX_EXPANDED_LOCATIONS:
113 raise InterfaceError("structure uses too many interface locations to inspect")
114 masks.extend(member_masks)
115 return tuple(masks)
116 element = self.items[0].location_masks(component)
117 if len(element) * self.count > MAX_EXPANDED_LOCATIONS:
118 raise InterfaceError("aggregate uses too many interface locations to inspect")
119 return element * self.count
120
121
122@dataclass(frozen=True, order=True)
123class Address:
124 location: int
125 component: int = 0
126 index: int = 0
127
128 def describe(self):
129 suffix = f", index {self.index}" if self.index else ""
130 return f"location {self.location}, component {self.component}{suffix}"
131
132
133@dataclass(frozen=True)
134class Varying:
135 address: Address
136 type: NumericType | AggregateType
137 per_primitive: bool = False
138
139 def occupied(self):
140 for offset, mask in enumerate(self.type.location_masks(self.address.component)):
141 for component in range(4):
142 if mask & (1 << component):
143 yield Address(self.address.location + offset, component, self.address.index)
144
145 def describe(self):
146 mode = " per-primitive" if self.per_primitive else ""
147 return f"{self.type.describe()}{mode} at {self.address.describe()}"
148
149
150@dataclass(frozen=True)
151class Declaration:
152 """One standalone varying or an entire structure. Preserve member order when linking."""
153
154 varyings: tuple[Varying, ...]
155 symbol: int
156 structure: bool = False
157 block: bool = False
158 indexed_by_vertex_or_primitive: bool = False
159
160 def describe(self):
161 parts = ", ".join(varying.describe() for varying in self.varyings)
162 if self.structure:
163 kind = "block" if self.block else "struct"
164 return f"{kind} %{self.symbol} ({parts})"
165 return f"%{self.symbol} ({parts})"
166
167
168@dataclass(frozen=True)
169class StageInterface:
170 stage: str
171 entry: str
172 inputs: tuple[Declaration, ...]
173 outputs: tuple[Declaration, ...]
174
175
176@dataclass(frozen=True)
177class EntryPoint:
178 model: int
179 name: str
180 interface_ids: tuple[int, ...]
181
182
183def parse_words(data):
184 if len(data) < 20 or len(data) % 4:
185 raise InterfaceError("SPIR-V must contain a five-word header and complete 32-bit words")
186 words = array("I")
187 words.frombytes(data)
188 if words[0] == SPIRV_MAGIC_SWAPPED:
189 words.byteswap()
190 if words[0] != SPIRV_MAGIC:
191 raise InterfaceError("invalid SPIR-V magic")
192 if not 0x00010000 <= words[1] <= 0x00010600 or words[1] & 0xff:
193 raise InterfaceError(f"unsupported SPIR-V version word 0x{words[1]:08x}")
194 if not words[3] or words[4]:
195 raise InterfaceError("invalid SPIR-V ID bound or reserved header word")
196 return words
197
198
199def instructions(words):
200 start = 5
201 while start < len(words):
202 first = words[start]
203 length, opcode = first >> 16, first & 0xffff
204 end = start + length
205 if not length or end > len(words):
206 raise InterfaceError(f"invalid instruction length at word {start}")
207 if opcode in DECLARATION_OPS:
208 yield opcode, tuple(words[start + 1:end]), start
209 start = end
210
211
212def decode_literal_string(words):
213 for i, word in enumerate(words):
214 if b"\x00" in struct.pack("<I", word):
215 raw = struct.pack(f"<{i + 1}I", *words[:i + 1])
216 name, _, padding = raw.partition(b"\x00")
217 if any(padding):
218 raise InterfaceError("nonzero padding in OpEntryPoint name")
219 try:
220 return name.decode("utf-8"), i + 1
221 except UnicodeDecodeError as exc:
222 raise InterfaceError("OpEntryPoint name is not UTF-8") from exc
223 raise InterfaceError("unterminated OpEntryPoint name")
224
225
226class Module:
227 def __init__(self, data):
228 words = parse_words(data)
229 self.bound = words[3]
230 self.types = {}
231 self.constants = {}
232 self.variables = {}
233 self.entry_points = []
234 self.decorations = defaultdict(dict)
235 self.member_decorations = defaultdict(dict)
236 self.groups = set()
237 self.group_uses = []
238 self.definition_ids = set()
239 self.shape_cache = {}
240 for opcode, operands, at in instructions(words):
241 self.read_instruction(opcode, operands, at)
242 self.apply_decoration_groups()
243
244 def require_id(self, identifier):
245 if not 0 < identifier < self.bound:
246 raise InterfaceError(f"ID %{identifier} is outside the SPIR-V bound")
247
248 def define(self, identifier):
249 self.require_id(identifier)
250 if identifier in self.definition_ids:
251 raise InterfaceError(f"duplicate definition of ID %{identifier}")
252 self.definition_ids.add(identifier)
253
254 @staticmethod
255 def require_operands(operands, at, minimum, maximum=None):
256 if len(operands) < minimum or (maximum is not None and len(operands) > maximum):
257 raise InterfaceError(f"invalid operands at word {at}")
258
259 def read_instruction(self, opcode, operands, at):
260 if opcode in TYPE_OPS:
261 exact = TYPE_OPERANDS.get(opcode)
262 self.require_operands(operands, at, exact or 1, exact)
263 identifier, *args = operands
264 self.define(identifier)
265 self.types[identifier] = (opcode, tuple(args))
266 elif opcode == OP_CONSTANT:
267 self.require_operands(operands, at, 3)
268 type_id, identifier, *literal = operands
269 self.require_id(type_id)
270 self.define(identifier)
271 self.constants[identifier] = (type_id, tuple(literal))
272 elif opcode == OP_VARIABLE:
273 self.require_operands(operands, at, 3, 4)
274 pointer, identifier, storage = operands[:3]
275 self.require_id(pointer)
276 self.define(identifier)
277 self.variables[identifier] = (pointer, storage)
278 elif opcode == OP_ENTRY_POINT:
279 self.require_operands(operands, at, 3)
280 model, function, *rest = operands
281 self.require_id(function)
282 name, words_used = decode_literal_string(rest)
283 ids = tuple(rest[words_used:])
284 for identifier in ids:
285 self.require_id(identifier)
286 if len(set(ids)) != len(ids):
287 raise InterfaceError(f"duplicate entry-point interface ID in {name!r}")
288 self.entry_points.append(EntryPoint(model, name, ids))
289 elif opcode in (OP_DECORATE, OP_MEMBER_DECORATE):
290 split = 1 if opcode == OP_DECORATE else 2
291 self.require_operands(operands, at, split + 1)
292 identifier = operands[0]
293 self.require_id(identifier)
294 decoration, *extra = operands[split:]
295 if decoration not in DECORATION_NAMES:
296 return
297 expected = int(decoration in VALUE_DECORATIONS)
298 if len(extra) != expected:
299 raise InterfaceError(f"invalid {DECORATION_NAMES[decoration]} decoration at word {at}")
300 target = (self.decorations[identifier] if split == 1
301 else self.member_decorations[(identifier, operands[1])])
302 self.add_decoration(target, decoration, extra[0] if extra else True)
303 elif opcode == OP_DECORATION_GROUP:
304 self.require_operands(operands, at, 1, 1)
305 self.define(operands[0])
306 self.groups.add(operands[0])
307 else:
308 self.require_operands(operands, at, 2 if opcode == OP_GROUP_DECORATE else 3)
309 if opcode == OP_GROUP_MEMBER_DECORATE and len(operands) % 2 != 1:
310 raise InterfaceError(f"unpaired group member decoration at word {at}")
311 self.group_uses.append((opcode, operands))
312
313 @staticmethod
314 def add_decoration(target, decoration, value):
315 if decoration in target and target[decoration] != value:
316 raise InterfaceError(f"conflicting {DECORATION_NAMES[decoration]} decorations")
317 target[decoration] = value
318
319 def apply_decoration_groups(self):
320 for opcode, operands in self.group_uses:
321 group, *targets = operands
322 if group not in self.groups:
323 raise InterfaceError(f"undefined decoration group %{group}")
324 source = self.decorations.get(group, {})
325 if opcode == OP_GROUP_DECORATE:
326 destinations = ((identifier, None) for identifier in targets)
327 else:
328 destinations = zip(targets[::2], targets[1::2])
329 for identifier, member in destinations:
330 self.require_id(identifier)
331 if identifier in self.groups:
332 raise InterfaceError("decoration groups cannot decorate each other")
333 target = (self.decorations[identifier] if member is None
334 else self.member_decorations[(identifier, member)])
335 for decoration, value in source.items():
336 self.add_decoration(target, decoration, value)
337
338 def type_declaration(self, identifier):
339 try:
340 return self.types[identifier]
341 except KeyError:
342 raise InterfaceError(f"missing or unsupported varying type %{identifier}") from None
343
344 def array_count(self, identifier):
345 try:
346 type_id, literal = self.constants[identifier]
347 except KeyError:
348 raise InterfaceError(f"varying array length %{identifier} is not a literal OpConstant") from None
349 opcode, args = self.type_declaration(type_id)
350 if opcode != OP_TYPE_INT or args[0] not in (16, 32, 64) or args[1] not in (0, 1):
351 raise InterfaceError("varying array length must be an integer")
352 width, signed = args
353 if len(literal) != (width + 31) // 32:
354 raise InterfaceError("invalid literal width for varying array length")
355 count = sum(word << (32 * i) for i, word in enumerate(literal)) & ((1 << width) - 1)
356 if not count or (signed and count >> (width - 1)):
357 raise InterfaceError("varying array length must be positive")
358 return count
359
360 def shape(self, identifier, path=()):
361 if identifier in self.shape_cache:
362 return self.shape_cache[identifier]
363 if identifier in path or len(path) == MAX_TYPE_DEPTH:
364 raise InterfaceError("cyclic or excessively deep varying type")
365 opcode, args = self.type_declaration(identifier)
366 nested = (*path, identifier)
367 if opcode in (OP_TYPE_INT, OP_TYPE_FLOAT):
368 width = args[0]
369 if width not in (16, 32, 64) or (opcode == OP_TYPE_INT and args[1] not in (0, 1)):
370 raise InterfaceError("unsupported numeric type in graphics interface")
371 kind = "f" if opcode == OP_TYPE_FLOAT else ("i" if args[1] else "u")
372 result = NumericType(kind, width)
373 elif opcode == OP_TYPE_VECTOR:
374 element = self.shape(args[0], nested)
375 if not isinstance(element, NumericType) or element.components != 1 or not 2 <= args[1] <= 4:
376 raise InterfaceError("invalid varying vector type")
377 result = NumericType(element.kind, element.width, args[1])
378 elif opcode in (OP_TYPE_ARRAY, OP_TYPE_MATRIX):
379 element = self.shape(args[0], nested)
380 if opcode == OP_TYPE_ARRAY:
381 result = AggregateType("array", (element,), self.array_count(args[1]))
382 else:
383 if (not isinstance(element, NumericType) or element.kind != "f" or element.components < 2
384 or not 2 <= args[1] <= 4):
385 raise InterfaceError("invalid varying matrix type")
386 result = AggregateType("matrix", (element,), args[1])
387 elif opcode == OP_TYPE_STRUCT:
388 if not args:
389 raise InterfaceError("empty structure in graphics interface")
390 for i in range(len(args)):
391 if self.member_decorations.get((identifier, i)):
392 raise InterfaceError("decorated nested interface structure members are unsupported")
393 result = AggregateType("struct", tuple(self.shape(member, nested) for member in args))
394 else:
395 raise InterfaceError("unsupported pointer in graphics interface")
396 self.shape_cache[identifier] = result
397 return result
398
399 def pick_entry(self, stage, entry):
400 named = [candidate for candidate in self.entry_points if candidate.name == entry]
401 matches = [candidate for candidate in named if stage is None or EXECUTION_STAGES.get(candidate.model) == stage]
402 if not matches:
403 found = ", ".join(EXECUTION_STAGES.get(candidate.model, str(candidate.model)) for candidate in named)
404 if found:
405 raise InterfaceError(f"entry point {entry!r} is {found}, expected {stage}")
406 raise InterfaceError(f"entry point {entry!r} not found")
407 if len(matches) > 1:
408 raise InterfaceError(f"entry point {entry!r} is ambiguous without a stage")
409 selected = matches[0]
410 if selected.model not in EXECUTION_STAGES:
411 raise InterfaceError(f"unsupported execution model {selected.model} for entry point {entry!r}")
412 return selected
413
414 def varying_type(self, pointer, storage, stage, decorations):
415 opcode, args = self.type_declaration(pointer)
416 if opcode != OP_TYPE_POINTER or args[0] != storage:
417 raise InterfaceError("variable pointer type does not match its storage class")
418 pointee = args[1]
419 per_vertex = DEC_PER_VERTEX in decorations
420 if per_vertex and (stage, storage) != ("ps", STORAGE_INPUT):
421 raise InterfaceError("PerVertexKHR is only supported on fragment inputs")
422 primitive_array = (stage, storage) in (("gs", STORAGE_INPUT), ("ms", STORAGE_OUTPUT))
423 indexed = per_vertex or primitive_array
424 if indexed:
425 # The array indexes vertices or primitives. It is outside the linked payload shape
426 # and does not consume locations. Its length does not need to match the other stage.
427 opcode, args = self.type_declaration(pointee)
428 if opcode != OP_TYPE_ARRAY:
429 raise InterfaceError(f"{stage} requires an outer per-vertex or per-primitive array")
430 pointee = args[0]
431 return pointee, indexed
432
433 @staticmethod
434 def address(decorations, location=None):
435 location = decorations.get(DEC_LOCATION, location)
436 component = decorations.get(DEC_COMPONENT, 0)
437 index = decorations.get(DEC_INDEX, 0)
438 if location is None:
439 raise InterfaceError("user varying is missing a Location decoration")
440 if component > 3 or index > 1:
441 raise InterfaceError("invalid Component or Index decoration")
442 return Address(location, component, index)
443
444 @staticmethod
445 def check_modes(decorations):
446 if DEC_PASSTHROUGH_NV in decorations:
447 raise InterfaceError("geometry passthrough interfaces require different matching rules")
448 if DEC_PATCH in decorations:
449 raise InterfaceError("tessellation patch interfaces are unsupported")
450
451 def declaration(self, symbol, pointer, storage, stage):
452 decorations = self.decorations.get(symbol, {})
453 self.check_modes(decorations)
454 if DEC_BUILTIN in decorations:
455 return None
456 type_id, indexed = self.varying_type(pointer, storage, stage, decorations)
457 opcode, args = self.type_declaration(type_id)
458 per_primitive = DEC_PER_PRIMITIVE in decorations
459 if opcode != OP_TYPE_STRUCT:
460 varying = Varying(self.address(decorations), self.shape(type_id), per_primitive)
461 return Declaration((varying,), symbol, indexed_by_vertex_or_primitive=indexed)
462
463 member_decs = [self.member_decorations.get((type_id, i), {}) for i in range(len(args))]
464 if member_decs and all(DEC_BUILTIN in member for member in member_decs):
465 return None
466 if any(DEC_BUILTIN in member for member in member_decs):
467 raise InterfaceError("mixed built-in and user-defined structure members")
468 is_block = DEC_BLOCK in self.decorations.get(type_id, {})
469 base_location = decorations.get(DEC_LOCATION)
470 if base_location is None and not is_block:
471 raise InterfaceError("a non-block structure needs a Location")
472 if DEC_COMPONENT in decorations or DEC_INDEX in decorations:
473 raise InterfaceError("Component or Index on an entire varying structure is unsupported")
474 if base_location is not None and any(DEC_LOCATION in member for member in member_decs):
475 raise InterfaceError("both the structure and its members declare Locations")
476 if not args:
477 raise InterfaceError("empty structure in graphics interface")
478 members = []
479 next_location = base_location
480 for child, member in zip(args, member_decs):
481 self.check_modes(member)
482 address = self.address(member, next_location)
483 shape = self.shape(child, (type_id,))
484 members.append(Varying(address, shape, per_primitive or DEC_PER_PRIMITIVE in member))
485 if base_location is not None:
486 next_location += len(shape.location_masks(address.component))
487 return Declaration(tuple(members), symbol, structure=True, block=is_block,
488 indexed_by_vertex_or_primitive=indexed)
489
490 def reflect(self, stage=None, entry="main"):
491 selected = self.pick_entry(stage, entry)
492 stage = EXECUTION_STAGES[selected.model]
493 directions = {STORAGE_INPUT: [], STORAGE_OUTPUT: []}
494 slots = {STORAGE_INPUT: {}, STORAGE_OUTPUT: {}}
495 for symbol in selected.interface_ids:
496 if symbol not in self.variables:
497 raise InterfaceError(f"entry point references missing variable %{symbol}")
498 pointer, storage = self.variables[symbol]
499 if storage not in directions:
500 continue
501 try:
502 declaration = self.declaration(symbol, pointer, storage, stage)
503 if declaration is None:
504 continue
505 for varying in declaration.varyings:
506 for address in varying.occupied():
507 before = slots[storage].get(address)
508 if before is not None:
509 raise InterfaceError(
510 f"overlap with %{before} at {address.describe()}")
511 slots[storage][address] = symbol
512 except InterfaceError as exc:
513 direction = "input" if storage == STORAGE_INPUT else "output"
514 raise InterfaceError(f"{stage} {direction} variable %{symbol}: {exc}") from exc
515 directions[storage].append(declaration)
516 key = lambda declaration: declaration.varyings[0].address
517 return StageInterface(stage, entry, tuple(sorted(directions[STORAGE_INPUT], key=key)),
518 tuple(sorted(directions[STORAGE_OUTPUT], key=key)))
519
520
521def reflect_module(data, stage=None, entry="main"):
522 return Module(data).reflect(stage, entry)
diff --git a/tools/spirv_metal_set0.py b/tools/spirv_metal_set0.py
index 767e93ff9..cbd2792f5 100644
--- a/tools/spirv_metal_set0.py
+++ b/tools/spirv_metal_set0.py
@@ -107,6 +107,11 @@ def rewrite(text, counts):
107 107
108 108
109def main(argv): 109def main(argv):
110 rest = argv[1:]
111 if rest and rest[0] in ("-h", "--help"):
112 for line in __doc__.strip().splitlines()[-2:]:
113 print(line)
114 return 0
110 counts = capacities() 115 counts = capacities()
111 if argv[1:] == ["--print-layout"]: 116 if argv[1:] == ["--print-layout"]:
112 for b, (c, i) in enumerate(zip(counts, metal_ids(counts))): 117 for b, (c, i) in enumerate(zip(counts, metal_ids(counts))):
diff --git a/tools/story_index.py b/tools/story_index.py
index 731185a02..7a7c7a837 100644
--- a/tools/story_index.py
+++ b/tools/story_index.py
@@ -303,7 +303,7 @@ def write_output(path, rows, summary):
303 json.dump({"summary": summary, "files": rows}, f, indent=1) 303 json.dump({"summary": summary, "files": rows}, f, indent=1)
304 else: 304 else:
305 with open(staged, "w", encoding="utf-8", newline="") as f: 305 with open(staged, "w", encoding="utf-8", newline="") as f:
306 w = csv.writer(f) 306 w = csv.writer(f, lineterminator="\n")
307 w.writerow(COLUMNS) 307 w.writerow(COLUMNS)
308 for r in rows: 308 for r in rows:
309 w.writerow([f"0x{r['offset']:x}" if i == 0 else ("" if r[c] is None else r[c]) 309 w.writerow([f"0x{r['offset']:x}" if i == 0 else ("" if r[c] is None else r[c])
diff --git a/tools/tex_export.py b/tools/tex_export.py
index df5157b27..f7de7dd28 100644
--- a/tools/tex_export.py
+++ b/tools/tex_export.py
@@ -187,12 +187,33 @@ def main():
187 ap.add_argument("--limit", type=positive_int, help="export only the first N textures (N >= 1)") 187 ap.add_argument("--limit", type=positive_int, help="export only the first N textures (N >= 1)")
188 ap.add_argument("--png", action="store_true", help="also write a PNG beside each DDS dds_png.py can decode") 188 ap.add_argument("--png", action="store_true", help="also write a PNG beside each DDS dds_png.py can decode")
189 a = ap.parse_args() 189 a = ap.parse_args()
190 with open(a.index, encoding="utf-8") as f: 190 try:
191 texs = json.load(f) 191 with open(a.index, encoding="utf-8") as f:
192 texs.sort(key=lambda t: (t["archive"], t["gpu"])) 192 texs = json.load(f)
193 except (OSError, ValueError) as e:
194 print(f"ERROR: cannot read {a.index}: {e}", file=sys.stderr)
195 return 2
196 if not isinstance(texs, list):
197 print(f"ERROR: cannot read {a.index}: expected a texture list, got {type(texs).__name__}", file=sys.stderr)
198 return 2
199 try:
200 texs.sort(key=lambda t: (t["archive"], t["gpu"]))
201 except KeyError as e:
202 print(f"ERROR: cannot read {a.index}: row has no {e.args[0]!r}", file=sys.stderr)
203 return 2
204 except TypeError as e:
205 print(f"ERROR: cannot read {a.index}: {e}", file=sys.stderr)
206 return 2
193 if a.limit is not None: # 0 used to read as "no limit", and a negative N dropped the last N 207 if a.limit is not None: # 0 used to read as "no limit", and a negative N dropped the last N
194 texs = texs[: a.limit] 208 texs = texs[: a.limit]
195 os.makedirs(a.out, exist_ok=True) 209 if os.path.exists(a.out) and not os.path.isdir(a.out):
210 print(f"ERROR: {a.out} is a file, not a folder", file=sys.stderr)
211 return 2
212 try:
213 os.makedirs(a.out, exist_ok=True)
214 except OSError as e: # a report path under an existing file, or a dangling symlink
215 print(f"ERROR: cannot create {a.out}: {e.strerror or e}", file=sys.stderr)
216 return 2
196 res, cache, pngs = Counter(), {}, Counter() 217 res, cache, pngs = Counter(), {}, Counter()
197 for i, t in enumerate(texs, 1): 218 for i, t in enumerate(texs, 1):
198 try: 219 try:
diff --git a/tools/text_tables.py b/tools/text_tables.py
index deee48822..60c4e9dce 100644
--- a/tools/text_tables.py
+++ b/tools/text_tables.py
@@ -40,10 +40,12 @@ import os
40import re 40import re
41import struct 41import struct
42import sys 42import sys
43import tempfile
43 44
44ROOT = os.path.dirname(os.path.abspath(__file__)) 45ROOT = os.path.dirname(os.path.abspath(__file__))
45if ROOT not in sys.path: 46if ROOT not in sys.path:
46 sys.path.insert(0, ROOT) 47 sys.path.insert(0, ROOT)
48from file_mode import published_mode # noqa: E402
47from hashdict import joaat # noqa: E402 49from hashdict import joaat # noqa: E402
48 50
49RESOURCE_MAGIC = b"0DRP" 51RESOURCE_MAGIC = b"0DRP"
@@ -270,7 +272,7 @@ def _clean(s: str) -> str:
270 272
271def _write_csv(path, fields, rows): 273def _write_csv(path, fields, rows):
272 with open(path, "w", encoding="utf-8", newline="") as fh: 274 with open(path, "w", encoding="utf-8", newline="") as fh:
273 w = csv.DictWriter(fh, fieldnames=fields) 275 w = csv.DictWriter(fh, fieldnames=fields, lineterminator="\n")
274 w.writeheader() 276 w.writeheader()
275 n = 0 277 n = 0
276 for row in rows: 278 for row in rows:
@@ -288,6 +290,12 @@ def main(argv=None) -> int:
288 ap.add_argument("--strings", help="CSV: every string (source, offset, lang, hash, label, text)") 290 ap.add_argument("--strings", help="CSV: every string (source, offset, lang, hash, label, text)")
289 a = ap.parse_args(argv) 291 a = ap.parse_args(argv)
290 outs = [p for p in (a.dialogue, a.tables, a.strings) if p] 292 outs = [p for p in (a.dialogue, a.tables, a.strings) if p]
293 seen = set()
294 for p in outs:
295 key = os.path.normcase(os.path.realpath(p))
296 if key in seen:
297 ap.error("outputs must be distinct files")
298 seen.add(key)
291 for path in a.sources + a.labels: 299 for path in a.sources + a.labels:
292 if not os.path.exists(path): 300 if not os.path.exists(path):
293 print(f"text_tables: error: {path}: no such file or directory", file=sys.stderr) 301 print(f"text_tables: error: {path}: no such file or directory", file=sys.stderr)
@@ -308,24 +316,73 @@ def main(argv=None) -> int:
308 316
309 lines = sum(len(v) for v in scan.pairs.values()) 317 lines = sum(len(v) for v in scan.pairs.values())
310 langs = scan.languages() 318 langs = scan.languages()
319 jobs = []
320 if a.dialogue:
321 fields = ["wave", "key", "label", "speaker"] + [f"text_{x}" for x in langs]
322 jobs.append((a.dialogue, fields, scan.dialogue_rows()))
323 if a.tables:
324 jobs.append((a.tables, ["source", "offset", "lang", "group", "strings", "resolved"],
325 ({"source": s, "offset": o, "lang": lang,
326 "group": table_group(names[h] for h in t if h in names),
327 "strings": len(t), "resolved": sum(h in names for h in t)}
328 for s, o, lang, t in scan.tables)))
329 if a.strings:
330 jobs.append((a.strings, ["source", "offset", "lang", "hash", "label", "text"],
331 ({"source": s, "offset": o, "lang": lang, "hash": f"{h:08x}", "label": names.get(h, ""),
332 "text": _clean(text)}
333 for s, o, lang, t in scan.tables for h, text in t.items())))
334 # Stage every report next to its destination, then swap them all in. A write that fails part-way must
335 # leave the previous reports intact instead of truncating the ones that came before it.
336 staged = []
337 originals = {}
311 try: 338 try:
312 if a.dialogue: 339 for dest, fields, rows in jobs:
313 fields = ["wave", "key", "label", "speaker"] + [f"text_{x}" for x in langs] 340 parent = os.path.dirname(os.path.abspath(dest))
314 _write_csv(a.dialogue, fields, scan.dialogue_rows()) 341 fd, tmp = tempfile.mkstemp(dir=parent, prefix=".text_tables-", suffix=".csv")
315 if a.tables: 342 os.close(fd)
316 _write_csv(a.tables, ["source", "offset", "lang", "group", "strings", "resolved"], 343 staged.append((tmp, dest))
317 ({"source": s, "offset": o, "lang": lang, 344 _write_csv(tmp, fields, rows)
318 "group": table_group(names[h] for h in t if h in names), 345 for _tmp, dest in staged:
319 "strings": len(t), "resolved": sum(h in names for h in t)} 346 if os.path.isdir(dest):
320 for s, o, lang, t in scan.tables)) 347 raise OSError(f"{dest} is a directory")
321 if a.strings: 348 for tmp, dest in staged:
322 _write_csv(a.strings, ["source", "offset", "lang", "hash", "label", "text"], 349 os.chmod(tmp, published_mode(dest))
323 ({"source": s, "offset": o, "lang": lang, "hash": f"{h:08x}", "label": names.get(h, ""), 350 # Move every old report aside before putting any new one in place. On Windows a report held
324 "text": _clean(text)} 351 # open by a reader cannot be renamed; failing here leaves all the originals untouched.
325 for s, o, lang, t in scan.tables for h, text in t.items())) 352 for _tmp, dest in staged:
353 if os.path.lexists(dest):
354 fd, backup = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(dest)),
355 prefix=".text_tables-old-", suffix=".csv")
356 os.close(fd)
357 os.remove(backup)
358 os.replace(dest, backup)
359 originals[dest] = backup
360 else:
361 originals[dest] = None
362 for tmp, dest in staged:
363 os.replace(tmp, dest)
326 except OSError as error: 364 except OSError as error:
365 for dest, backup in originals.items():
366 try:
367 if os.path.lexists(dest):
368 os.remove(dest)
369 if backup is not None:
370 os.replace(backup, dest)
371 except OSError:
372 pass
373 for tmp, _ in staged:
374 try:
375 os.remove(tmp)
376 except OSError:
377 pass
327 print(f"text_tables: error: cannot write: {error}", file=sys.stderr) 378 print(f"text_tables: error: cannot write: {error}", file=sys.stderr)
328 return 2 379 return 2
380 for backup in originals.values():
381 if backup is not None:
382 try:
383 os.remove(backup)
384 except OSError:
385 pass
329 with_text = collections.Counter() 386 with_text = collections.Counter()
330 for row in scan.dialogue_rows(): 387 for row in scan.dialogue_rows():
331 for lang in langs: 388 for lang in langs:
diff --git a/tools/valu_fuzz.py b/tools/valu_fuzz.py
index 8e1a65a44..2b9beeb97 100644
--- a/tools/valu_fuzz.py
+++ b/tools/valu_fuzz.py
@@ -530,8 +530,8 @@ class F16Family(Family):
530 elif n == "v_pack_b32_f16": 530 elif n == "v_pack_b32_f16":
531 sel = op["opsel"] 531 sel = op["opsel"]
532 lo, hi = half(s[0], sel[0]), half(s[1], sel[1]) 532 lo, hi = half(s[0], sel[0]), half(s[1], sel[1])
533 # a signaling NaN half is uncertain (a quiet NaN stays compared): gfx1150 quiets a signaling NaN here (0x7c96 -> 0x7e96); the model moves bits, 533 # a signaling NaN half is uncertain (a quiet NaN stays compared): gfx1150 quiets a signaling NaN here (0x7c96 -> 0x7e96); the model moves
534 # and whether RDNA2 does the same is not known 534 # bits, which is what RDNA2 does under IEEE mode 0 and not under mode 1 (0x7c01 -> 0xfe01 on gfx1036, SHADER-260)
535 if "pack_swapped" in PERTURB: 535 if "pack_swapped" in PERTURB:
536 lo, hi = hi, lo 536 lo, hi = hi, lo
537 R[d] = Reg(lo | (hi << 16), unc(s[0], sel[0]) or is_f16_snan(lo), unc(s[1], sel[1]) or is_f16_snan(hi)) 537 R[d] = Reg(lo | (hi << 16), unc(s[0], sel[0]) or is_f16_snan(lo), unc(s[1], sel[1]) or is_f16_snan(hi))
diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py
index bbac702cf..97e3880cf 100644
--- a/tools/vk_subgroup_info.py
+++ b/tools/vk_subgroup_info.py
@@ -6,17 +6,23 @@ make_game.py uses it to choose between native wave64 translation and --wave64-em
6Vulkan implementation through ctypes (standard library only), so it works before the runtime stage has built anything. 6Vulkan implementation through ctypes (standard library only), so it works before the runtime stage has built anything.
7On macOS it opens MoltenVK directly, using the same LEONIDA_VULKAN_LOADER override as the C++ test tools. 7On macOS it opens MoltenVK directly, using the same LEONIDA_VULKAN_LOADER override as the C++ test tools.
8 8
9Device choice follows the runtime (runtime/shims/d3d12_vulkan_device.cpp): Vulkan 1.3 devices with dynamicRendering, 9Device choice follows the runtime (runtime/shims/d3d12_vulkan_device.cpp, runtime/src/vulkan_device_filter.h):
10synchronization2, timelineSemaphore and separateDepthStencilLayouts and a graphics queue family; a discrete GPU wins 10LEONIDA_VK_DEVICE filters by deviceName substring case-insensitively (failing when nothing matches), then Vulkan 1.3
11(the last one), otherwise the first. The runtime also needs the rest of its device setup (surface, extensions); 11devices with dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts and a graphics queue
12that is not checked here. vk_pipeline_check picks by device type only, so on a PC where the two differ the pipelines 12family; a discrete GPU wins (the last one), otherwise the first. The runtime also needs the rest of its device setup
13stage can run on another GPU than the one asked here. VK_LOADER_DRIVERS_SELECT (e.g. '*amd*') narrows which 13(surface, extensions); that is not checked here. vk_pipeline_check picks by device type only, so on a PC where the two
14drivers the loader offers. 14differ the pipelines stage can run on another GPU than the one asked here. VK_LOADER_DRIVERS_SELECT (e.g. '*amd*')
15narrows which drivers the loader offers.
15 16
16native64 matches the current translated SPIR-V 1.5 modules, which do not allow varying subgroup sizes: either 64 can 17native64 matches the current translated SPIR-V 1.5 modules, which do not allow varying subgroup sizes: either 64 can
17be required for both compute and mesh, or the default subgroupSize is 64 and subgroup operations are supported in 18be required for both compute and mesh, or the default subgroupSize is 64 and subgroup operations are supported in
18both stages. SPIR-V 1.6 modules or stages created with ALLOW_VARYING_SUBGROUP_SIZE need a different check. 19both stages. SPIR-V 1.6 modules or stages created with ALLOW_VARYING_SUBGROUP_SIZE need a different check.
19 20
21rdna2_amd_windows says whether the device is RDNA2 (gfx103x, by PCI device ID) under AMD's proprietary Windows driver.
22That driver's shader compiler crashes (an access violation in vkCreateComputePipelines) on many --wave64-emulate
23compute shaders with LDS: #857, from driver 32.0.21030 to at least 32.0.21045.29003, on iGPUs and RX 6000 cards
24alike, while RDNA3, RDNA4, RADV and NVIDIA take the same modules. make_game.py leaves emulation off for such a GPU.
25
20per_vertex_inputs says whether the device can run a pixel shader with PerVertexKHR inputs (16-bit interpolation, 26per_vertex_inputs says whether the device can run a pixel shader with PerVertexKHR inputs (16-bit interpolation,
21docs/design.md): the fragmentShaderBarycentric feature, and a driver other than MoltenVK, whose SPIR-V to MSL 27docs/design.md): the fragmentShaderBarycentric feature, and a driver other than MoltenVK, whose SPIR-V to MSL
22conversion rejects the decoration ("PerVertexKHR decoration is not supported in MSL", MoltenVK 1.4.2). Where it is 28conversion rejects the decoration ("PerVertexKHR decoration is not supported in MSL", MoltenVK 1.4.2). Where it is
@@ -38,6 +44,13 @@ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES = 1000225000
38VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES = 1000196000 44VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES = 1000196000
39VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR = 1000203000 45VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR = 1000203000
40VK_DRIVER_ID_MOLTENVK = 14 46VK_DRIVER_ID_MOLTENVK = 14
47VK_DRIVER_ID_AMD_PROPRIETARY = 1
48AMD_VENDOR_ID = 0x1002
49# PCI device IDs of RDNA2 (gfx103x) GPUs: Navi 21/22/23/24 cards, and the iGPUs of Van Gogh (Steam Deck),
50# Rembrandt (Ryzen 6000), Mendocino (Ryzen 7020) and Raphael/Granite Ridge (Ryzen 7000/9000 desktop). #857 has
51# crash reports from 0x13C0, 0x164E, 0x73BF (RX 6800) and 0x73DF (RX 6700).
52RDNA2_DEVICE_IDS = ((0x73A0, 0x73FF), (0x7420, 0x743F), (0x163F, 0x163F), (0x1435, 0x1435), (0x1681, 0x1681),
53 (0x1506, 0x1506), (0x164E, 0x164E), (0x13C0, 0x13C0))
41DRIVER_PROPS_SIZE = 536 # sizeof(VkPhysicalDeviceDriverProperties): 16 + driverID + 2 x char[256] + version, padded 54DRIVER_PROPS_SIZE = 536 # sizeof(VkPhysicalDeviceDriverProperties): 16 + driverID + 2 x char[256] + version, padded
42BARY_FEATURES_SIZE = 24 # sizeof(VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR): 16 + one VkBool32 55BARY_FEATURES_SIZE = 24 # sizeof(VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR): 16 + one VkBool32
43VK_SHADER_STAGE_COMPUTE_BIT = 0x20 56VK_SHADER_STAGE_COMPUTE_BIT = 0x20
@@ -58,6 +71,8 @@ F13_SUBGROUP_SIZE_CONTROL = 16 + 4 * 7
58F13_SYNCHRONIZATION2 = 16 + 4 * 9 71F13_SYNCHRONIZATION2 = 16 + 4 * 9
59F13_DYNAMIC_RENDERING = 16 + 4 * 12 72F13_DYNAMIC_RENDERING = 16 + 4 * 12
60PROPS_DEVICE_TYPE = 16 # offsets in VkPhysicalDeviceProperties 73PROPS_DEVICE_TYPE = 16 # offsets in VkPhysicalDeviceProperties
74PROPS_VENDOR_ID = 8
75PROPS_DEVICE_ID = 12
61PROPS_DEVICE_NAME = 20 # char[256] 76PROPS_DEVICE_NAME = 20 # char[256]
62PROPS_API_VERSION = 0 77PROPS_API_VERSION = 0
63QUEUE_FAMILY_SIZE = 24 # sizeof(VkQueueFamilyProperties) 78QUEUE_FAMILY_SIZE = 24 # sizeof(VkQueueFamilyProperties)
@@ -119,6 +134,12 @@ def load_vulkan():
119 raise RuntimeError("no Vulkan loader found (" + ", ".join(names) + ")") 134 raise RuntimeError("no Vulkan loader found (" + ", ".join(names) + ")")
120 135
121 136
137def rdna2_amd_windows(vendor_id: int, device_id: int, driver_id: int) -> bool:
138 """An RDNA2 GPU under AMD's proprietary (Windows) driver: the one whose compiler crashes on #857's modules."""
139 return (vendor_id == AMD_VENDOR_ID and driver_id == VK_DRIVER_ID_AMD_PROPRIETARY
140 and any(lo <= device_id <= hi for lo, hi in RDNA2_DEVICE_IDS))
141
142
122def physical_devices(vk, instance): 143def physical_devices(vk, instance):
123 # The list can grow between the count and fetch. Recount, with a bound for a changing driver. 144 # The list can grow between the count and fetch. Recount, with a bound for a changing driver.
124 for _ in range(3): 145 for _ in range(3):
@@ -160,6 +181,8 @@ def query() -> dict:
160 devs = physical_devices(vk, inst) 181 devs = physical_devices(vk, inst)
161 if not devs: 182 if not devs:
162 raise RuntimeError("no Vulkan device") 183 raise RuntimeError("no Vulkan device")
184 device_filter = os.environ.get("LEONIDA_VK_DEVICE", "")
185 wanted = device_filter.lower()
163 chosen = None 186 chosen = None
164 for d in devs: 187 for d in devs:
165 d = ctypes.c_void_p(d) 188 d = ctypes.c_void_p(d)
@@ -173,8 +196,11 @@ def query() -> dict:
173 set_next(props, subgroup) 196 set_next(props, subgroup)
174 vk.vkGetPhysicalDeviceProperties2(d, props) 197 vk.vkGetPhysicalDeviceProperties2(d, props)
175 raw = bytes(props)[16:] 198 raw = bytes(props)[16:]
199 dev_name = raw[PROPS_DEVICE_NAME:PROPS_DEVICE_NAME + 256].split(b"\0")[0].decode("utf-8", "replace")
176 if int.from_bytes(raw[PROPS_API_VERSION:PROPS_API_VERSION + 4], "little") < VK_API_VERSION_1_3: 200 if int.from_bytes(raw[PROPS_API_VERSION:PROPS_API_VERSION + 4], "little") < VK_API_VERSION_1_3:
177 continue 201 continue
202 if wanted and wanted not in dev_name.lower():
203 continue
178 f13 = block(F13_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES) 204 f13 = block(F13_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES)
179 f12 = block(F12_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES) 205 f12 = block(F12_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES)
180 set_next(f12, f13) 206 set_next(f12, f13)
@@ -195,13 +221,20 @@ def query() -> dict:
195 dtype = int.from_bytes(raw[PROPS_DEVICE_TYPE:PROPS_DEVICE_TYPE + 4], "little") 221 dtype = int.from_bytes(raw[PROPS_DEVICE_TYPE:PROPS_DEVICE_TYPE + 4], "little")
196 # the runtime's rule: the first usable device, replaced by every later discrete GPU 222 # the runtime's rule: the first usable device, replaced by every later discrete GPU
197 if chosen is None or dtype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: 223 if chosen is None or dtype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
198 chosen = (raw[PROPS_DEVICE_NAME:PROPS_DEVICE_NAME + 256].split(b"\0")[0].decode("utf-8", "replace"), 224 chosen = (dev_name,
199 subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize, 225 subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize,
200 sg.requiredSubgroupSizeStages, bool(u32(f13, F13_SUBGROUP_SIZE_CONTROL)), 226 sg.requiredSubgroupSizeStages, bool(u32(f13, F13_SUBGROUP_SIZE_CONTROL)),
201 bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK) 227 bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK,
228 int.from_bytes(raw[PROPS_VENDOR_ID:PROPS_VENDOR_ID + 4], "little"),
229 int.from_bytes(raw[PROPS_DEVICE_ID:PROPS_DEVICE_ID + 4], "little"), u32(drv, 16))
202 if chosen is None: 230 if chosen is None:
231 if device_filter:
232 raise RuntimeError(
233 f"LEONIDA_VK_DEVICE={device_filter}: no Vulkan 1.3 GPU with the features and graphics queue "
234 "the runtime needs matches"
235 )
203 raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs") 236 raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs")
204 name, subgroup_size, supported_stages, lo, hi, required_stages, sgc, per_vertex = chosen 237 name, subgroup_size, supported_stages, lo, hi, required_stages, sgc, per_vertex, vendor, device, driver = chosen
205 compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT) 238 compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT)
206 mesh_required = bool(required_stages & VK_SHADER_STAGE_MESH_BIT_EXT) 239 mesh_required = bool(required_stages & VK_SHADER_STAGE_MESH_BIT_EXT)
207 compute_supported = bool(supported_stages & VK_SHADER_STAGE_COMPUTE_BIT) 240 compute_supported = bool(supported_stages & VK_SHADER_STAGE_COMPUTE_BIT)
@@ -221,6 +254,10 @@ def query() -> dict:
221 "mesh_in_supported_stages": mesh_supported, 254 "mesh_in_supported_stages": mesh_supported,
222 "native64": bool(can_require_64 or has_default_64), 255 "native64": bool(can_require_64 or has_default_64),
223 "per_vertex_inputs": per_vertex, 256 "per_vertex_inputs": per_vertex,
257 "vendor_id": vendor,
258 "device_id": device,
259 "driver_id": driver,
260 "rdna2_amd_windows": rdna2_amd_windows(vendor, device, driver),
224 } 261 }
225 finally: 262 finally:
226 vk.vkDestroyInstance(inst, None) 263 vk.vkDestroyInstance(inst, None)
diff --git a/tools/world_index.py b/tools/world_index.py
index e72f8952c..c3e6a62bf 100644
--- a/tools/world_index.py
+++ b/tools/world_index.py
@@ -396,7 +396,11 @@ def scan_rpf(path, start=None, limit=None, max_inflate=CAP, collect=None):
396 396
397 397
398def _directory_files(path): 398def _directory_files(path):
399 for root, _, files in os.walk(path): 399 def scan_failed(error: OSError) -> None:
400 raise error
401
402 # A partial walk must fail before the caller starts writing reports.
403 for root, _, files in os.walk(path, onerror=scan_failed):
400 for name in sorted(files): 404 for name in sorted(files):
401 yield os.path.join(root, name) 405 yield os.path.join(root, name)
402 406
@@ -415,6 +419,15 @@ def _carve_successors(folder):
415 for off, stored in by_off.items() if (off + stored + 15) & ~15 in by_off} 419 for off, stored in by_off.items() if (off + stored + 15) & ~15 in by_off}
416 420
417 421
422def _read_carved(path, max_inflate):
423 """Read a carved file within the cap, or return None if it is too large."""
424 with open(path, "rb") as f:
425 if os.fstat(f.fileno()).st_size > max_inflate:
426 return None
427 data = f.read(max_inflate + 1) # detect growth after fstat
428 return data if len(data) <= max_inflate else None
429
430
418def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, directory_files=None): 431def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, directory_files=None):
419 """Scan an RPF9 archive, or every carved file in a directory.""" 432 """Scan an RPF9 archive, or every carved file in a directory."""
420 if directory_files is not None or os.path.isdir(path): 433 if directory_files is not None or os.path.isdir(path):
@@ -436,10 +449,9 @@ def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, di
436 stats["files"] += 1 449 stats["files"] += 1
437 stats["scanned_bytes"] += sub["scanned_bytes"] 450 stats["scanned_bytes"] += sub["scanned_bytes"]
438 continue 451 continue
439 if os.path.getsize(p) > max_inflate: 452 b = _read_carved(p, max_inflate)
453 if b is None:
440 continue 454 continue
441 with open(p, "rb") as f:
442 b = f.read(max_inflate + 1)
443 stats["files"] += 1 455 stats["files"] += 1
444 stats["scanned_bytes"] += len(b) 456 stats["scanned_bytes"] += len(b)
445 # As in scan_rpf: a 0DRPz resource that needs a continuation takes the next stream, when the 457 # As in scan_rpf: a 0DRPz resource that needs a continuation takes the next stream, when the
@@ -476,8 +488,9 @@ def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, di
476 magic = f.read(4) 488 magic = f.read(4)
477 if magic == b"9FPR": 489 if magic == b"9FPR":
478 return scan_rpf(path, start, limit, max_inflate, collect) 490 return scan_rpf(path, start, limit, max_inflate, collect)
479 with open(path, "rb") as f: 491 b = _read_carved(path, max_inflate)
480 b = f.read(max_inflate + 1) 492 if b is None:
493 return [], {"path": os.path.abspath(path), "files": 0, "scanned_bytes": 0}
481 row = parse_resource(b, collect) 494 row = parse_resource(b, collect)
482 return ([dict(row, offset=0, size=len(b), file=os.path.basename(path))] if row else [], 495 return ([dict(row, offset=0, size=len(b), file=os.path.basename(path))] if row else [],
483 {"path": os.path.abspath(path), "files": 1, "scanned_bytes": len(b)}) 496 {"path": os.path.abspath(path), "files": 1, "scanned_bytes": len(b)})
@@ -748,7 +761,7 @@ def _write_reports(a, rows, stats, agg):
748 "position_max", "lod", "lod_dist_min", "lod_dist_max"] 761 "position_max", "lod", "lod_dist_min", "lod_dist_max"]
749 os.makedirs(os.path.dirname(os.path.abspath(a.csv)), exist_ok=True) 762 os.makedirs(os.path.dirname(os.path.abspath(a.csv)), exist_ok=True)
750 with open(a.csv, "w", newline="", encoding="utf-8") as f: 763 with open(a.csv, "w", newline="", encoding="utf-8") as f:
751 w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore") 764 w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore", lineterminator="\n")
752 w.writeheader() 765 w.writeheader()
753 for r in rows: 766 for r in rows:
754 r = dict(r) 767 r = dict(r)
diff --git a/tools/world_names.py b/tools/world_names.py
index 70e89b62f..4ffe3f01a 100644
--- a/tools/world_names.py
+++ b/tools/world_names.py
@@ -573,7 +573,7 @@ def _resolve(args) -> int:
573 for path in (args.dict, *args.maps, *args.archetypes): 573 for path in (args.dict, *args.maps, *args.archetypes):
574 if _same_report_path(args.out, path): 574 if _same_report_path(args.out, path):
575 raise ValueError( 575 raise ValueError(
576 f"resolve: --out {args.out!r} would overwrite input {path!r}") 576 f"resolve: --out {args.out} would overwrite input {path}")
577 try: 577 try:
578 dictionary = NameDictionary.from_json(_load_json(args.dict)) 578 dictionary = NameDictionary.from_json(_load_json(args.dict))
579 except ValueError as exc: 579 except ValueError as exc:
diff --git a/tools/xdxr_bvh.py b/tools/xdxr_bvh.py
index edcc79a8b..e8fcefde3 100644
--- a/tools/xdxr_bvh.py
+++ b/tools/xdxr_bvh.py
@@ -740,11 +740,15 @@ def check_build(directory, rays=300, seed=1):
740 return [f"no cases in {directory}"] 740 return [f"no cases in {directory}"]
741 problems = [] 741 problems = []
742 cases = {n: _load_case(directory, n) for n in names} 742 cases = {n: _load_case(directory, n) for n in names}
743 mem = Memory()
744 for n, (desc, data) in cases.items():
745 mem.place(desc["address"], data)
746 rng = random.Random(seed) 743 rng = random.Random(seed)
747 for n, (desc, data) in cases.items(): 744 for n, (desc, data) in cases.items():
745 # An in-place update leaves two dumps at one address (before and after): the case being checked comes first,
746 # so its own bytes answer reads there.
747 mem = Memory()
748 mem.place(desc["address"], data)
749 for other, (odesc, odata) in cases.items():
750 if other != n:
751 mem.place(odesc["address"], odata)
748 errs = validate(data, expect_bottom=desc["kind"] == "blas") 752 errs = validate(data, expect_bottom=desc["kind"] == "blas")
749 problems += [f"{n}: {e}" for e in errs] 753 problems += [f"{n}: {e}" for e in errs]
750 if desc["kind"] == "blas": 754 if desc["kind"] == "blas":