diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-26 16:55:04 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-26 16:55:04 -0500 |
| commit | df92abca8ee2a8f9093efea7fcaa4dadc3ddaebc (patch) | |
| tree | 97ef8f95544fe263049d3f7360823f16100de209 /tools | |
| parent | 49a0b69fcdb80db1f2a44ce7ca0ab8dfdec1e403 (diff) | |
| parent | e5a7c8942678b323f655939c81f5d8855d20c248 (diff) | |
Merge main e5a7c8942 into shadow-aliased-guard (#1867)
One conflict, runtime/README.md: this branch rewrote the LEONIDA_SHADOW_ALIAS_MS
row, main (#2163) added the LEONIDA_SHADOW_KEEP row after it. Both rows kept;
the keep row's "aliased" now reads "aliased while they can't be guarded at every
address", since aliased pages are no longer copied without a sign of a write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools')
| -rw-r--r-- | tools/address_guard.py | 110 | ||||
| -rw-r--r-- | tools/bcpack_history_calib.py | 2 | ||||
| -rw-r--r-- | tools/build_dstorage_history.py | 159 | ||||
| -rw-r--r-- | tools/dds_png.py | 224 | ||||
| -rw-r--r-- | tools/rdna2spirv.py | 342 | ||||
| -rw-r--r-- | tools/tex_export.py | 8 | ||||
| -rw-r--r-- | tools/tex_headers.py | 3 | ||||
| -rw-r--r-- | tools/wave64_emulate_opt.py | 12 | ||||
| -rw-r--r-- | tools/wave64_halves.py | 10 |
9 files changed, 803 insertions, 67 deletions
diff --git a/tools/address_guard.py b/tools/address_guard.py new file mode 100644 index 000000000..1acbad528 --- /dev/null +++ b/tools/address_guard.py | |||
| @@ -0,0 +1,110 @@ | |||
| 1 | """The address guard's page table and header, as the runtime writes them (runtime/src/address_guard.h) and the | ||
| 2 | shaders translated with `rdna2spirv.py --address-guard` read them (docs/d3d12_vulkan.md, "Address guard"). | ||
| 3 | |||
| 4 | Standard library only. Used by the translator tests and scripts/run_address_guard_gpu_test.py to build a heap, and | ||
| 5 | as the Python reference of the check a guarded access makes: | ||
| 6 | |||
| 7 | python -I tools/address_guard.py 0x90000:0x91000 --check 0x90ffc 8 | ||
| 8 | |||
| 9 | Offsets are heap offsets (device address - heap_base), taken as 48-bit values: a negative one (a buffer below the | ||
| 10 | arena) is its two's complement in 48 bits, as the shaders sign-extend a V#'s base. | ||
| 11 | """ | ||
| 12 | import argparse | ||
| 13 | import struct | ||
| 14 | import sys | ||
| 15 | |||
| 16 | # Shared with tools/rdna2spirv.py (ADDRESS_GUARD and the GUARD_* constants) and runtime/src/address_guard.h. | ||
| 17 | HEADER = 0x70000 # arena offset of the header | ||
| 18 | ZERO = 0x71000 # refused loads read here (+ the offset within its 4 KiB page) | ||
| 19 | DUMP = 0x78000 # refused stores and atomics write here | ||
| 20 | RESERVED_END = 0x80000 # the guard's part of the arena ends here | ||
| 21 | MAGIC = int.from_bytes(b"LGUARD01", "little") | ||
| 22 | L1 = 1 << 16 # level-1 words: bits 47..32 of the offset | ||
| 23 | BLOCK_WORDS = 1 << 15 # a level-2 block: one bit per 4 KiB page of a 4 GiB chunk | ||
| 24 | PAGE = 1 << 12 | ||
| 25 | MASK48 = (1 << 48) - 1 | ||
| 26 | EMPTY_BLOCK, FULL_BLOCK = 0, 1 # every table has them; allocated blocks start at 2 | ||
| 27 | |||
| 28 | |||
| 29 | def header(limit, table_offset, refused=0, last=0): | ||
| 30 | """The 64-byte header: magic, arena size (offsets below it pass without a lookup), the table's address minus | ||
| 31 | heap_base (mod 2^64), the refusal count and the last refused offset, which the shaders write.""" | ||
| 32 | return struct.pack("<QQQIIQ24x", MAGIC, limit, table_offset & ((1 << 64) - 1), refused, 0, last) | ||
| 33 | |||
| 34 | |||
| 35 | def table_words(spans, max_blocks=None): | ||
| 36 | """The table's words for backed [start, end) heap offset spans: level 1, then the level-2 blocks. A page is | ||
| 37 | backed when any byte of it is (a GPU page is mapped whole). Past `max_blocks` allocated blocks a chunk gets the | ||
| 38 | full block: everything in it passes, as the runtime does when it runs out of room (and logs it).""" | ||
| 39 | chunks = {} | ||
| 40 | for start, end in spans: | ||
| 41 | if end <= start: | ||
| 42 | continue | ||
| 43 | for page in range((start & MASK48) >> 12, (((end - 1) & MASK48) >> 12) + 1): | ||
| 44 | chunks.setdefault(page >> 20, set()).add(page & 0xFFFFF) | ||
| 45 | level1 = [EMPTY_BLOCK] * L1 | ||
| 46 | blocks = [] | ||
| 47 | for chunk in sorted(chunks): | ||
| 48 | if max_blocks is not None and len(blocks) >= max_blocks: | ||
| 49 | level1[chunk] = FULL_BLOCK | ||
| 50 | continue | ||
| 51 | bits = [0] * BLOCK_WORDS | ||
| 52 | for page in chunks[chunk]: | ||
| 53 | bits[page >> 5] |= 1 << (page & 31) | ||
| 54 | level1[chunk] = 2 + len(blocks) | ||
| 55 | blocks.append(bits) | ||
| 56 | words = level1 + [0] * BLOCK_WORDS + [0xFFFFFFFF] * BLOCK_WORDS | ||
| 57 | for bits in blocks: | ||
| 58 | words += bits | ||
| 59 | return words | ||
| 60 | |||
| 61 | |||
| 62 | def page_backed(words, offset): | ||
| 63 | """The table's bit for the page of heap offset `offset`.""" | ||
| 64 | offset &= MASK48 | ||
| 65 | block = words[(offset >> 32) & (L1 - 1)] | ||
| 66 | page = (offset >> 12) & 0xFFFFF | ||
| 67 | return bool(words[L1 + block * BLOCK_WORDS + (page >> 5)] >> (page & 31) & 1) | ||
| 68 | |||
| 69 | |||
| 70 | def passes(words, limit, offset, extent): | ||
| 71 | """What a guarded access does: True when [offset, offset + extent) is below `limit` (the arena) or the pages of | ||
| 72 | its first and last byte are backed. `offset` is sign-extended from 48 bits, as the shaders do.""" | ||
| 73 | offset &= MASK48 | ||
| 74 | if offset >> 47: | ||
| 75 | offset -= 1 << 48 | ||
| 76 | end = offset + extent - 1 | ||
| 77 | if 0 <= offset < limit and 0 <= end < limit: | ||
| 78 | return True | ||
| 79 | return page_backed(words, offset) and page_backed(words, end) | ||
| 80 | |||
| 81 | |||
| 82 | def _int(text): | ||
| 83 | return int(text, 0) | ||
| 84 | |||
| 85 | |||
| 86 | def main(argv=None): | ||
| 87 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | ||
| 88 | ap.add_argument("spans", nargs="*", help="backed heap offset spans, START:END (hex or decimal)") | ||
| 89 | ap.add_argument("--limit", type=_int, default=RESERVED_END, help="the arena's size (default %(default)#x)") | ||
| 90 | ap.add_argument("--check", nargs=2, type=_int, metavar=("OFFSET", "BYTES"), action="append", default=[], | ||
| 91 | help="print whether an access passes") | ||
| 92 | a = ap.parse_args(argv) | ||
| 93 | spans = [] | ||
| 94 | for text in a.spans: | ||
| 95 | start, _, end = text.partition(":") | ||
| 96 | spans.append((_int(start), _int(end))) | ||
| 97 | words = table_words(spans) | ||
| 98 | blocks = (len(words) - L1) // BLOCK_WORDS | ||
| 99 | print(f"table: {len(words) * 4} bytes, {blocks - 2} level-2 block(s) besides the empty and full ones") | ||
| 100 | for offset, extent in a.check: | ||
| 101 | print(f"{offset:#x} +{extent}: {'passes' if passes(words, a.limit, offset, extent) else 'refused'}") | ||
| 102 | return 0 | ||
| 103 | |||
| 104 | |||
| 105 | if __name__ == "__main__": | ||
| 106 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 107 | sys.stdout.reconfigure(errors="replace") | ||
| 108 | except (AttributeError, ValueError, OSError): | ||
| 109 | pass | ||
| 110 | sys.exit(main()) | ||
diff --git a/tools/bcpack_history_calib.py b/tools/bcpack_history_calib.py index 4c8312b41..01bb3af2e 100644 --- a/tools/bcpack_history_calib.py +++ b/tools/bcpack_history_calib.py | |||
| @@ -1858,6 +1858,8 @@ class Bc7Calibrator: | |||
| 1858 | if xy is None: | 1858 | if xy is None: |
| 1859 | continue | 1859 | continue |
| 1860 | qpts = get_quads(xy[0], xy[1]) | 1860 | qpts = get_quads(xy[0], xy[1]) |
| 1861 | if qpts is None: # the sibling block is undetermined itself | ||
| 1862 | continue | ||
| 1861 | spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(4)) | 1863 | spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(4)) |
| 1862 | weight = 4.0 if spread <= 6.0 else (2.0 if spread <= 18.0 else 0.5) | 1864 | weight = 4.0 if spread <= 6.0 else (2.0 if spread <= 18.0 else 0.5) |
| 1863 | sm = None if ns == 1 else (p2[part] if ns == 2 else p3[part]) | 1865 | sm = None if ns == 1 else (p2[part] if ns == 2 else p3[part]) |
diff --git a/tools/build_dstorage_history.py b/tools/build_dstorage_history.py index ee9c224bd..8320f87d4 100644 --- a/tools/build_dstorage_history.py +++ b/tools/build_dstorage_history.py | |||
| @@ -93,6 +93,164 @@ def extend_missing(base, extra): | |||
| 93 | base["bc7"][value][k][j] = extra["bc7"][value][k][j] | 93 | base["bc7"][value][k][j] = extra["bc7"][value][k][j] |
| 94 | 94 | ||
| 95 | 95 | ||
| 96 | def _field_count(docs): | ||
| 97 | return (sum(map(bool, docs["bc6h"]["endpointClass"])) + sum(map(bool, docs["bc6h"]["indexClass"])) + | ||
| 98 | sum(bool(v) for key in ("historyEndpointBits", "historyIndexBits") for row in docs["bc7"][key] for v in row)) | ||
| 99 | |||
| 100 | |||
| 101 | def _unknown_references(codec, lanes, blocks, docs, table): | ||
| 102 | """Whether the stream's first 256 blocks start a predictor chain at a field the profile still lacks.""" | ||
| 103 | if codec == 7: | ||
| 104 | try: | ||
| 105 | return bool(calib.bcpack._bc7_check(lanes, min(blocks, 256), table, set(), has_history=True)) | ||
| 106 | except calib.bcpack.BcpackError: | ||
| 107 | return False | ||
| 108 | l0, l1 = lanes[0], lanes[1] | ||
| 109 | for i in range(min(blocks, 256)): | ||
| 110 | di = calib.bcpack._inter8(l1[2*i], l1[2*i+1]) | ||
| 111 | de = (di + calib.bcpack._unzig(calib.bcpack._inter8(l0[2*i], l0[2*i+1]))) & 255 | ||
| 112 | if (de > i and not docs["bc6h"]["endpointClass"][256+i-de] or | ||
| 113 | di > i and not docs["bc6h"]["indexClass"][256+i-di]): | ||
| 114 | return True | ||
| 115 | return False | ||
| 116 | |||
| 117 | |||
| 118 | def _decode_known(pool, start, size, docs, table, cache): | ||
| 119 | """Tiled bytes of a range plus the byte offsets (within it) of blocks the profile cannot determine. | ||
| 120 | |||
| 121 | A BC7 stream that the decoder refuses for its unknown history still determines every block whose predictor | ||
| 122 | chains start elsewhere; only the blocks rooted at an unknown field, or failing the anchor and p-bit check, are | ||
| 123 | marked. Other BCPack streams must decode in provisional mode.""" | ||
| 124 | bcpack = calib.bcpack | ||
| 125 | out = bytearray(size) | ||
| 126 | unknown = set() | ||
| 127 | for virt, csize, offset, packed, codec, _ in pool.chunks_for(start, size): | ||
| 128 | key = (offset, packed, codec) | ||
| 129 | if key not in cache: | ||
| 130 | raw = pool.data[offset:offset+packed] | ||
| 131 | bad = () | ||
| 132 | if codec in (0, 8): | ||
| 133 | data = pool.read_range(virt, csize, None, bcpack_mode="off") | ||
| 134 | elif codec == 7: | ||
| 135 | lanes, _ = bcpack.decode_lanes(raw, 7, csize) | ||
| 136 | blocks = csize // 16 | ||
| 137 | missing = bcpack._bc7_check(lanes, blocks, table, set(), has_history=True) | ||
| 138 | data, status = bcpack._bc7_rebuild(lanes, blocks, table) | ||
| 139 | ends = {k for kind, k in missing if kind == "endpoint"} | ||
| 140 | idxs = {k for kind, k in missing if kind == "index"} | ||
| 141 | l0, l1 = lanes[0], lanes[1] | ||
| 142 | er, ir = [-1] * blocks, [-1] * blocks | ||
| 143 | for i in range(blocks): | ||
| 144 | di = bcpack._inter8(l1[2*i], l1[2*i+1]) | ||
| 145 | de = (di + bcpack._unzig(bcpack._inter8(l0[2*i], l0[2*i+1]))) & 255 | ||
| 146 | er[i] = -1 if de == 0 else (256 + i - de if de > i else er[i - de]) | ||
| 147 | ir[i] = -1 if di == 0 else (256 + i - di if di > i else ir[i - di]) | ||
| 148 | bad = {16 * i for i in range(blocks) if status[i] or er[i] in ends or ir[i] in idxs} | ||
| 149 | else: | ||
| 150 | data = bcpack.decode(raw, codec, csize, allow_provisional=True, history=docs) | ||
| 151 | cache[key] = (bytes(data), bad) | ||
| 152 | data, bad = cache[key] | ||
| 153 | lo, hi = max(start, virt), min(start + size, virt + csize) | ||
| 154 | out[lo - start:hi - start] = data[lo - virt:hi - virt] | ||
| 155 | unknown.update(virt + b - start for b in bad if lo <= virt + b < hi) | ||
| 156 | return bytes(out), unknown | ||
| 157 | |||
| 158 | |||
| 159 | def _known_quads(getter, layout, ref, kind, unknown): | ||
| 160 | """The sibling getter, answering None where a reference block is undetermined.""" | ||
| 161 | if not unknown: | ||
| 162 | return getter | ||
| 163 | bw, bh = (ref["pixels_w"] + 3) // 4, (ref["pixels_h"] + 3) // 4 | ||
| 164 | def get_quads(bx, by): | ||
| 165 | # A child's 2x2 pixels per quad lie in one block; a parent's quads cover a 2x2 block square. | ||
| 166 | x0, y0, span = (bx // 2, by // 2, 1) if kind == "child" else (2 * bx, 2 * by, 2) | ||
| 167 | for y in range(y0, y0 + span): | ||
| 168 | for x in range(x0, x0 + span): | ||
| 169 | if calib.tiled_offset(layout, ref, min(x, bw - 1), min(y, bh - 1)) in unknown: | ||
| 170 | return None | ||
| 171 | return getter(bx, by) | ||
| 172 | return get_quads | ||
| 173 | |||
| 174 | |||
| 175 | def fit_decoded_neighbors(pools, docs, rounds=4): | ||
| 176 | """Fill fields that only streams without a raw or zlib sibling reference. | ||
| 177 | |||
| 178 | The other fits take their reference from a raw or zlib mip. A packed tail whose larger mips are BCPack-coded | ||
| 179 | too has none, so a field that only such streams use stays unknown and the runtime refuses them. Decode the | ||
| 180 | nearest BCPack sibling with the profile so far and fit against it; it may lie in the same refused stream, whose | ||
| 181 | undetermined blocks are left out of the reference. A decoded mip can be the reference of the next one, so | ||
| 182 | repeat while a round adds fields. Only fields still missing are filled, and never as confirmed. | ||
| 183 | """ | ||
| 184 | table = bptc.load_bc7(docs) | ||
| 185 | jobs = [] | ||
| 186 | for path in pools: | ||
| 187 | with closing(ttpf.Pool(path)) as pool: | ||
| 188 | wanted = set() | ||
| 189 | for _, size, offset, packed, codec, _ in pool.chunks: | ||
| 190 | if codec in (6, 7): | ||
| 191 | blocks = min(2048, size // 16) | ||
| 192 | lanes = calib.decode_lanes_prefix(pool.data[offset:offset+packed], codec, size, blocks*2) | ||
| 193 | if _unknown_references(codec, lanes, blocks, docs, table): | ||
| 194 | wanted.add(offset) | ||
| 195 | if not wanted: | ||
| 196 | continue | ||
| 197 | for index in range(pool.textures): | ||
| 198 | d = pool.descriptor(index) | ||
| 199 | codec = next((c for c in (6, 7) if d["format"] in calib.CODEC_DXGI[c]), None) | ||
| 200 | if not codec or d["dimension"] not in (1, 2): | ||
| 201 | continue | ||
| 202 | a = ttpf.analyze(pool, index) | ||
| 203 | if not a.get("available") or a.get("blocked"): | ||
| 204 | continue | ||
| 205 | layout = a["layout"] | ||
| 206 | for layer in range(d["depth"]): | ||
| 207 | for level, mip in enumerate(layout["mips"]): | ||
| 208 | start = (d["base"] + layout.get("data_offset", 0) + mip["offset"] + | ||
| 209 | layer * mip.get("slice_stride", layout.get("face_size", 0))) | ||
| 210 | if any(c[2] in wanted for c in pool.chunks_for(start, mip["region"])): | ||
| 211 | jobs.append((path, index, codec, layer, level)) | ||
| 212 | for _ in range(rounds): | ||
| 213 | before = _field_count(docs) | ||
| 214 | table = bptc.load_bc7(docs) | ||
| 215 | fits = {6: calib.Bc6hCalibrator(), 7: calib.Bc7Calibrator()} | ||
| 216 | for path in sorted({job[0] for job in jobs}): | ||
| 217 | with closing(ttpf.Pool(path)) as pool: | ||
| 218 | cache = {} | ||
| 219 | for _, index, codec, layer, level in (job for job in jobs if job[0] == path): | ||
| 220 | d = pool.descriptor(index) | ||
| 221 | layout = ttpf.analyze(pool, index)["layout"] | ||
| 222 | mips = layout["mips"] | ||
| 223 | def address(m): | ||
| 224 | return (d["base"] + layout.get("data_offset", 0) + m["offset"] + | ||
| 225 | layer * m.get("slice_stride", layout.get("face_size", 0))) | ||
| 226 | mip = mips[level] | ||
| 227 | start = address(mip) | ||
| 228 | chunks = [(size, offset, packed, virt - start, min(2048, size // 16)) | ||
| 229 | for virt, size, offset, packed, mode, _ in pool.chunks_for(start, mip["region"]) | ||
| 230 | if mode == codec and start - virt < 2048 * 16] | ||
| 231 | for neighbor, kind in ((level+1, "child"), (level-1, "parent")): | ||
| 232 | if not 0 <= neighbor < len(mips) or mips[neighbor]["region"] > 1048576: | ||
| 233 | continue | ||
| 234 | ref = mips[neighbor] | ||
| 235 | if codec not in pool.codecs(address(ref), ref["region"]): | ||
| 236 | continue # a raw or zlib sibling is the other fits' reference | ||
| 237 | try: | ||
| 238 | tiled, unknown = _decode_known(pool, address(ref), ref["region"], docs, table, cache) | ||
| 239 | except (calib.bcpack.BcpackError, ValueError): | ||
| 240 | continue | ||
| 241 | getter = _known_quads(calib._make_sibling_quads_getter(codec, layout, ref, tiled, kind, | ||
| 242 | signed=d["format"] == 96), | ||
| 243 | layout, ref, kind, unknown) | ||
| 244 | inverse = calib.make_inverse_tile_lookup(layout, mip) | ||
| 245 | for size, offset, packed, relative, blocks in chunks: | ||
| 246 | lanes = calib.decode_lanes_prefix(pool.data[offset:offset+packed], codec, size, blocks*2) | ||
| 247 | fits[codec].add_pool_chunk(lanes, blocks, inverse, relative, getter) | ||
| 248 | extend_missing(docs, {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()}) | ||
| 249 | if _field_count(docs) == before: | ||
| 250 | break | ||
| 251 | return docs | ||
| 252 | |||
| 253 | |||
| 96 | def collect(pools, trainer, temporary): | 254 | def collect(pools, trainer, temporary): |
| 97 | """The host trainer consumes framed chunks and returns violation counts per candidate.""" | 255 | """The host trainer consumes framed chunks and returns violation counts per candidate.""" |
| 98 | output = temporary / "constraints" | 256 | output = temporary / "constraints" |
| @@ -214,6 +372,7 @@ def build(game, output, trainer, base_history=None, json_out=None, if_needed=Fal | |||
| 214 | calib.calibrate_from_pools(pools, fits) | 372 | calib.calibrate_from_pools(pools, fits) |
| 215 | docs = {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()} | 373 | docs = {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()} |
| 216 | extend_missing(docs, fit_slices(pools)) | 374 | extend_missing(docs, fit_slices(pools)) |
| 375 | fit_decoded_neighbors(pools, docs) | ||
| 217 | history = temp/"history.json" | 376 | history = temp/"history.json" |
| 218 | history.write_text(json.dumps(docs), encoding="utf-8", newline="\n") | 377 | history.write_text(json.dumps(docs), encoding="utf-8", newline="\n") |
| 219 | if not trainer: | 378 | if not trainer: |
diff --git a/tools/dds_png.py b/tools/dds_png.py index dd59d7545..ec9b73a3c 100644 --- a/tools/dds_png.py +++ b/tools/dds_png.py | |||
| @@ -1,9 +1,11 @@ | |||
| 1 | """Pure standard-library DDS to PNG decoder and 2x box-filter downscaler. | 1 | """Pure standard-library DDS to PNG decoder and 2x box-filter downscaler. |
| 2 | 2 | ||
| 3 | Supports legacy and DX10 DDS headers across uncompressed 32-bit formats | 3 | Supports legacy and DX10 DDS headers across uncompressed 32-bit formats |
| 4 | (BGRA8, RGBA8, BGRX8, RGBX8, R10G10B10A2_UNORM, and arbitrary 32-bit RGB/RGBA bitmasks), the | 4 | (BGRA8, RGBA8, BGRX8, RGBX8, R10G10B10A2_UNORM/UINT/TYPELESS, and arbitrary 32-bit RGB/RGBA bitmasks), the |
| 5 | legacy 24-bit RGB layouts (BGR8/RGB8, e.g. the D3DFMT_R8G8B8 byte order), | 5 | legacy 24-bit RGB layouts (BGR8/RGB8, e.g. the D3DFMT_R8G8B8 byte order), the DX10 16-bit packed |
| 6 | and block-compressed formats (BC1, BC2, BC3, BC4, BC5, BC7). | 6 | B5G6R5_UNORM and B5G5R5A1_UNORM (5- and 6-bit channels widened by bit replication, as for BC1 endpoints), |
| 7 | the DX10 8-bit R8 and R8G8 formats (UNORM, SNORM, UINT, SINT), the 64-bit R16G16B16A16 UNORM, SNORM and | ||
| 8 | FLOAT formats, and block-compressed formats (BC1, BC2, BC3, BC4, BC5, BC7). | ||
| 7 | 9 | ||
| 8 | BC7 covers all eight modes. Decoding DXGI 97/98/99 (typeless, UNORM, UNORM_SRGB) | 10 | BC7 covers all eight modes. Decoding DXGI 97/98/99 (typeless, UNORM, UNORM_SRGB) |
| 9 | preserves the stored RGBA8 values. The reserved mode (no mode bit in the first | 11 | preserves the stored RGBA8 values. The reserved mode (no mode bit in the first |
| @@ -11,12 +13,19 @@ byte) decodes as transparent black. BC6H is not supported. | |||
| 11 | DXT2, DXT4 and premultiplied DX10 images are converted to straight alpha for PNG. | 13 | DXT2, DXT4 and premultiplied DX10 images are converted to straight alpha for PNG. |
| 12 | For tagged sRGB images, unpremultiplication and downscaling use linear light. The PNG stores sRGB bytes. | 14 | For tagged sRGB images, unpremultiplication and downscaling use linear light. The PNG stores sRGB bytes. |
| 13 | 15 | ||
| 14 | DX10 R16_FLOAT (54), R32_FLOAT (41) and R16G16B16A16_FLOAT (10) are read as linear values and | 16 | DX10 R16G16B16A16_UNORM (11) is normalized to RGBA8 with half-up rounding. R16_FLOAT (54), |
| 17 | R32_FLOAT (41) and R16G16B16A16_FLOAT (10) are read as linear values and | ||
| 15 | written like the UNORM formats, with no tone mapping or sRGB transfer: clamp to | 18 | written like the UNORM formats, with no tone mapping or sRGB transfer: clamp to |
| 16 | [0, 1], then round(v * 255) half up. +inf saturates to 255; -inf, negative values | 19 | [0, 1], then round(v * 255) half up. +inf saturates to 255; -inf, negative values |
| 17 | and NaN map to 0. The single-channel formats fill red, with green and blue 0 and alpha 255; | 20 | and NaN map to 0. The single-channel formats fill red, with green and blue 0 and alpha 255; |
| 18 | R16G16B16A16_FLOAT keeps its own alpha. | 21 | R16G16B16A16_FLOAT keeps its own alpha. |
| 19 | R11G11B10_FLOAT previews clamp RGB to [0, 1], map NaN to zero and use opaque alpha. | 22 | R16G16B16A16_SNORM (13) maps its signed normalized channels from [-1, 1] to [0, 255], |
| 23 | with both -32768 and -32767 representing -1.0. | ||
| 24 | R11G11B10_FLOAT and R9G9B9E5_SHAREDEXP (67, mantissa * 2^(exponent - 24) per channel) previews clamp RGB | ||
| 25 | to [0, 1] and use opaque alpha; NaN maps to zero for R11G11B10_FLOAT. | ||
| 26 | R8 and R8G8 previews fill red (and green), with blue 0 and alpha 255. SNORM maps [-1, 1] to [0, 255] like | ||
| 27 | BC4/BC5 SNORM (-128 and -127 are both -1.0); UINT keeps the byte; SINT adds 128 for display. | ||
| 28 | R10G10B10A2_UINT and _TYPELESS are shown like R10G10B10A2_UNORM: each field scaled from its bit width. | ||
| 20 | 29 | ||
| 21 | Usage: | 30 | Usage: |
| 22 | python -I tools/dds_png.py <in.dds> --info | 31 | python -I tools/dds_png.py <in.dds> --info |
| @@ -87,8 +96,21 @@ _DXGI_MAP: dict[int, str] = { | |||
| 87 | 93: "BGRX8", | 96 | 93: "BGRX8", |
| 88 | 26: "R11G11B10_FLOAT", | 97 | 26: "R11G11B10_FLOAT", |
| 89 | 41: "R32_FLOAT", | 98 | 41: "R32_FLOAT", |
| 99 | 49: "R8G8_UNORM", | ||
| 90 | 56: "R16_UNORM", | 100 | 56: "R16_UNORM", |
| 101 | 61: "R8_UNORM", | ||
| 102 | 11: "RGBA16_UNORM", | ||
| 103 | 13: "RGBA16_SNORM", | ||
| 104 | 51: "RG8_SNORM", | ||
| 105 | 50: "RG8_UINT", | ||
| 106 | 52: "RG8_SINT", | ||
| 107 | 63: "R8_SNORM", | ||
| 108 | 62: "R8_UINT", | ||
| 109 | 64: "R8_SINT", | ||
| 91 | 65: "A8_UNORM", | 110 | 65: "A8_UNORM", |
| 111 | 67: "R9G9B9E5_FLOAT", | ||
| 112 | 85: "B5G6R5_UNORM", | ||
| 113 | 86: "B5G5R5A1_UNORM", | ||
| 92 | 70: "BC1", | 114 | 70: "BC1", |
| 93 | 71: "BC1", | 115 | 71: "BC1", |
| 94 | 72: "BC1", | 116 | 72: "BC1", |
| @@ -265,7 +287,7 @@ def _parse_header_internal( | |||
| 265 | f"Truncated DX10 DDS header: {len(data)} bytes (need at least {DDS_DX10_HEADER_SIZE})" | 287 | f"Truncated DX10 DDS header: {len(data)} bytes (need at least {DDS_DX10_HEADER_SIZE})" |
| 266 | ) | 288 | ) |
| 267 | dxgi_format = struct.unpack_from("<I", data, 128)[0] | 289 | dxgi_format = struct.unpack_from("<I", data, 128)[0] |
| 268 | if dxgi_format == 24: # DXGI_FORMAT_R10G10B10A2_UNORM, R in the low bits. | 290 | if dxgi_format in (23, 24, 25): # R10G10B10A2_TYPELESS/UNORM/UINT, R in the low bits. |
| 269 | fmt = "RGBA8" | 291 | fmt = "RGBA8" |
| 270 | masks = (0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000) | 292 | masks = (0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000) |
| 271 | else: | 293 | else: |
| @@ -366,9 +388,16 @@ class _Plane(NamedTuple): | |||
| 366 | 388 | ||
| 367 | 389 | ||
| 368 | _TEXEL_BYTES = { | 390 | _TEXEL_BYTES = { |
| 369 | "RGBA8": 4, "BGRA8": 4, "BGRX8": 4, "RGBX8": 4, "R11G11B10_FLOAT": 4, | 391 | "RGBA8": 4, "BGRA8": 4, "BGRX8": 4, "RGBX8": 4, |
| 392 | "R11G11B10_FLOAT": 4, "R9G9B9E5_FLOAT": 4, | ||
| 370 | "BGR8": 3, "RGB8": 3, "R16_UNORM": 2, "A8_UNORM": 1, | 393 | "BGR8": 3, "RGB8": 3, "R16_UNORM": 2, "A8_UNORM": 1, |
| 371 | "R32_FLOAT": 4, | 394 | "R32_FLOAT": 4, "R8_UNORM": 1, "R8G8_UNORM": 2, |
| 395 | "RGBA16_UNORM": 8, "RGBA16_SNORM": 8, | ||
| 396 | "B5G6R5_UNORM": 2, "B5G5R5A1_UNORM": 2, | ||
| 397 | "RG8_SNORM": 2, | ||
| 398 | "RG8_UINT": 2, "RG8_SINT": 2, | ||
| 399 | "R8_SNORM": 1, | ||
| 400 | "R8_UINT": 1, "R8_SINT": 1, | ||
| 372 | **{fmt: layout[0] for fmt, layout in _HALF_FLOAT_LAYOUT.items()}, | 401 | **{fmt: layout[0] for fmt, layout in _HALF_FLOAT_LAYOUT.items()}, |
| 373 | } | 402 | } |
| 374 | 403 | ||
| @@ -576,6 +605,32 @@ def _decode_uncompressed_24( | |||
| 576 | return bytes(out) | 605 | return bytes(out) |
| 577 | 606 | ||
| 578 | 607 | ||
| 608 | def _decode_packed_16(payload: memoryview, width: int, height: int, fmt: str, pitch: int) -> bytes: | ||
| 609 | """Decode DXGI B5G6R5_UNORM or B5G5R5A1_UNORM pixels to RGBA8.""" | ||
| 610 | row_bytes = width * 2 | ||
| 611 | pitch = pitch or row_bytes | ||
| 612 | if pitch < row_bytes: | ||
| 613 | raise DdsError(f"Invalid {fmt} row pitch: {pitch} bytes (need at least {row_bytes})") | ||
| 614 | expected = (height - 1) * pitch + row_bytes | ||
| 615 | if len(payload) < expected: | ||
| 616 | raise DdsError(f"Truncated {fmt} payload: {len(payload)} bytes (need {expected})") | ||
| 617 | |||
| 618 | out = bytearray(width * height * 4) | ||
| 619 | dst = 0 | ||
| 620 | for start in range(0, height * pitch, pitch): | ||
| 621 | for (pixel,) in struct.iter_unpack("<H", payload[start:start + row_bytes]): | ||
| 622 | if fmt == "B5G6R5_UNORM": | ||
| 623 | r, g, b = (pixel >> 11) & 0x1F, (pixel >> 5) & 0x3F, pixel & 0x1F | ||
| 624 | out[dst:dst + 4] = bytes(((r << 3) | (r >> 2), (g << 2) | (g >> 4), | ||
| 625 | (b << 3) | (b >> 2), 255)) | ||
| 626 | else: | ||
| 627 | r, g, b = (pixel >> 10) & 0x1F, (pixel >> 5) & 0x1F, pixel & 0x1F | ||
| 628 | out[dst:dst + 4] = bytes(((r << 3) | (r >> 2), (g << 3) | (g >> 2), | ||
| 629 | (b << 3) | (b >> 2), 255 if pixel & 0x8000 else 0)) | ||
| 630 | dst += 4 | ||
| 631 | return bytes(out) | ||
| 632 | |||
| 633 | |||
| 579 | def _bc_interp_lut(v0: int, v1: int) -> tuple[int, int, int, int, int, int, int, int]: | 634 | def _bc_interp_lut(v0: int, v1: int) -> tuple[int, int, int, int, int, int, int, int]: |
| 580 | """Build the 8-entry BC3-alpha / BC4 / BC5 unsigned interpolation table.""" | 635 | """Build the 8-entry BC3-alpha / BC4 / BC5 unsigned interpolation table.""" |
| 581 | if v0 > v1: | 636 | if v0 > v1: |
| @@ -1055,8 +1110,33 @@ def _decode_r11g11b10(payload: memoryview, width: int, height: int, pitch: int) | |||
| 1055 | return bytes(rgba) | 1110 | return bytes(rgba) |
| 1056 | 1111 | ||
| 1057 | 1112 | ||
| 1058 | def _decode_single_channel(payload: memoryview, width: int, height: int, pitch: int, fmt: str) -> bytes: | 1113 | def _decode_r9g9b9e5(payload: memoryview, width: int, height: int, pitch: int) -> bytes: |
| 1059 | """Red-only R16_UNORM/R32_FLOAT and alpha-only A8_UNORM.""" | 1114 | """Decode DXGI R9G9B9E5_SHAREDEXP, clamping its shared-exponent RGB values to [0, 1].""" |
| 1115 | row_bytes = width * 4 | ||
| 1116 | pitch = pitch or row_bytes | ||
| 1117 | if pitch < row_bytes: | ||
| 1118 | raise DdsError(f"Invalid R9G9B9E5_FLOAT row pitch: {pitch} bytes (need at least {row_bytes})") | ||
| 1119 | expected = (height - 1) * pitch + row_bytes | ||
| 1120 | if len(payload) < expected: | ||
| 1121 | raise DdsError(f"Truncated R9G9B9E5_FLOAT payload: {len(payload)} bytes (need {expected})") | ||
| 1122 | |||
| 1123 | rgba = bytearray(width * height * 4) | ||
| 1124 | rgba[3::4] = b"\xff" * (width * height) | ||
| 1125 | dst = 0 | ||
| 1126 | for start in range(0, height * pitch, pitch): | ||
| 1127 | for (pixel,) in struct.iter_unpack("<I", payload[start:start + row_bytes]): | ||
| 1128 | exponent = (pixel >> 27) & 0x1F | ||
| 1129 | scale = exponent - 24 | ||
| 1130 | for shift in (0, 9, 18): | ||
| 1131 | value = math.ldexp((pixel >> shift) & 0x1FF, scale) | ||
| 1132 | rgba[dst] = 255 if value >= 1.0 else int(value * 255.0 + 0.5) | ||
| 1133 | dst += 1 | ||
| 1134 | dst += 1 | ||
| 1135 | return bytes(rgba) | ||
| 1136 | |||
| 1137 | |||
| 1138 | def _decode_channels(payload: memoryview, width: int, height: int, pitch: int, fmt: str) -> bytes: | ||
| 1139 | """Preview R, RG and alpha-only texels with zero for absent color channels.""" | ||
| 1060 | bpp = _TEXEL_BYTES[fmt] | 1140 | bpp = _TEXEL_BYTES[fmt] |
| 1061 | row_bytes = width * bpp | 1141 | row_bytes = width * bpp |
| 1062 | pitch = pitch or row_bytes | 1142 | pitch = pitch or row_bytes |
| @@ -1072,7 +1152,22 @@ def _decode_single_channel(payload: memoryview, width: int, height: int, pitch: | |||
| 1072 | dst = 0 | 1152 | dst = 0 |
| 1073 | for start in range(0, height * pitch, pitch): | 1153 | for start in range(0, height * pitch, pitch): |
| 1074 | row = payload[start:start + row_bytes] | 1154 | row = payload[start:start + row_bytes] |
| 1075 | if fmt == "R16_UNORM": | 1155 | if fmt in ("R8_UNORM", "R8G8_UNORM"): |
| 1156 | for channel in range(bpp): | ||
| 1157 | rgba[dst + channel:dst + width * 4:4] = row[channel::bpp] | ||
| 1158 | dst += width * 4 | ||
| 1159 | elif fmt == "R8_UINT": | ||
| 1160 | rgba[dst:dst + 4 * width:4] = row | ||
| 1161 | dst += 4 * width | ||
| 1162 | elif fmt == "R8_SINT": | ||
| 1163 | for (v,) in struct.iter_unpack("<b", row): | ||
| 1164 | rgba[dst] = v + 128 | ||
| 1165 | dst += 4 | ||
| 1166 | elif fmt == "R8_SNORM": | ||
| 1167 | for (v,) in struct.iter_unpack("<b", row): | ||
| 1168 | rgba[dst] = int(round((max(-127, v) / 127.0 * 0.5 + 0.5) * 255.0)) | ||
| 1169 | dst += 4 | ||
| 1170 | elif fmt == "R16_UNORM": | ||
| 1076 | for (v,) in struct.iter_unpack("<H", row): | 1171 | for (v,) in struct.iter_unpack("<H", row): |
| 1077 | rgba[dst] = (v * 255 + 32767) // 65535 | 1172 | rgba[dst] = (v * 255 + 32767) // 65535 |
| 1078 | dst += 4 | 1173 | dst += 4 |
| @@ -1089,6 +1184,97 @@ def _decode_single_channel(payload: memoryview, width: int, height: int, pitch: | |||
| 1089 | return bytes(rgba) | 1184 | return bytes(rgba) |
| 1090 | 1185 | ||
| 1091 | 1186 | ||
| 1187 | def _decode_rgba16_unorm(payload: memoryview, width: int, height: int, pitch: int) -> bytes: | ||
| 1188 | """Decode DXGI R16G16B16A16_UNORM to RGBA8 with half-up normalization.""" | ||
| 1189 | row_bytes = width * 8 | ||
| 1190 | pitch = pitch or row_bytes | ||
| 1191 | if pitch < row_bytes: | ||
| 1192 | raise DdsError(f"Invalid RGBA16_UNORM row pitch: {pitch} bytes (need at least {row_bytes})") | ||
| 1193 | expected = (height - 1) * pitch + row_bytes | ||
| 1194 | if len(payload) < expected: | ||
| 1195 | raise DdsError(f"Truncated RGBA16_UNORM payload: {len(payload)} bytes (need {expected})") | ||
| 1196 | |||
| 1197 | rgba = bytearray(width * height * 4) | ||
| 1198 | dst = 0 | ||
| 1199 | for start in range(0, height * pitch, pitch): | ||
| 1200 | for (r, g, b, a) in struct.iter_unpack("<4H", payload[start:start + row_bytes]): | ||
| 1201 | rgba[dst:dst + 4] = bytes(((r * 255 + 32767) // 65535, | ||
| 1202 | (g * 255 + 32767) // 65535, | ||
| 1203 | (b * 255 + 32767) // 65535, | ||
| 1204 | (a * 255 + 32767) // 65535)) | ||
| 1205 | dst += 4 | ||
| 1206 | return bytes(rgba) | ||
| 1207 | |||
| 1208 | |||
| 1209 | def _decode_rgba16_snorm(payload: memoryview, width: int, height: int, pitch: int) -> bytes: | ||
| 1210 | """Decode DXGI R16G16B16A16_SNORM into a displayable RGBA8 representation.""" | ||
| 1211 | row_bytes = width * 8 | ||
| 1212 | pitch = pitch or row_bytes | ||
| 1213 | if pitch < row_bytes: | ||
| 1214 | raise DdsError(f"Invalid RGBA16_SNORM row pitch: {pitch} bytes (need at least {row_bytes})") | ||
| 1215 | expected = (height - 1) * pitch + row_bytes | ||
| 1216 | if len(payload) < expected: | ||
| 1217 | raise DdsError(f"Truncated RGBA16_SNORM payload: {len(payload)} bytes (need {expected})") | ||
| 1218 | |||
| 1219 | rgba = bytearray(width * height * 4) | ||
| 1220 | dst = 0 | ||
| 1221 | for start in range(0, height * pitch, pitch): | ||
| 1222 | for (r, g, b, a) in struct.iter_unpack("<4h", payload[start:start + row_bytes]): | ||
| 1223 | # SNORM maps -32768 and -32767 to -1.0; the preview maps [-1, 1] to [0, 255]. | ||
| 1224 | channels = (max(r, -32767), max(g, -32767), max(b, -32767), max(a, -32767)) | ||
| 1225 | rgba[dst:dst + 4] = bytes((((v + 32767) * 255 + 32767) // 65534) for v in channels) | ||
| 1226 | dst += 4 | ||
| 1227 | return bytes(rgba) | ||
| 1228 | |||
| 1229 | |||
| 1230 | def _decode_rg8_snorm(payload: memoryview, width: int, height: int, pitch: int) -> bytes: | ||
| 1231 | """Decode DXGI R8G8_SNORM to red/green preview channels with opaque alpha.""" | ||
| 1232 | row_bytes = width * 2 | ||
| 1233 | pitch = pitch or row_bytes | ||
| 1234 | if pitch < row_bytes: | ||
| 1235 | raise DdsError(f"Invalid R8G8_SNORM row pitch: {pitch} bytes (need at least {row_bytes})") | ||
| 1236 | expected = (height - 1) * pitch + row_bytes | ||
| 1237 | if len(payload) < expected: | ||
| 1238 | raise DdsError(f"Truncated R8G8_SNORM payload: {len(payload)} bytes (need {expected})") | ||
| 1239 | |||
| 1240 | def to_u8(value: int) -> int: | ||
| 1241 | return int(round((max(-127, value) / 127.0 * 0.5 + 0.5) * 255.0)) | ||
| 1242 | |||
| 1243 | rgba = bytearray(width * height * 4) | ||
| 1244 | rgba[3::4] = b"\xff" * (width * height) | ||
| 1245 | dst = 0 | ||
| 1246 | for start in range(0, height * pitch, pitch): | ||
| 1247 | row = payload[start:start + row_bytes] | ||
| 1248 | for red, green in struct.iter_unpack("<bb", row): | ||
| 1249 | rgba[dst:dst + 2] = bytes((to_u8(red), to_u8(green))) | ||
| 1250 | dst += 4 | ||
| 1251 | return bytes(rgba) | ||
| 1252 | |||
| 1253 | |||
| 1254 | def _decode_rg8_integer(payload: memoryview, width: int, height: int, pitch: int, fmt: str) -> bytes: | ||
| 1255 | """Preview DXGI R8G8_UINT as bytes and R8G8_SINT by offsetting [-128, 127] to [0, 255].""" | ||
| 1256 | row_bytes = width * 2 | ||
| 1257 | pitch = pitch or row_bytes | ||
| 1258 | if pitch < row_bytes: | ||
| 1259 | raise DdsError(f"Invalid {fmt} row pitch: {pitch} bytes (need at least {row_bytes})") | ||
| 1260 | expected = (height - 1) * pitch + row_bytes | ||
| 1261 | if len(payload) < expected: | ||
| 1262 | raise DdsError(f"Truncated {fmt} payload: {len(payload)} bytes (need {expected})") | ||
| 1263 | |||
| 1264 | rgba = bytearray(width * height * 4) | ||
| 1265 | rgba[3::4] = b"\xff" * (width * height) | ||
| 1266 | dst = 0 | ||
| 1267 | unpack = struct.Struct("<BB").iter_unpack if fmt == "RG8_UINT" else struct.Struct("<bb").iter_unpack | ||
| 1268 | for start in range(0, height * pitch, pitch): | ||
| 1269 | for red, green in unpack(payload[start:start + row_bytes]): | ||
| 1270 | if fmt == "RG8_SINT": | ||
| 1271 | red += 128 | ||
| 1272 | green += 128 | ||
| 1273 | rgba[dst:dst + 2] = bytes((red, green)) | ||
| 1274 | dst += 4 | ||
| 1275 | return bytes(rgba) | ||
| 1276 | |||
| 1277 | |||
| 1092 | def _bc7_read_indices(bits: int, index_bits: int, is_anchor: tuple[int, ...]) -> tuple[list[int], int]: | 1278 | def _bc7_read_indices(bits: int, index_bits: int, is_anchor: tuple[int, ...]) -> tuple[list[int], int]: |
| 1093 | """Read 16 LSB-first pixel indices; anchor pixels omit their implicit zero MSB.""" | 1279 | """Read 16 LSB-first pixel indices; anchor pixels omit their implicit zero MSB.""" |
| 1094 | indices = [] | 1280 | indices = [] |
| @@ -1248,6 +1434,12 @@ def _decode_plane(data: bytes | bytearray | memoryview, plane: _Plane, info: _Dd | |||
| 1248 | 1434 | ||
| 1249 | if fmt in ("RGBA8", "BGRA8", "BGRX8", "RGBX8"): | 1435 | if fmt in ("RGBA8", "BGRA8", "BGRX8", "RGBX8"): |
| 1250 | rgba = _decode_uncompressed_32(payload, width, height, fmt, masks, pitch) | 1436 | rgba = _decode_uncompressed_32(payload, width, height, fmt, masks, pitch) |
| 1437 | elif fmt == "RGBA16_UNORM": | ||
| 1438 | rgba = _decode_rgba16_unorm(payload, width, height, pitch) | ||
| 1439 | elif fmt == "RGBA16_SNORM": | ||
| 1440 | rgba = _decode_rgba16_snorm(payload, width, height, pitch) | ||
| 1441 | elif fmt in ("B5G6R5_UNORM", "B5G5R5A1_UNORM"): | ||
| 1442 | rgba = _decode_packed_16(payload, width, height, fmt, pitch) | ||
| 1251 | elif fmt in _HALF_FLOAT_LAYOUT: | 1443 | elif fmt in _HALF_FLOAT_LAYOUT: |
| 1252 | rgba = _decode_half_float(payload, width, height, fmt, pitch) | 1444 | rgba = _decode_half_float(payload, width, height, fmt, pitch) |
| 1253 | elif fmt in _RGB24_LAYOUTS.values(): | 1445 | elif fmt in _RGB24_LAYOUTS.values(): |
| @@ -1269,8 +1461,14 @@ def _decode_plane(data: bytes | bytearray | memoryview, plane: _Plane, info: _Dd | |||
| 1269 | rgba = _decode_bc5(payload, 0, width, height, signed=True) | 1461 | rgba = _decode_bc5(payload, 0, width, height, signed=True) |
| 1270 | elif fmt == "R11G11B10_FLOAT": | 1462 | elif fmt == "R11G11B10_FLOAT": |
| 1271 | rgba = _decode_r11g11b10(payload, width, height, pitch) | 1463 | rgba = _decode_r11g11b10(payload, width, height, pitch) |
| 1272 | elif fmt in ("R16_UNORM", "R32_FLOAT", "A8_UNORM"): | 1464 | elif fmt == "RG8_SNORM": |
| 1273 | rgba = _decode_single_channel(payload, width, height, pitch, fmt) | 1465 | rgba = _decode_rg8_snorm(payload, width, height, pitch) |
| 1466 | elif fmt in ("RG8_UINT", "RG8_SINT"): | ||
| 1467 | rgba = _decode_rg8_integer(payload, width, height, pitch, fmt) | ||
| 1468 | elif fmt == "R9G9B9E5_FLOAT": | ||
| 1469 | rgba = _decode_r9g9b9e5(payload, width, height, pitch) | ||
| 1470 | elif fmt in ("R8_UNORM", "R8G8_UNORM", "R8_SNORM", "R8_UINT", "R8_SINT", "R16_UNORM", "R32_FLOAT", "A8_UNORM"): | ||
| 1471 | rgba = _decode_channels(payload, width, height, pitch, fmt) | ||
| 1274 | elif fmt == "BC7": | 1472 | elif fmt == "BC7": |
| 1275 | rgba = _decode_bc7(payload, 0, width, height) | 1473 | rgba = _decode_bc7(payload, 0, width, height) |
| 1276 | else: | 1474 | else: |
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 4311f3100..b10de728e 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py | |||
| @@ -120,6 +120,33 @@ PC_TAIL_SET, PC_TAIL_BINDING = 1, 0 | |||
| 120 | F16_HALVES = False | 120 | F16_HALVES = False |
| 121 | F16_HALF_TOP = 29 | 121 | F16_HALF_TOP = 29 |
| 122 | OPT_SPIRV = False # --opt: run tools/spirv_opt.py basic-block peephole pass on emitted SPIR-V (#884) | 122 | OPT_SPIRV = False # --opt: run tools/spirv_opt.py basic-block peephole pass on emitted SPIR-V (#884) |
| 123 | # --address-guard: every access through heap_base + VA is checked against what the runtime backs (docs/d3d12_vulkan.md, | ||
| 124 | # "Address guard"); one that fails reads 0 and drops its store. The runtime (LEONIDA_ADDRESS_GUARD=1) writes a header | ||
| 125 | # at arena offset GUARD_HEADER: GUARD_MAGIC (u64), the arena's size (u64, offsets below it pass without a lookup), the | ||
| 126 | # page table's address minus heap_base (u64), a count of refused accesses (u32, the shaders add to it) and the last | ||
| 127 | # refused offset (u64). Without the magic every access passes, so a guarded module runs unchanged on a runtime with | ||
| 128 | # the guard off. A refused load reads the zero area, a refused store or atomic writes the dump area; both are in the | ||
| 129 | # arena's reserved first 512 KiB. Shared with runtime/src/address_guard.h. | ||
| 130 | ADDRESS_GUARD = False | ||
| 131 | # --address-guard (diagnostics): the module's id, FNV-1a of its file stem, which a refused access stores in the header | ||
| 132 | # (+28) next to its offset, so the runtime's refusal line names the module. Set by _translate for each file. | ||
| 133 | GUARD_MODULE_ID = 0 | ||
| 134 | |||
| 135 | |||
| 136 | def fnv1a32(text): | ||
| 137 | """32-bit FNV-1a of a UTF-8 string (the address guard's module id; tools/address_guard.py --module maps names).""" | ||
| 138 | h = 0x811C9DC5 | ||
| 139 | for b in text.encode("utf-8"): | ||
| 140 | h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF | ||
| 141 | return h | ||
| 142 | |||
| 143 | |||
| 144 | GUARD_HEADER = 0x70000 | ||
| 145 | GUARD_ZERO = 0x71000 | ||
| 146 | GUARD_DUMP = 0x78000 | ||
| 147 | GUARD_MAGIC = int.from_bytes(b"LGUARD01", "little") | ||
| 148 | GUARD_L1 = 1 << 16 # level-1 entries: bits 47..32 of the 48-bit offset (4 GiB each) | ||
| 149 | GUARD_BLOCK_WORDS = 1 << 15 # level-2 block: one bit per 4 KiB page of a 4 GiB chunk | ||
| 123 | 150 | ||
| 124 | 151 | ||
| 125 | # The heap base as one %ulong, in the entry block of %main: the push constants don't change during the invocation, and | 152 | # The heap base as one %ulong, in the entry block of %main: the push constants don't change during the invocation, and |
| @@ -132,6 +159,109 @@ HEAP_BASE_ENTRY = ["%heap_base_lo = OpLoad %uint %ud_base_lo_p", | |||
| 132 | "%heap_base = OpBitwiseOr %ulong %heap_base_hi_sh %heap_base_lo64"] | 159 | "%heap_base = OpBitwiseOr %ulong %heap_base_hi_sh %heap_base_lo64"] |
| 133 | 160 | ||
| 134 | 161 | ||
| 162 | def guard_entry(cl, cu): | ||
| 163 | """--address-guard: the entry-block lines that read the runtime's guard header at heap_base + GUARD_HEADER once | ||
| 164 | per invocation: %gd_on (the magic is there), %gd_limit (the arena's size) and %gd_table (the page table's address | ||
| 165 | minus heap_base). The header is in the arena's reserved range, so the read itself is always backed.""" | ||
| 166 | L = [f"%gd_hp = OpIAdd %ulong %heap_base {cl(GUARD_HEADER)}", | ||
| 167 | "%gd_p = OpConvertUToPtr %_ptr_PSB_arr %gd_hp"] | ||
| 168 | for i in range(6): | ||
| 169 | L += [f"%gd_w{i}p = OpAccessChain %_ptr_PSB_uint %gd_p {cu(i)}", f"%gd_w{i} = OpLoad %uint %gd_w{i}p Aligned 4"] | ||
| 170 | for name, lo, hi in (("magic", 0, 1), ("limit", 2, 3), ("table", 4, 5)): | ||
| 171 | L += [f"%gd_{name}_l = OpUConvert %ulong %gd_w{lo}", f"%gd_{name}_h = OpUConvert %ulong %gd_w{hi}", | ||
| 172 | f"%gd_{name}_s = OpShiftLeftLogical %ulong %gd_{name}_h %c64_32", | ||
| 173 | f"%gd_{name} = OpBitwiseOr %ulong %gd_{name}_s %gd_{name}_l"] | ||
| 174 | L.append(f"%gd_on = OpIEqual %bool %gd_magic {cl(GUARD_MAGIC)}") | ||
| 175 | return L | ||
| 176 | |||
| 177 | |||
| 178 | def guard_function(cl, cu): | ||
| 179 | """--address-guard: %guard_fn(heap_base, on, limit, table, offset, delta, sink) -> host address. | ||
| 180 | |||
| 181 | `offset` is the access's sign-extended 48-bit heap offset and `delta` its span minus one. Without the runtime's | ||
| 182 | guard (`on` false), or when [offset, offset + delta] is below `limit` (the arena, all of it backed), the result is | ||
| 183 | heap_base + offset after one compare. Otherwise the page table at heap_base + table decides, per 4 KiB page of the | ||
| 184 | first and the last byte: level 1 is GUARD_L1 words indexed by offset bits 47..32 (the level-2 block of that 4 GiB | ||
| 185 | chunk: 0 none backed, 1 all), level 2 is one bit per page (bits 31..12), GUARD_BLOCK_WORDS words a block, after | ||
| 186 | level 1. A refused access counts itself in the header and goes to heap_base + sink + (offset & 0xFFF).""" | ||
| 187 | ul = "%ulong" | ||
| 188 | L = ["%guard_fn = OpFunction %ulong None %fn_guard", | ||
| 189 | "%ga_hb = OpFunctionParameter %ulong", "%ga_on = OpFunctionParameter %bool", | ||
| 190 | "%ga_lim = OpFunctionParameter %ulong", "%ga_tab = OpFunctionParameter %ulong", | ||
| 191 | "%ga_off = OpFunctionParameter %ulong", "%ga_delta = OpFunctionParameter %ulong", | ||
| 192 | "%ga_sink = OpFunctionParameter %ulong", | ||
| 193 | "%ga_entry = OpLabel", | ||
| 194 | f"%ga_end = OpIAdd {ul} %ga_off %ga_delta", | ||
| 195 | f"%ga_a = OpULessThan %bool %ga_off %ga_lim", | ||
| 196 | f"%ga_b = OpULessThan %bool %ga_end %ga_lim", | ||
| 197 | "%ga_in = OpLogicalAnd %bool %ga_a %ga_b", | ||
| 198 | "%ga_off_n = OpLogicalNot %bool %ga_on", | ||
| 199 | "%ga_pass = OpLogicalOr %bool %ga_in %ga_off_n", | ||
| 200 | "OpSelectionMerge %ga_m None", | ||
| 201 | "OpBranchConditional %ga_pass %ga_m %ga_slow", | ||
| 202 | "%ga_slow = OpLabel", | ||
| 203 | f"%ga_tb = OpIAdd {ul} %ga_hb %ga_tab"] | ||
| 204 | |||
| 205 | def bit(k, o): | ||
| 206 | """Lines for %ga_bit{k}: the page-table bit of heap offset id `o`.""" | ||
| 207 | return [f"%ga_c{k} = OpShiftRightLogical {ul} {o} %c64_32", | ||
| 208 | f"%ga_ci{k} = OpBitwiseAnd {ul} %ga_c{k} {cl(GUARD_L1 - 1)}", | ||
| 209 | f"%ga_ca{k} = OpShiftLeftLogical {ul} %ga_ci{k} {cl(2)}", | ||
| 210 | f"%ga_cp{k} = OpIAdd {ul} %ga_tb %ga_ca{k}", | ||
| 211 | f"%ga_cq{k} = OpConvertUToPtr %_ptr_PSB_uint %ga_cp{k}", | ||
| 212 | f"%ga_e{k} = OpLoad %uint %ga_cq{k} Aligned 4", | ||
| 213 | f"%ga_e64{k} = OpUConvert {ul} %ga_e{k}", | ||
| 214 | f"%ga_pg{k} = OpShiftRightLogical {ul} {o} {cl(12)}", | ||
| 215 | f"%ga_pm{k} = OpBitwiseAnd {ul} %ga_pg{k} {cl(0xFFFFF)}", | ||
| 216 | f"%ga_pw{k} = OpShiftRightLogical {ul} %ga_pm{k} {cl(5)}", | ||
| 217 | f"%ga_eb{k} = OpIMul {ul} %ga_e64{k} {cl(GUARD_BLOCK_WORDS)}", | ||
| 218 | f"%ga_wi0{k} = OpIAdd {ul} %ga_eb{k} %ga_pw{k}", | ||
| 219 | f"%ga_wi{k} = OpIAdd {ul} %ga_wi0{k} {cl(GUARD_L1)}", | ||
| 220 | f"%ga_wa{k} = OpShiftLeftLogical {ul} %ga_wi{k} {cl(2)}", | ||
| 221 | f"%ga_wp{k} = OpIAdd {ul} %ga_tb %ga_wa{k}", | ||
| 222 | f"%ga_wq{k} = OpConvertUToPtr %_ptr_PSB_uint %ga_wp{k}", | ||
| 223 | f"%ga_w{k} = OpLoad %uint %ga_wq{k} Aligned 4", | ||
| 224 | f"%ga_pl{k} = OpUConvert %uint %ga_pm{k}", | ||
| 225 | f"%ga_sh{k} = OpBitwiseAnd %uint %ga_pl{k} {cu(31)}", | ||
| 226 | f"%ga_bs{k} = OpShiftRightLogical %uint %ga_w{k} %ga_sh{k}", | ||
| 227 | f"%ga_b1{k} = OpBitwiseAnd %uint %ga_bs{k} {cu(1)}", | ||
| 228 | f"%ga_bit{k} = OpINotEqual %bool %ga_b1{k} {cu(0)}"] | ||
| 229 | L += bit(0, "%ga_off") + bit(1, "%ga_end") | ||
| 230 | hdr = cl(GUARD_HEADER) | ||
| 231 | L += ["%ga_ok = OpLogicalAnd %bool %ga_bit0 %ga_bit1", | ||
| 232 | "OpSelectionMerge %ga_rm None", | ||
| 233 | "OpBranchConditional %ga_ok %ga_rm %ga_ref", | ||
| 234 | "%ga_ref = OpLabel", | ||
| 235 | # The refusal count (header +24) and the last refused offset (+32, low dword first): what the runtime logs. | ||
| 236 | f"%ga_h = OpIAdd {ul} %ga_hb {hdr}", | ||
| 237 | "%ga_hp = OpConvertUToPtr %_ptr_PSB_arr %ga_h", | ||
| 238 | f"%ga_cnt = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(6)}", | ||
| 239 | f"%ga_old = OpAtomicIAdd %uint %ga_cnt {cu(1)} {cu(0)} {cu(1)}", | ||
| 240 | "%ga_lo = OpUConvert %uint %ga_off", | ||
| 241 | "%ga_hs = OpShiftRightLogical %ulong %ga_off %c64_32", | ||
| 242 | "%ga_hi = OpUConvert %uint %ga_hs", | ||
| 243 | f"%ga_lp = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(8)}", | ||
| 244 | "OpStore %ga_lp %ga_lo Aligned 4", | ||
| 245 | f"%ga_hq = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(9)}", | ||
| 246 | "OpStore %ga_hq %ga_hi Aligned 4", | ||
| 247 | # The refusing module's id (+28, diagnostics): GUARD_MODULE_ID, FNV-1a of the translated file's stem. | ||
| 248 | f"%ga_ip = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(7)}", | ||
| 249 | f"OpStore %ga_ip {cu(GUARD_MODULE_ID)} Aligned 4", | ||
| 250 | "OpBranch %ga_rm", | ||
| 251 | "%ga_rm = OpLabel", | ||
| 252 | "OpBranch %ga_m", | ||
| 253 | "%ga_m = OpLabel", | ||
| 254 | "%ga_okp = OpPhi %bool %true %ga_entry %ga_ok %ga_rm", | ||
| 255 | f"%ga_good = OpIAdd {ul} %ga_hb %ga_off", | ||
| 256 | f"%ga_po = OpBitwiseAnd {ul} %ga_off {cl(0xFFF)}", | ||
| 257 | f"%ga_sb = OpIAdd {ul} %ga_hb %ga_sink", | ||
| 258 | f"%ga_bad = OpIAdd {ul} %ga_sb %ga_po", | ||
| 259 | f"%ga_r = OpSelect {ul} %ga_okp %ga_good %ga_bad", | ||
| 260 | "OpReturnValue %ga_r", | ||
| 261 | "OpFunctionEnd"] | ||
| 262 | return L | ||
| 263 | |||
| 264 | |||
| 135 | def pc_tail_chain(name, member, c): | 265 | def pc_tail_chain(name, member, c): |
| 136 | """`name` = pointer to push-constant tail member `member`, numbered as in %UserData (1-2 heap base, 3-4 code base, | 266 | """`name` = pointer to push-constant tail member `member`, numbered as in %UserData (1-2 heap base, 3-4 code base, |
| 137 | 5-6 --mesh-compute output address): a member of the push-constant block by default, member - 1 of the uniform | 267 | 5-6 --mesh-compute output address): a member of the push-constant block by default, member - 1 of the uniform |
| @@ -421,6 +551,7 @@ class Gen: | |||
| 421 | self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler) | 551 | self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler) |
| 422 | self.uses_storage3d = False | 552 | self.uses_storage3d = False |
| 423 | self.uses_heap = False | 553 | self.uses_heap = False |
| 554 | self.uses_guard = False # --address-guard: an access called %guard_fn (the entry block reads the header) | ||
| 424 | self.uses_codebase = False | 555 | self.uses_codebase = False |
| 425 | self.uses_pc_tail = False # --pc-tail-ubo and the shader reads the tail (set in assemble) | 556 | self.uses_pc_tail = False # --pc-tail-ubo and the shader reads the tail (set in assemble) |
| 426 | self.uses_long = False | 557 | self.uses_long = False |
| @@ -440,6 +571,8 @@ class Gen: | |||
| 440 | self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it | 571 | self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it |
| 441 | self.fmt_norm_fn = None # lines of the shared exact norm quotient for a run-time width (SHADER-849) | 572 | self.fmt_norm_fn = None # lines of the shared exact norm quotient for a run-time width (SHADER-849) |
| 442 | self.fmt_enc_fn = None # shared format encoder for stores through a dynamic V# | 573 | self.fmt_enc_fn = None # shared format encoder for stores through a dynamic V# |
| 574 | self.guard_fn = None # --address-guard: lines of %guard_fn, once an access needs it | ||
| 575 | self.guard_last = None # --address-guard: (guarded address, unguarded address) of the last host_addr | ||
| 443 | self.uses_fmt_tables = False # %fmt_desc_tab / %fmt_norm_rep_tab: a format's kind and channel widths | 576 | self.uses_fmt_tables = False # %fmt_desc_tab / %fmt_norm_rep_tab: a format's kind and channel widths |
| 444 | self.x_round_fns: dict[str, list[str]] = {} # emulate_inline: helper functions for x_round pre-barrier setup | 577 | self.x_round_fns: dict[str, list[str]] = {} # emulate_inline: helper functions for x_round pre-barrier setup |
| 445 | self.x_round_fn_types: dict[int, str] = {} # emulate_inline: arity -> OpTypeFunction id for x_round_fns | 578 | self.x_round_fn_types: dict[int, str] = {} # emulate_inline: arity -> OpTypeFunction id for x_round_fns |
| @@ -1596,8 +1729,14 @@ class Gen: | |||
| 1596 | def modify_f(self, f, a): | 1729 | def modify_f(self, f, a): |
| 1597 | return self.tof(self.modify(self.tou(f), a)) | 1730 | return self.tof(self.modify(self.tou(f), a)) |
| 1598 | 1731 | ||
| 1599 | def host_addr(self, xbox_va): | 1732 | def host_addr(self, xbox_va, kind="load", extent=4): |
| 1600 | """Add the sign-extended 48-bit effective VA to the heap base built in the entry block.""" | 1733 | """Add the sign-extended 48-bit effective VA to the heap base built in the entry block. |
| 1734 | |||
| 1735 | --address-guard: the address is checked against the runtime's page table first (guard_addr). `kind` is | ||
| 1736 | "load", "store" or "rmw" (an atomic): a refused load reads the zero area, a refused store or atomic the dump | ||
| 1737 | area. `extent` is the bytes the access spans from this address: an int, or for a run-time span a callable | ||
| 1738 | that emits it and returns the %ulong id of extent - 1 (guard_delta), called only with the guard so the | ||
| 1739 | unguarded module stays byte for byte the same. Its first and last byte are checked.""" | ||
| 1601 | # V# truncates device_address - heap_base to 48 bits, including when an import lies below the heap. | 1740 | # V# truncates device_address - heap_base to 48 bits, including when an import lies below the heap. |
| 1602 | # Extend after adding byte offsets. Console user VAs and full-width root VAs already fit signed 48 bits. | 1741 | # Extend after adding byte offsets. Console user VAs and full-width root VAs already fit signed 48 bits. |
| 1603 | shift = self.cu(16) | 1742 | shift = self.cu(16) |
| @@ -1607,8 +1746,77 @@ class Gen: | |||
| 1607 | self.emit(f"{r} = OpIAdd %ulong %heap_base {offset}") | 1746 | self.emit(f"{r} = OpIAdd %ulong %heap_base {offset}") |
| 1608 | self.uses_heap = True | 1747 | self.uses_heap = True |
| 1609 | self.cu(1), self.cu(2) # member indices of the push-constant block, declared before assembly | 1748 | self.cu(1), self.cu(2) # member indices of the push-constant block, declared before assembly |
| 1749 | if not ADDRESS_GUARD: | ||
| 1750 | return r | ||
| 1751 | return self.guard_addr(offset, r, kind, extent) | ||
| 1752 | |||
| 1753 | def guard_delta(self, n, step): | ||
| 1754 | """--address-guard: the %ulong id of (bytes spanned - 1) for n dwords (an int, or a %uint id of at least 1), | ||
| 1755 | linear (step None) or each `step` bytes apart (a %uint id: a swizzled buffer access, buf_dword_ptr).""" | ||
| 1756 | if isinstance(n, int) and (step is None or n == 1): | ||
| 1757 | return self.cl(4 * n - 1) | ||
| 1758 | if isinstance(n, int): | ||
| 1759 | n1 = self.cu(n - 1) | ||
| 1760 | else: | ||
| 1761 | zero, dec, n1 = self.tmp(), self.tmp(), self.tmp() | ||
| 1762 | self.emit(f"{zero} = OpIEqual %bool {n} {self.cu(0)}") | ||
| 1763 | self.emit(f"{dec} = OpISub %uint {n} {self.cu(1)}") | ||
| 1764 | self.emit(f"{n1} = OpSelect %uint {zero} {self.cu(0)} {dec}") | ||
| 1765 | m, m64, d = self.tmp(), self.tmp(), self.tmp() | ||
| 1766 | self.emit(f"{m} = OpIMul %uint {n1} {step if step is not None else self.cu(4)}") | ||
| 1767 | self.emit(f"{m64} = OpUConvert %ulong {m}") | ||
| 1768 | self.emit(f"{d} = OpIAdd %ulong {m64} {self.cl(3)}") | ||
| 1769 | return d | ||
| 1770 | |||
| 1771 | def guard_addr(self, offset, unguarded, kind, extent): | ||
| 1772 | """--address-guard: the host address of the access at heap offset `offset` (sign-extended 48 bits): itself | ||
| 1773 | when the runtime backs its first and last byte (or the runtime's guard is off), else a place in the arena's | ||
| 1774 | zero area (a load) or dump area (a store, an atomic) at the same offset within a 4 KiB page, so alignment | ||
| 1775 | holds. One call of %guard_fn (an arena offset passes on a compare; any other looks up two page-table bits).""" | ||
| 1776 | self.uses_guard = True | ||
| 1777 | delta = self.cl(extent - 1) if isinstance(extent, int) else extent() | ||
| 1778 | sink = self.cl(GUARD_ZERO if kind == "load" else GUARD_DUMP) | ||
| 1779 | if self.guard_fn is None: | ||
| 1780 | self.guard_fn = guard_function(self.cl, self.cu) | ||
| 1781 | guard_entry(self.cl, self.cu) # registers the entry block's constants while they can still be declared | ||
| 1782 | r = self.tmp() | ||
| 1783 | self.emit(f"{r} = OpFunctionCall %ulong %guard_fn %heap_base %gd_on %gd_limit %gd_table {offset} {delta} {sink}") | ||
| 1784 | self.guard_last = (r, unguarded) | ||
| 1610 | return r | 1785 | return r |
| 1611 | 1786 | ||
| 1787 | def sub_dwords(self, nbytes, b3): | ||
| 1788 | """--address-guard: the dwords a 1- or 2-byte access at byte `b3` (a %uint id) of a dword reads: 1, or 2 for | ||
| 1789 | a 2-byte access at byte 3 (an int or a %uint id).""" | ||
| 1790 | if nbytes == 1: | ||
| 1791 | return 1 | ||
| 1792 | cross, n = self.tmp(), self.tmp() | ||
| 1793 | self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") | ||
| 1794 | self.emit(f"{n} = OpSelect %uint {cross} {self.cu(2)} {self.cu(1)}") | ||
| 1795 | return n | ||
| 1796 | |||
| 1797 | def store_element_dwords(self, fmt, fixed_fmt): | ||
| 1798 | """--address-guard: the whole dwords a typed buffer store of one element writes (at least 1: a 1- or 2-byte | ||
| 1799 | element is written through its own guarded dword): from the instruction's format, or the V#'s (`fmt`, a %uint | ||
| 1800 | id) at run time.""" | ||
| 1801 | if fixed_fmt is not None: | ||
| 1802 | return max(1, self.FORMATS.get(fixed_fmt, (4,))[0] // 4) | ||
| 1803 | size, q, n = self.fmt_size_of(fmt), self.tmp(), self.tmp() | ||
| 1804 | self.emit(f"{q} = OpShiftRightLogical %uint {size} {self.cu(2)}") | ||
| 1805 | self.emit(f"{n} = OpExtInst %uint %glsl UMax {q} {self.cu(1)}") | ||
| 1806 | return n | ||
| 1807 | |||
| 1808 | def guard_zero(self, value, ty="%uint"): | ||
| 1809 | """--address-guard: `value` (an atomic's result) or 0 when the last host_addr was refused: a refused atomic | ||
| 1810 | ran on the dump area, and what it returned from there means nothing. `value` unchanged without the guard.""" | ||
| 1811 | if not ADDRESS_GUARD or self.guard_last is None: | ||
| 1812 | return value | ||
| 1813 | r, unguarded = self.guard_last | ||
| 1814 | ok, out = self.tmp(), self.tmp() | ||
| 1815 | zero = self.cu(0) if ty == "%uint" else self.cl(0) | ||
| 1816 | self.emit(f"{ok} = OpIEqual %bool {r} {unguarded}") | ||
| 1817 | self.emit(f"{out} = OpSelect {ty} {ok} {value} {zero}") | ||
| 1818 | return out | ||
| 1819 | |||
| 1612 | def tof(self, u): | 1820 | def tof(self, u): |
| 1613 | """The %float with the bits of %uint u. Bitcasting a tou result back gives tou's argument (Gen.bitcast_from), | 1821 | """The %float with the bits of %uint u. Bitcasting a tou result back gives tou's argument (Gen.bitcast_from), |
| 1614 | so u must be a %uint and tou's argument a %float; an %int's bits go through int_bits.""" | 1822 | so u must be a %uint and tou's argument a %float; an %int's bits go through int_bits.""" |
| @@ -2336,7 +2544,7 @@ class Gen: | |||
| 2336 | self.emit(f"{f2} = OpISub %ulong {far} {self.cl(3)}") | 2544 | self.emit(f"{f2} = OpISub %ulong {far} {self.cl(3)}") |
| 2337 | self.emit(f"{sel} = OpSelect %ulong {cross} {f2} {va}") | 2545 | self.emit(f"{sel} = OpSelect %ulong {cross} {f2} {va}") |
| 2338 | va = sel | 2546 | va = sel |
| 2339 | p, sh = self.global_byte_ptr(va) | 2547 | p, sh = self.global_byte_ptr(va, "store" if store else "load") |
| 2340 | if store: | 2548 | if store: |
| 2341 | byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) | 2549 | byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) |
| 2342 | self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") | 2550 | self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") |
| @@ -2386,7 +2594,7 @@ class Gen: | |||
| 2386 | vd = a[0] | 2594 | vd = a[0] |
| 2387 | addr, _, in_b, raw_parts, step = self.buffer_address(a, mods, parts=True) | 2595 | addr, _, in_b, raw_parts, step = self.buffer_address(a, mods, parts=True) |
| 2388 | act = self.active_b() | 2596 | act = self.active_b() |
| 2389 | ptr, host = self.tmp(), self.host_addr(addr) | 2597 | ptr, host = self.tmp(), self.host_addr(addr, "load", lambda: self.guard_delta(n, step)) |
| 2390 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") | 2598 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") |
| 2391 | 2599 | ||
| 2392 | def guarded(cond, dwords): | 2600 | def guarded(cond, dwords): |
| @@ -2453,7 +2661,7 @@ class Gen: | |||
| 2453 | self.emit(f"{b64} = OpUConvert %ulong {b3}") | 2661 | self.emit(f"{b64} = OpUConvert %ulong {b3}") |
| 2454 | self.emit(f"{aligned} = OpISub %ulong {addr} {b64}") | 2662 | self.emit(f"{aligned} = OpISub %ulong {addr} {b64}") |
| 2455 | self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") | 2663 | self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") |
| 2456 | ptr, host = self.tmp(), self.host_addr(aligned) | 2664 | ptr, host = self.tmp(), self.host_addr(aligned, "load", lambda: self.guard_delta(self.sub_dwords(nbytes, b3), step)) |
| 2457 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") | 2665 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") |
| 2458 | p0, w0 = self.buf_dword_ptr(ptr, host, step, 0), self.tmp() | 2666 | p0, w0 = self.buf_dword_ptr(ptr, host, step, 0), self.tmp() |
| 2459 | self.emit(f"{w0} = OpLoad %uint {p0} Aligned 4") | 2667 | self.emit(f"{w0} = OpLoad %uint {p0} Aligned 4") |
| @@ -2957,7 +3165,7 @@ class Gen: | |||
| 2957 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") | 3165 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") |
| 2958 | self.emit(f"{lbl_do} = OpLabel") | 3166 | self.emit(f"{lbl_do} = OpLabel") |
| 2959 | ptr, p, init = self.tmp(), self.tmp(), self.tmp() | 3167 | ptr, p, init = self.tmp(), self.tmp(), self.tmp() |
| 2960 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") | 3168 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'rmw')}") |
| 2961 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") | 3169 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") |
| 2962 | self.emit(f"{init} = OpAtomicLoad %uint {p} {self.cu(1)} {self.cu(0)}") | 3170 | self.emit(f"{init} = OpAtomicLoad %uint {p} {self.cu(1)} {self.cu(0)}") |
| 2963 | self.emit(f"OpBranch {lbl_hdr}") | 3171 | self.emit(f"OpBranch {lbl_hdr}") |
| @@ -2975,6 +3183,7 @@ class Gen: | |||
| 2975 | self.emit(f"{lbl_cont} = OpLabel") | 3183 | self.emit(f"{lbl_cont} = OpLabel") |
| 2976 | self.emit(f"OpBranch {lbl_hdr}") | 3184 | self.emit(f"OpBranch {lbl_hdr}") |
| 2977 | self.emit(f"{lbl_exit} = OpLabel") | 3185 | self.emit(f"{lbl_exit} = OpLabel") |
| 3186 | cur = self.guard_zero(cur) | ||
| 2978 | self.emit(f"OpBranch {lbl_end}") | 3187 | self.emit(f"OpBranch {lbl_end}") |
| 2979 | self.emit(f"{lbl_end} = OpLabel") | 3188 | self.emit(f"{lbl_end} = OpLabel") |
| 2980 | old = self.tmp() | 3189 | old = self.tmp() |
| @@ -3022,7 +3231,7 @@ class Gen: | |||
| 3022 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") | 3231 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") |
| 3023 | self.emit(f"{lbl_do} = OpLabel") | 3232 | self.emit(f"{lbl_do} = OpLabel") |
| 3024 | ptr, p = self.tmp(), self.tmp() | 3233 | ptr, p = self.tmp(), self.tmp() |
| 3025 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") | 3234 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'rmw')}") |
| 3026 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") | 3235 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") |
| 3027 | if is_inc_dec: | 3236 | if is_inc_dec: |
| 3028 | res, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) | 3237 | res, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) |
| @@ -3035,6 +3244,7 @@ class Gen: | |||
| 3035 | self.emit(f"{res} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") | 3244 | self.emit(f"{res} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") |
| 3036 | else: | 3245 | else: |
| 3037 | self.emit(f"{res} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {val}") | 3246 | self.emit(f"{res} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {val}") |
| 3247 | res = self.guard_zero(res) | ||
| 3038 | self.emit(f"OpBranch {lbl_end}") | 3248 | self.emit(f"OpBranch {lbl_end}") |
| 3039 | self.emit(f"{lbl_end} = OpLabel") | 3249 | self.emit(f"{lbl_end} = OpLabel") |
| 3040 | self.emit(f"{old} = OpPhi %uint {res} {done_lbl} {self.cu(0)} {pre}") | 3250 | self.emit(f"{old} = OpPhi %uint {res} {done_lbl} {self.cu(0)} {pre}") |
| @@ -3086,13 +3296,14 @@ class Gen: | |||
| 3086 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") | 3296 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") |
| 3087 | self.emit(f"{lbl_do} = OpLabel") | 3297 | self.emit(f"{lbl_do} = OpLabel") |
| 3088 | ptr = self.tmp() | 3298 | ptr = self.tmp() |
| 3089 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") | 3299 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'rmw', 8)}") |
| 3090 | res = [] | 3300 | res = [] |
| 3091 | for w in range(2): | 3301 | for w in range(2): |
| 3092 | p, r = self.tmp(), self.tmp() | 3302 | p, r = self.tmp(), self.tmp() |
| 3093 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") | 3303 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") |
| 3094 | self.emit(f"{r} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") | 3304 | self.emit(f"{r} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") |
| 3095 | res.append(r) | 3305 | res.append(r) |
| 3306 | res = [self.guard_zero(r) for r in res] | ||
| 3096 | self.emit(f"OpBranch {lbl_end}") | 3307 | self.emit(f"OpBranch {lbl_end}") |
| 3097 | self.emit(f"{lbl_end} = OpLabel") | 3308 | self.emit(f"{lbl_end} = OpLabel") |
| 3098 | olds = [] | 3309 | olds = [] |
| @@ -3160,7 +3371,7 @@ class Gen: | |||
| 3160 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") | 3371 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") |
| 3161 | self.emit(f"{lbl_do} = OpLabel") | 3372 | self.emit(f"{lbl_do} = OpLabel") |
| 3162 | ptr, p = self.tmp(), self.tmp() | 3373 | ptr, p = self.tmp(), self.tmp() |
| 3163 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") | 3374 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'rmw')}") |
| 3164 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") | 3375 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") |
| 3165 | if is_inc_dec: | 3376 | if is_inc_dec: |
| 3166 | res_do, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) | 3377 | res_do, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) |
| @@ -3178,6 +3389,7 @@ class Gen: | |||
| 3178 | self.emit(f"{res_do} = OpAtomicExchange %uint {p} {self.cu(1)} {self.cu(0)} {val}") | 3389 | self.emit(f"{res_do} = OpAtomicExchange %uint {p} {self.cu(1)} {self.cu(0)} {val}") |
| 3179 | else: | 3390 | else: |
| 3180 | self.emit(f"{res_do} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {val}") | 3391 | self.emit(f"{res_do} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {val}") |
| 3392 | res_do = self.guard_zero(res_do) | ||
| 3181 | self.emit(f"OpBranch {lbl_end}") | 3393 | self.emit(f"OpBranch {lbl_end}") |
| 3182 | self.emit(f"{lbl_end} = OpLabel") | 3394 | self.emit(f"{lbl_end} = OpLabel") |
| 3183 | self.emit(f"{old} = OpPhi %uint {res_do} {done_lbl} {self.cu(0)} {pre_label}") | 3395 | self.emit(f"{old} = OpPhi %uint {res_do} {done_lbl} {self.cu(0)} {pre_label}") |
| @@ -3228,13 +3440,14 @@ class Gen: | |||
| 3228 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") | 3440 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") |
| 3229 | self.emit(f"{lbl_do} = OpLabel") | 3441 | self.emit(f"{lbl_do} = OpLabel") |
| 3230 | ptr = self.tmp() | 3442 | ptr = self.tmp() |
| 3231 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") | 3443 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'rmw', 8)}") |
| 3232 | res = [] | 3444 | res = [] |
| 3233 | for w in range(2): | 3445 | for w in range(2): |
| 3234 | p, r = self.tmp(), self.tmp() | 3446 | p, r = self.tmp(), self.tmp() |
| 3235 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") | 3447 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") |
| 3236 | self.emit(f"{r} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") | 3448 | self.emit(f"{r} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") |
| 3237 | res.append(r) | 3449 | res.append(r) |
| 3450 | res = [self.guard_zero(r) for r in res] | ||
| 3238 | self.emit(f"OpBranch {lbl_end}") | 3451 | self.emit(f"OpBranch {lbl_end}") |
| 3239 | self.emit(f"{lbl_end} = OpLabel") | 3452 | self.emit(f"{lbl_end} = OpLabel") |
| 3240 | olds = [] | 3453 | olds = [] |
| @@ -3628,7 +3841,7 @@ class Gen: | |||
| 3628 | self.emit(f"OpSelectionMerge {lbl_end} None") | 3841 | self.emit(f"OpSelectionMerge {lbl_end} None") |
| 3629 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") | 3842 | self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") |
| 3630 | self.emit(f"{lbl_do} = OpLabel") | 3843 | self.emit(f"{lbl_do} = OpLabel") |
| 3631 | ptr, host = self.tmp(), self.host_addr(aligned) | 3844 | ptr, host = self.tmp(), self.host_addr(aligned, "load", lambda: self.guard_delta(need, step)) |
| 3632 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") | 3845 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") |
| 3633 | loaded = [] | 3846 | loaded = [] |
| 3634 | for i in range(5): | 3847 | for i in range(5): |
| @@ -3839,7 +4052,7 @@ class Gen: | |||
| 3839 | "global_load_sbyte_d16": (1, False, True, 0), "global_load_sbyte_d16_hi": (1, False, True, 1), | 4052 | "global_load_sbyte_d16": (1, False, True, 0), "global_load_sbyte_d16_hi": (1, False, True, 1), |
| 3840 | "global_load_short_d16": (2, False, False, 0), "global_load_short_d16_hi": (2, False, False, 1)} | 4053 | "global_load_short_d16": (2, False, False, 0), "global_load_short_d16_hi": (2, False, False, 1)} |
| 3841 | 4054 | ||
| 3842 | def global_byte_ptr(self, va): | 4055 | def global_byte_ptr(self, va, kind="load"): |
| 3843 | """(pointer to the dword holding byte `va`, bit offset of that byte in it) for a ulong Xbox VA.""" | 4056 | """(pointer to the dword holding byte `va`, bit offset of that byte in it) for a ulong Xbox VA.""" |
| 3844 | lo, b3, b64, al, arr, p, sh = (self.tmp() for _ in range(7)) | 4057 | lo, b3, b64, al, arr, p, sh = (self.tmp() for _ in range(7)) |
| 3845 | self.emit(f"{lo} = OpUConvert %uint {va}") | 4058 | self.emit(f"{lo} = OpUConvert %uint {va}") |
| @@ -3847,7 +4060,7 @@ class Gen: | |||
| 3847 | self.emit(f"{b64} = OpUConvert %ulong {b3}") | 4060 | self.emit(f"{b64} = OpUConvert %ulong {b3}") |
| 3848 | self.emit(f"{al} = OpISub %ulong {va} {b64}") | 4061 | self.emit(f"{al} = OpISub %ulong {va} {b64}") |
| 3849 | # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations (as buffer stores). | 4062 | # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations (as buffer stores). |
| 3850 | self.emit(f"{arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") | 4063 | self.emit(f"{arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al, kind)}") |
| 3851 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {arr} {self.cu(0)}") | 4064 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {arr} {self.cu(0)}") |
| 3852 | self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") | 4065 | self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") |
| 3853 | return p, sh | 4066 | return p, sh |
| @@ -3879,7 +4092,7 @@ class Gen: | |||
| 3879 | if k: | 4092 | if k: |
| 3880 | va = self.tmp() | 4093 | va = self.tmp() |
| 3881 | self.emit(f"{va} = OpIAdd %ulong {full} {self.cl(k)}") | 4094 | self.emit(f"{va} = OpIAdd %ulong {full} {self.cl(k)}") |
| 3882 | p, sh = self.global_byte_ptr(va) | 4095 | p, sh = self.global_byte_ptr(va, "store" if store else "load") |
| 3883 | if store: | 4096 | if store: |
| 3884 | byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) | 4097 | byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) |
| 3885 | self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") | 4098 | self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") |
| @@ -3948,7 +4161,8 @@ class Gen: | |||
| 3948 | self.emit(f"{b3} = OpBitwiseAnd %uint {lo32} {self.cu(3)}") | 4161 | self.emit(f"{b3} = OpBitwiseAnd %uint {lo32} {self.cu(3)}") |
| 3949 | self.emit(f"{b64} = OpUConvert %ulong {b3}") | 4162 | self.emit(f"{b64} = OpUConvert %ulong {b3}") |
| 3950 | self.emit(f"{al} = OpISub %ulong {full} {b64}") | 4163 | self.emit(f"{al} = OpISub %ulong {full} {b64}") |
| 3951 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") | 4164 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr " |
| 4165 | f"{self.host_addr(al, 'load', lambda: self.guard_delta(self.sub_dwords(bits // 8, b3), None))}") | ||
| 3952 | self.emit(f"{p0} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") | 4166 | self.emit(f"{p0} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") |
| 3953 | self.emit(f"{w} = OpLoad %uint {p0} Aligned 4") | 4167 | self.emit(f"{w} = OpLoad %uint {p0} Aligned 4") |
| 3954 | self.emit(f"{shb} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") | 4168 | self.emit(f"{shb} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") |
| @@ -3975,7 +4189,7 @@ class Gen: | |||
| 3975 | vals.append(v) | 4189 | vals.append(v) |
| 3976 | else: | 4190 | else: |
| 3977 | ptr = self.tmp() | 4191 | ptr = self.tmp() |
| 3978 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") | 4192 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'load', 4 * n)}") |
| 3979 | for i in range(n): | 4193 | for i in range(n): |
| 3980 | p, v = self.tmp(), self.tmp() | 4194 | p, v = self.tmp(), self.tmp() |
| 3981 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") | 4195 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") |
| @@ -3997,7 +4211,7 @@ class Gen: | |||
| 3997 | self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") | 4211 | self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") |
| 3998 | self.emit(f"{lbl_do} = OpLabel") | 4212 | self.emit(f"{lbl_do} = OpLabel") |
| 3999 | ptr = self.tmp() | 4213 | ptr = self.tmp() |
| 4000 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") | 4214 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'store', 4 * n)}") |
| 4001 | for i in range(n): | 4215 | for i in range(n): |
| 4002 | p = self.tmp() | 4216 | p = self.tmp() |
| 4003 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") | 4217 | self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") |
| @@ -4543,7 +4757,7 @@ class Gen: | |||
| 4543 | if words is not None and per is not None and len(words) > 1: | 4757 | if words is not None and per is not None and len(words) > 1: |
| 4544 | # modes 0 and 3: every dword is stored only if it ends inside (measured: a store that straddles the edge | 4758 | # modes 0 and 3: every dword is stored only if it ends inside (measured: a store that straddles the edge |
| 4545 | # writes the dwords before it); a store past the end of the buffer is a host-memory hazard otherwise | 4759 | # writes the dwords before it); a store past the end of the buffer is a host-memory hazard otherwise |
| 4546 | ptr, host = self.tmp(), self.host_addr(addr) | 4760 | ptr, host = self.tmp(), self.host_addr(addr, "store", lambda: self.guard_delta(len(words), step)) |
| 4547 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") | 4761 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") |
| 4548 | for i, w in enumerate(words): | 4762 | for i, w in enumerate(words): |
| 4549 | cond, lbl_do, lbl_end = self.tmp(), self.tmp() + "_do", self.tmp() + "_end" | 4763 | cond, lbl_do, lbl_end = self.tmp(), self.tmp() + "_do", self.tmp() + "_end" |
| @@ -4570,7 +4784,8 @@ class Gen: | |||
| 4570 | self.emit(f"OpSelectionMerge {lbl_end} None") | 4784 | self.emit(f"OpSelectionMerge {lbl_end} None") |
| 4571 | self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") | 4785 | self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") |
| 4572 | self.emit(f"{lbl_do} = OpLabel") | 4786 | self.emit(f"{lbl_do} = OpLabel") |
| 4573 | ptr, host = self.tmp(), self.host_addr(addr) | 4787 | ptr, host = self.tmp(), self.host_addr(addr, "store", lambda: self.guard_delta( |
| 4788 | len(words) if words is not None else self.store_element_dwords(plans[0], fixed_fmt), step)) | ||
| 4574 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") | 4789 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") |
| 4575 | if words is not None: | 4790 | if words is not None: |
| 4576 | for i, w in enumerate(words): | 4791 | for i, w in enumerate(words): |
| @@ -4660,7 +4875,7 @@ class Gen: | |||
| 4660 | self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") | 4875 | self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") |
| 4661 | # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. | 4876 | # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. |
| 4662 | dword_arr = self.tmp() | 4877 | dword_arr = self.tmp() |
| 4663 | self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") | 4878 | self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al, 'store')}") |
| 4664 | self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") | 4879 | self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") |
| 4665 | self.emit(f"{mk} = OpCopyObject %uint {self.cu((1 << (8 * size)) - 1)}") | 4880 | self.emit(f"{mk} = OpCopyObject %uint {self.cu((1 << (8 * size)) - 1)}") |
| 4666 | self.emit(f"{mks} = OpShiftLeftLogical %uint {mk} {sh24}") | 4881 | self.emit(f"{mks} = OpShiftLeftLogical %uint {mk} {sh24}") |
| @@ -4703,7 +4918,7 @@ class Gen: | |||
| 4703 | self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") | 4918 | self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") |
| 4704 | # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. | 4919 | # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. |
| 4705 | dword_arr = self.tmp() | 4920 | dword_arr = self.tmp() |
| 4706 | self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") | 4921 | self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al, 'store')}") |
| 4707 | self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") | 4922 | self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") |
| 4708 | self.emit(f"{one} = OpIEqual %bool {size} {self.cu(1)}") | 4923 | self.emit(f"{one} = OpIEqual %bool {size} {self.cu(1)}") |
| 4709 | self.emit(f"{mk} = OpSelect %uint {one} {self.cu(0xFF)} {self.cu(0xFFFF)}") | 4924 | self.emit(f"{mk} = OpSelect %uint {one} {self.cu(0xFF)} {self.cu(0xFFFF)}") |
| @@ -7419,22 +7634,23 @@ class Gen: | |||
| 7419 | raise Unsupported("DPP operands") | 7634 | raise Unsupported("DPP operands") |
| 7420 | # A VOPC compare in DPP form (docs/design.md, "DPP on a VOPC compare"): src0 comes through the same lane | 7635 | # A VOPC compare in DPP form (docs/design.md, "DPP on a VOPC compare"): src0 comes through the same lane |
| 7421 | # selection and the result is a mask bit, not a VGPR. Only the forms where every lane writes its bit are | 7636 | # selection and the result is a mask bit, not a VGPR. Only the forms where every lane writes its bit are |
| 7422 | # taken: what a lane that DPP leaves unwritten does to its VCC bit is not measured. | 7637 | # taken: what a lane that DPP leaves unwritten does to its VCC bit is measured on RDNA3 only (it gets 0), not |
| 7638 | # on RDNA2. v_cmpx writes EXEC instead and prints no destination, so its src0 is the first operand | ||
| 7639 | # (SHADER-VOPCX-DPP). | ||
| 7423 | compare = base_op(ins["op"]).startswith("v_cmp") | 7640 | compare = base_op(ins["op"]).startswith("v_cmp") |
| 7641 | first = 0 if base_op(ins["op"]).startswith("v_cmpx") else 1 | ||
| 7424 | if compare: | 7642 | if compare: |
| 7425 | if base_op(ins["op"]).startswith("v_cmpx"): | 7643 | if len(args) != first + 2: |
| 7426 | raise Unsupported("DPP on v_cmpx") | ||
| 7427 | if len(args) != 3: | ||
| 7428 | raise Unsupported("DPP compare operands") | 7644 | raise Unsupported("DPP compare operands") |
| 7429 | if row_mask != 0xF or bank_mask != 0xF or not (dpp8 is not None or bound): | 7645 | if row_mask != 0xF or bank_mask != 0xF or not (dpp8 is not None or bound): |
| 7430 | raise Unsupported("DPP compare with lanes that keep their mask bit") | 7646 | raise Unsupported("DPP compare with lanes DPP leaves unwritten") |
| 7431 | elif args[0].get("k") != "vgpr" or args[0].get("n", 1) != 1: | 7647 | elif args[0].get("k") != "vgpr" or args[0].get("n", 1) != 1: |
| 7432 | raise Unsupported("DPP destination") | 7648 | raise Unsupported("DPP destination") |
| 7433 | if args[1].get("n", 1) != 1: | 7649 | if args[first].get("n", 1) != 1: |
| 7434 | raise Unsupported("DPP 64-bit source") | 7650 | raise Unsupported("DPP 64-bit source") |
| 7435 | if args[1].get("sext"): | 7651 | if args[first].get("sext"): |
| 7436 | raise Unsupported("DPP sext") | 7652 | raise Unsupported("DPP sext") |
| 7437 | src = args[1] | 7653 | src = args[first] |
| 7438 | raw_src = dict(src) | 7654 | raw_src = dict(src) |
| 7439 | raw_src.pop("neg", None) | 7655 | raw_src.pop("neg", None) |
| 7440 | raw_src.pop("abs", None) | 7656 | raw_src.pop("abs", None) |
| @@ -7615,10 +7831,10 @@ class Gen: | |||
| 7615 | else: | 7831 | else: |
| 7616 | write = self.tmp() | 7832 | write = self.tmp() |
| 7617 | self.emit(f"{write} = OpLogicalAnd %bool {enabled} {src_ok}") | 7833 | self.emit(f"{write} = OpLogicalAnd %bool {enabled} {src_ok}") |
| 7618 | args[1] = {"k": "ssa", "v": src0} | 7834 | args[first] = {"k": "ssa", "v": src0} |
| 7619 | if compare: | 7835 | if compare: |
| 7620 | # Every lane is enabled and an invalid source reads 0 (checked above), so the compare's own EXEC guard | 7836 | # Every lane is enabled and an invalid source reads 0 (checked above), so the compare's own EXEC guard |
| 7621 | # is the only one: the mask write is the plain compare's. | 7837 | # is the only one: the mask write is the plain compare's (for v_cmpx, EXEC's). |
| 7622 | return self._insn({**ins, "args": args}) | 7838 | return self._insn({**ins, "args": args}) |
| 7623 | previous = self.dpp_guard | 7839 | previous = self.dpp_guard |
| 7624 | self.dpp_guard = write | 7840 | self.dpp_guard = write |
| @@ -12795,7 +13011,7 @@ class Gen: | |||
| 12795 | self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}") | 13011 | self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}") |
| 12796 | self.emit(f"{full} = OpIAdd %ulong {addr} {o64}") | 13012 | self.emit(f"{full} = OpIAdd %ulong {addr} {o64}") |
| 12797 | ptr = self.tmp() | 13013 | ptr = self.tmp() |
| 12798 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") | 13014 | self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'load', 4 * n)}") |
| 12799 | self.uses_psb = True | 13015 | self.uses_psb = True |
| 12800 | lim = None | 13016 | lim = None |
| 12801 | lim_val = None | 13017 | lim_val = None |
| @@ -15217,7 +15433,14 @@ class Gen: | |||
| 15217 | e(f"{off} = OpShiftLeftLogical %ulong {nm} {self.cl(3)}") | 15433 | e(f"{off} = OpShiftLeftLogical %ulong {nm} {self.cl(3)}") |
| 15218 | e(f"{addr} = OpIAdd %ulong {base} {off}") | 15434 | e(f"{addr} = OpIAdd %ulong {base} {off}") |
| 15219 | ptr = T() | 15435 | ptr = T() |
| 15220 | e(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") | 15436 | |
| 15437 | def node_delta(): | ||
| 15438 | """--address-guard: a box32 node (type 5) is read up to dword 27, the others up to dword 15.""" | ||
| 15439 | b32, d = T(), T() | ||
| 15440 | e(f"{b32} = OpIEqual %bool {ntype} {self.cu(5)}") | ||
| 15441 | e(f"{d} = OpSelect %ulong {b32} {self.cl(4 * 28 - 1)} {self.cl(4 * 16 - 1)}") | ||
| 15442 | return d | ||
| 15443 | e(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'load', node_delta)}") | ||
| 15221 | 15444 | ||
| 15222 | def ldw(i): | 15445 | def ldw(i): |
| 15223 | pp, v = T(), T() | 15446 | pp, v = T(), T() |
| @@ -16259,6 +16482,10 @@ def assemble(gen): | |||
| 16259 | types.append("%fn_desc_lookup = OpTypeFunction %uint " + " ".join(["%uint"] * 8)) | 16482 | types.append("%fn_desc_lookup = OpTypeFunction %uint " + " ".join(["%uint"] * 8)) |
| 16260 | if gen.tbuffer_norm_fns: | 16483 | if gen.tbuffer_norm_fns: |
| 16261 | types.append("%fn_tbuffer_norm = OpTypeFunction %uint %uint") | 16484 | types.append("%fn_tbuffer_norm = OpTypeFunction %uint %uint") |
| 16485 | if gen.guard_fn: | ||
| 16486 | # --address-guard: (heap_base, on, limit, table, offset, delta, sink) -> host address; no other function | ||
| 16487 | # type of the module has this signature. | ||
| 16488 | types.append("%fn_guard = OpTypeFunction %ulong %ulong %bool %ulong %ulong %ulong %ulong %ulong") | ||
| 16262 | if gen.fmt_fn or gen.fmt_enc_fn: | 16489 | if gen.fmt_fn or gen.fmt_enc_fn: |
| 16263 | types.append("%v4uint_fmt = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 | 16490 | types.append("%v4uint_fmt = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 |
| 16264 | if gen.fmt_fn: | 16491 | if gen.fmt_fn: |
| @@ -16562,6 +16789,8 @@ def assemble(gen): | |||
| 16562 | gen.consts.setdefault(1, "%c1") | 16789 | gen.consts.setdefault(1, "%c1") |
| 16563 | gen.consts.setdefault(2, "%c2") | 16790 | gen.consts.setdefault(2, "%c2") |
| 16564 | fn += [pc_tail_chain("%ud_base_lo_p", 1, gen.cu), pc_tail_chain("%ud_base_hi_p", 2, gen.cu)] + HEAP_BASE_ENTRY | 16791 | fn += [pc_tail_chain("%ud_base_lo_p", 1, gen.cu), pc_tail_chain("%ud_base_hi_p", 2, gen.cu)] + HEAP_BASE_ENTRY |
| 16792 | if gen.uses_guard: | ||
| 16793 | fn += guard_entry(gen.cl, gen.cu) | ||
| 16565 | if gen.uses_codebase: | 16794 | if gen.uses_codebase: |
| 16566 | fn += [pc_tail_chain("%ud_code_lo_p", 3, gen.cu), pc_tail_chain("%ud_code_hi_p", 4, gen.cu)] | 16795 | fn += [pc_tail_chain("%ud_code_lo_p", 3, gen.cu), pc_tail_chain("%ud_code_hi_p", 4, gen.cu)] |
| 16567 | # A mesh shader reads its root arguments from the graphics window (user_data_dword, GRAPHICS_ROOT_DWORD). | 16796 | # A mesh shader reads its root arguments from the graphics window (user_data_dword, GRAPHICS_ROOT_DWORD). |
| @@ -16687,7 +16916,7 @@ def assemble(gen): | |||
| 16687 | fn.append(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {gen.cu(r)}") | 16916 | fn.append(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {gen.cu(r)}") |
| 16688 | # Spill pointers last: a spilled value's type may be declared anywhere above. | 16917 | # Spill pointers last: a spilled value's type may be declared anywhere above. |
| 16689 | types += [f"{ptr} = OpTypePointer Function {t}" for t, ptr in gen.x_ptr_types.items()] | 16918 | types += [f"{ptr} = OpTypePointer Function {t}" for t, ptr in gen.x_ptr_types.items()] |
| 16690 | helpers = (gen.desc_fn or []) + (gen.fmt_fn or []) + (gen.fmt_enc_fn or []) | 16919 | helpers = (gen.desc_fn or []) + (gen.fmt_fn or []) + (gen.fmt_enc_fn or []) + (gen.guard_fn or []) |
| 16691 | for function in gen.tbuffer_norm_fns.values(): | 16920 | for function in gen.tbuffer_norm_fns.values(): |
| 16692 | helpers.extend(function) | 16921 | helpers.extend(function) |
| 16693 | for function in gen.x_round_fns.values(): | 16922 | for function in gen.x_round_fns.values(): |
| @@ -17661,6 +17890,18 @@ def mix_literal(raw, printed, op): | |||
| 17661 | return stored | 17890 | return stored |
| 17662 | 17891 | ||
| 17663 | 17892 | ||
| 17893 | def restore_text_cut_mix_literal(ins, enc): | ||
| 17894 | """llvm-mc 21.1.8 can print a v_fma_mix* literal cut to its low 16 bits in the text while its printed encoding | ||
| 17895 | holds all 32 (the printed-encoding check then passes, and the text alone reads the high half as +0.0): take the | ||
| 17896 | literal from the printed encoding. Measured on 1.0.2.1: 47,910 such instructions in 1,218 pipeline-library | ||
| 17897 | programs and 6 in one FidelityFX FSPX program; none among the game's own shaders.""" | ||
| 17898 | if len(enc) != 12 or enc[3] != 0xCC or not base_op(ins["op"]).startswith("v_fma_mix"): | ||
| 17899 | return | ||
| 17900 | literal = int.from_bytes(enc[8:], "little") | ||
| 17901 | if literal >> 16 and any(a.get("k") == "imm" and a.get("v") == literal & 0xFFFF for a in ins["args"][1:4]): | ||
| 17902 | restore_mix_literal(ins, enc, literal) | ||
| 17903 | |||
| 17904 | |||
| 17664 | def restore_mix_literal(ins, raw, literal): | 17905 | def restore_mix_literal(ins, raw, literal): |
| 17665 | """Give every source of ``ins`` that the stored bytes encode as the literal (SRC field 0xff) its 32-bit value.""" | 17906 | """Give every source of ``ins`` that the stored bytes encode as the literal (SRC field 0xff) its 32-bit value.""" |
| 17666 | w1 = int.from_bytes(raw[4:8], "little") | 17907 | w1 = int.from_bytes(raw[4:8], "little") |
| @@ -17735,12 +17976,12 @@ def restore_mix_inline_literal(ins, raw, literal): | |||
| 17735 | 17976 | ||
| 17736 | def skipped_form(ins, blob, at): | 17977 | def skipped_form(ins, blob, at): |
| 17737 | """Whether rdna2_decode's instruction at blob offset ``at`` is one of the forms llvm-mc skips that | 17978 | """Whether rdna2_decode's instruction at blob offset ``at`` is one of the forms llvm-mc skips that |
| 17738 | restore_vcc_tuples takes from the blob: a tuple that reaches vcc (SGPRs 106 and 107), a VOPC f32 compare in DPP | 17979 | restore_vcc_tuples takes from the blob: a tuple that reaches vcc (SGPRs 106 and 107), a VOPC f32 compare (v_cmp or |
| 17739 | form (docs/design.md, "DPP on a VOPC compare"), or the measured v_dot4_i32_i8 with op_sel 2 / op_sel_hi 5 and no | 17980 | v_cmpx) in DPP form (docs/design.md, "DPP on a VOPC compare"), or the measured v_dot4_i32_i8 with op_sel 2 / op_sel_hi 5 and no |
| 17740 | clamp or neg, all reserved bits clear (tedin7, upstream PR #281; docs/fspx.md). shader_disasm.py prints the last | 17981 | clamp or neg, all reserved bits clear (tedin7, upstream PR #281; docs/fspx.md). shader_disasm.py prints the last |
| 17741 | two itself; this covers a listing made without that pass (#984).""" | 17982 | two itself; this covers a listing made without that pass (#984).""" |
| 17742 | op = ins["op"] | 17983 | op = ins["op"] |
| 17743 | if op.startswith("v_cmp_") and op.endswith("_f32_dpp"): | 17984 | if op.startswith(("v_cmp_", "v_cmpx_")) and op.endswith("_f32_dpp"): |
| 17744 | return True | 17985 | return True |
| 17745 | if op == "v_dot4_i32_i8" and int.from_bytes(blob[at:at + 4], "little") >> 8 == 0xCC1650 and blob[at + 7] >> 3 == 1: | 17986 | if op == "v_dot4_i32_i8" and int.from_bytes(blob[at:at + 4], "little") >> 8 == 0xCC1650 and blob[at + 7] >> 3 == 1: |
| 17746 | return True | 17987 | return True |
| @@ -18022,6 +18263,9 @@ def check_printed_encodings(path, info): | |||
| 18022 | Only a listing whose header names the code range it was disassembled from (shader_disasm.py), with a blob that | 18263 | Only a listing whose header names the code range it was disassembled from (shader_disasm.py), with a blob that |
| 18023 | holds that range, is checked: a hand-written listing, run_gpu_tests.py's "code 0x0..0x0 (synthetic)" and a | 18264 | holds that range, is checked: a hand-written listing, run_gpu_tests.py's "code 0x0..0x0 (synthetic)" and a |
| 18024 | test's header-only blob are not the bytes the text came from.""" | 18265 | test's header-only blob are not the bytes the text came from.""" |
| 18266 | for ins in info["insns"]: | ||
| 18267 | if ins.get("enc"): # needs only the printed encoding, so it runs before the blob checks below | ||
| 18268 | restore_text_cut_mix_literal(ins, bytes.fromhex(ins["enc"])) | ||
| 18025 | with open(path, encoding="utf-8", errors="replace") as f: | 18269 | with open(path, encoding="utf-8", errors="replace") as f: |
| 18026 | m = HDR.match(f.readline()) | 18270 | m = HDR.match(f.readline()) |
| 18027 | if not m or int(m.group(3), 16) <= int(m.group(2), 16): | 18271 | if not m or int(m.group(3), 16) <= int(m.group(2), 16): |
| @@ -18165,6 +18409,8 @@ def barriers_under_control_flow(text): | |||
| 18165 | 18409 | ||
| 18166 | 18410 | ||
| 18167 | def _translate(path): | 18411 | def _translate(path): |
| 18412 | global GUARD_MODULE_ID | ||
| 18413 | GUARD_MODULE_ID = fnv1a32(os.path.splitext(os.path.basename(path))[0]) | ||
| 18168 | info = parse_file(path) | 18414 | info = parse_file(path) |
| 18169 | stage = stage_of(info["name"], path) | 18415 | stage = stage_of(info["name"], path) |
| 18170 | if stage not in ("vs", "ps", "cs", "ms", "gs"): | 18416 | if stage not in ("vs", "ps", "cs", "ms", "gs"): |
| @@ -18188,6 +18434,7 @@ def _translate(path): | |||
| 18188 | exact = bool(bad) and len(bad) == info["invalid"] | 18434 | exact = bool(bad) and len(bad) == info["invalid"] |
| 18189 | for ins in insns: | 18435 | for ins in insns: |
| 18190 | enc = bytes.fromhex(ins["enc"]) | 18436 | enc = bytes.fromhex(ins["enc"]) |
| 18437 | restore_text_cut_mix_literal(ins, enc) | ||
| 18191 | op, operand_count = ins["op"], len(ins["args"]) | 18438 | op, operand_count = ins["op"], len(ins["args"]) |
| 18192 | if exact: | 18439 | if exact: |
| 18193 | while pos in bad and not same_encoding(blob[pos:pos + len(enc)], enc, op, operand_count): | 18440 | while pos in bad and not same_encoding(blob[pos:pos + len(enc)], enc, op, operand_count): |
| @@ -18885,11 +19132,19 @@ def translate(path): | |||
| 18885 | 19132 | ||
| 18886 | A workgroup barrier has to be reached by every invocation. NVIDIA waits for every thread, so one that | 19133 | A workgroup barrier has to be reached by every invocation. NVIDIA waits for every thread, so one that |
| 18887 | an invocation never reaches stands the group until the driver resets the card (Xid 109, device lost). | 19134 | an invocation never reaches stands the group until the driver resets the card (Xid 109, device lost). |
| 18888 | A program that hangs costs a whole run; re-translating it costs one more pass offline.""" | 19135 | A program that hangs costs a whole run; re-translating it costs one more pass offline. |
| 19136 | |||
| 19137 | Only a multi-wave plan falls back. A single-wave workgroup (`inline_all`, `x_lanes == 64`) is one wave: | ||
| 19138 | its barriers sit at the top level or under `%pc` guards, and `%pc` between blocks comes from scalar state | ||
| 19139 | and votes read back from `%x_buf`, so all invocations take the same path; lane-local `%pc` exists only in | ||
| 19140 | `emit_folded_region`'s `if (%active)` bodies, which emit no exchange and no barrier. The round loop is | ||
| 19141 | also what drives RADV/ACO's spiller to tens of GB and the program 10-100 times slower (docs/design.md, | ||
| 19142 | "Wave64 emulation: single-wave barrier fallback").""" | ||
| 18889 | global WAVE64_PLAN | 19143 | global WAVE64_PLAN |
| 18890 | asm = _translate(path) | 19144 | asm = _translate(path) |
| 18891 | gen = _translate.last_gen | 19145 | gen = _translate.last_gen |
| 18892 | if (gen is not None and getattr(gen, "emulate_plan", None) is not None | 19146 | plan = getattr(gen, "emulate_plan", None) if gen is not None else None |
| 19147 | if (plan is not None and plan.get("mode") != "inline_all" | ||
| 18893 | and barriers_under_control_flow(asm)): | 19148 | and barriers_under_control_flow(asm)): |
| 18894 | WAVE64_PLAN = False | 19149 | WAVE64_PLAN = False |
| 18895 | try: | 19150 | try: |
| @@ -19461,6 +19716,8 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): | |||
| 19461 | lay["params"] = {str(k): v for k, v in lay["params"].items()} | 19716 | lay["params"] = {str(k): v for k, v in lay["params"].items()} |
| 19462 | m["mesh_compute"] = lay | 19717 | m["mesh_compute"] = lay |
| 19463 | m["push_constant_bytes"] = lay["push_constant_bytes"] | 19718 | m["push_constant_bytes"] = lay["push_constant_bytes"] |
| 19719 | if g.uses_guard: | ||
| 19720 | m["address_guard"] = True # --address-guard: its accesses read the runtime's guard header | ||
| 19464 | if PC_TAIL_UBO: | 19721 | if PC_TAIL_UBO: |
| 19465 | # --pc-tail-ubo: s0..s31 alone in push constants; the tail, if the shader reads it, in a uniform block. | 19722 | # --pc-tail-ubo: s0..s31 alone in push constants; the tail, if the shader reads it, in a uniform block. |
| 19466 | m["push_constant_bytes"] = 4 * USER_SGPRS | 19723 | m["push_constant_bytes"] = 4 * USER_SGPRS |
| @@ -19880,6 +20137,10 @@ def main(): | |||
| 19880 | help="keep only s0..s31 (128 bytes) in push constants and read the heap base, code base and " | 20137 | help="keep only s0..s31 (128 bytes) in push constants and read the heap base, code base and " |
| 19881 | "--mesh-compute output address from a uniform block at set 1, binding 0 (metadata: pc_tail), " | 20138 | "--mesh-compute output address from a uniform block at set 1, binding 0 (metadata: pc_tail), " |
| 19882 | "for devices whose maxPushConstantsSize is below 144") | 20139 | "for devices whose maxPushConstantsSize is below 144") |
| 20140 | ap.add_argument("--address-guard", action="store_true", | ||
| 20141 | help="check every heap_base + VA access against the runtime's page table of backed memory " | ||
| 20142 | "(LEONIDA_ADDRESS_GUARD=1): an unbacked one reads 0 and drops its store instead of reaching " | ||
| 20143 | "a wild GPU address (metadata: address_guard; docs/d3d12_vulkan.md, Address guard)") | ||
| 19883 | ap.add_argument("--descriptor-hash", choices=DESCRIPTOR_HASHES, default="fnv1a", | 20144 | ap.add_argument("--descriptor-hash", choices=DESCRIPTOR_HASHES, default="fnv1a", |
| 19884 | help="bindless descriptor table hash shared with the runtime (default: fnv1a)") | 20145 | help="bindless descriptor table hash shared with the runtime (default: fnv1a)") |
| 19885 | ap.add_argument("--descriptor-table", choices=DESCRIPTOR_TABLES, default="tagged", | 20146 | ap.add_argument("--descriptor-table", choices=DESCRIPTOR_TABLES, default="tagged", |
| @@ -19919,8 +20180,9 @@ def main(): | |||
| 19919 | LOOP_LIMIT = a.loop_limit | 20180 | LOOP_LIMIT = a.loop_limit |
| 19920 | MAX_STRUCTURED_DEPTH = a.max_structured_depth | 20181 | MAX_STRUCTURED_DEPTH = a.max_structured_depth |
| 19921 | global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV | 20182 | global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV |
| 19922 | global PC_TAIL_UBO | 20183 | global PC_TAIL_UBO, ADDRESS_GUARD |
| 19923 | PC_TAIL_UBO = a.pc_tail_ubo | 20184 | PC_TAIL_UBO = a.pc_tail_ubo |
| 20185 | ADDRESS_GUARD = a.address_guard | ||
| 19924 | global FMA_EXACT | 20186 | global FMA_EXACT |
| 19925 | FMA_KHR = a.fma == "khr" | 20187 | FMA_KHR = a.fma == "khr" |
| 19926 | SHADER_CLOCK = a.shader_clock == "khr" | 20188 | SHADER_CLOCK = a.shader_clock == "khr" |
diff --git a/tools/tex_export.py b/tools/tex_export.py index e0630805d..70eb0c3ef 100644 --- a/tools/tex_export.py +++ b/tools/tex_export.py | |||
| @@ -12,9 +12,11 @@ For each texture: | |||
| 12 | otherwise on raw element bytes) | 12 | otherwise on raw element bytes) |
| 13 | - writes <out>/<archive>/<cpu blob>_<q index>_<WxH>_<format>.dds and records the choice in export_log.json, | 13 | - writes <out>/<archive>/<cpu blob>_<q index>_<WxH>_<format>.dds and records the choice in export_log.json, |
| 14 | with "heuristic": true whenever two distinct placements fitted (the pick is a score, not a verified layout) | 14 | with "heuristic": true whenever two distinct placements fitted (the pick is a score, not a verified layout) |
| 15 | - with --png, also writes the same path with .png for every texture tools/dds_png.py can decode (BC1-BC5, BC7 | 15 | - with --png, also writes the same path with .png for every texture tools/dds_png.py can decode (BC1-BC5, BC7, |
| 16 | and 8-bit RGBA/BGRA, R10G10B10A2_UNORM or R11G11B10_FLOAT, with no sRGB transfer; BC5 blue is a reconstructed normal Z; | 16 | 8-bit RGBA/BGRA, R8 and R8G8 UNORM/SNORM/UINT/SINT, R16_UNORM, R10G10B10A2_UNORM/UINT, R11G11B10_FLOAT, |
| 17 | R16_FLOAT, R32_FLOAT and R16G16B16A16_FLOAT clamped to [0, 1], NaN as 0). | 17 | R9G9B9E5_SHAREDEXP and R16G16B16A16_UNORM/SNORM, with no sRGB transfer; BC5 blue is a reconstructed normal Z; |
| 18 | SNORM maps [-1, 1] to [0, 255], SINT is offset by 128; R9G9B9E5_SHAREDEXP, R16_FLOAT, R32_FLOAT and | ||
| 19 | R16G16B16A16_FLOAT clamp to [0, 1], with NaN as 0 for formats that can encode it). | ||
| 18 | The rest (including BC6H) keep their | 20 | The rest (including BC6H) keep their |
| 19 | DDS only and are counted as "png unsupported". A PNG that fails to decode or write is counted as | 21 | DDS only and are counted as "png unsupported". A PNG that fails to decode or write is counted as |
| 20 | "png error:<Type>" and its DDS stays; neither changes the exit code | 22 | "png error:<Type>" and its DDS stays; neither changes the exit code |
diff --git a/tools/tex_headers.py b/tools/tex_headers.py index 780a2bbb8..4479822a2 100644 --- a/tools/tex_headers.py +++ b/tools/tex_headers.py | |||
| @@ -40,6 +40,7 @@ DXGI = { | |||
| 40 | 49: "R8G8_UNORM", 50: "R8G8_UINT", 51: "R8G8_SNORM", 52: "R8G8_SINT", | 40 | 49: "R8G8_UNORM", 50: "R8G8_UINT", 51: "R8G8_SNORM", 52: "R8G8_SINT", |
| 41 | 54: "R16_FLOAT", 56: "R16_UNORM", 57: "R16_UINT", 58: "R16_SNORM", 59: "R16_SINT", | 41 | 54: "R16_FLOAT", 56: "R16_UNORM", 57: "R16_UINT", 58: "R16_SNORM", 59: "R16_SINT", |
| 42 | 61: "R8_UNORM", 62: "R8_UINT", 63: "R8_SNORM", 64: "R8_SINT", | 42 | 61: "R8_UNORM", 62: "R8_UINT", 63: "R8_SNORM", 64: "R8_SINT", |
| 43 | 67: "R9G9B9E5_SHAREDEXP", | ||
| 43 | 71: "BC1_UNORM", 72: "BC1_UNORM_SRGB", | 44 | 71: "BC1_UNORM", 72: "BC1_UNORM_SRGB", |
| 44 | 74: "BC2_UNORM", 75: "BC2_UNORM_SRGB", | 45 | 74: "BC2_UNORM", 75: "BC2_UNORM_SRGB", |
| 45 | 77: "BC3_UNORM", 78: "BC3_UNORM_SRGB", | 46 | 77: "BC3_UNORM", 78: "BC3_UNORM_SRGB", |
| @@ -148,7 +149,7 @@ FMT_INFO = { | |||
| 148 | 16: (8, 1), 17: (8, 1), 18: (8, 1), | 149 | 16: (8, 1), 17: (8, 1), 18: (8, 1), |
| 149 | 24: (4, 1), 25: (4, 1), 26: (4, 1), 28: (4, 1), 29: (4, 1), 30: (4, 1), 31: (4, 1), 32: (4, 1), | 150 | 24: (4, 1), 25: (4, 1), 26: (4, 1), 28: (4, 1), 29: (4, 1), 30: (4, 1), 31: (4, 1), 32: (4, 1), |
| 150 | 34: (4, 1), 35: (4, 1), 36: (4, 1), 37: (4, 1), 38: (4, 1), 41: (4, 1), 42: (4, 1), 43: (4, 1), | 151 | 34: (4, 1), 35: (4, 1), 36: (4, 1), 37: (4, 1), 38: (4, 1), 41: (4, 1), 42: (4, 1), 43: (4, 1), |
| 151 | 87: (4, 1), 91: (4, 1), | 152 | 67: (4, 1), 87: (4, 1), 91: (4, 1), |
| 152 | 6: (12, 1), 7: (12, 1), 8: (12, 1), | 153 | 6: (12, 1), 7: (12, 1), 8: (12, 1), |
| 153 | 10: (8, 1), 11: (8, 1), 12: (8, 1), 13: (8, 1), 14: (8, 1), | 154 | 10: (8, 1), 11: (8, 1), 12: (8, 1), 13: (8, 1), 14: (8, 1), |
| 154 | 2: (16, 1), 3: (16, 1), 4: (16, 1), | 155 | 2: (16, 1), 3: (16, 1), 4: (16, 1), |
diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index 1ff464fd1..f8a50e0eb 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py | |||
| @@ -1741,13 +1741,6 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb | |||
| 1741 | if any(sb_has_endpgm[u] for u in it_blocks): | 1741 | if any(sb_has_endpgm[u] for u in it_blocks): |
| 1742 | saw_endpgm = True | 1742 | saw_endpgm = True |
| 1743 | 1743 | ||
| 1744 | # Multi-wave soundness guard: any `s_barrier` inside a non-top-level guard/loop must stay in global x_scheduler | ||
| 1745 | # so waves on different paths can meet at different s_barrier sites (cs_barrier_divergent). | ||
| 1746 | for it in flat_top: | ||
| 1747 | if it[0] != "block": | ||
| 1748 | if any(sb_has_sbarrier[u] for u in _blocks_in_tree(it)): | ||
| 1749 | return None | ||
| 1750 | |||
| 1751 | def check_sync_free(it): | 1744 | def check_sync_free(it): |
| 1752 | sub_blocks = _blocks_in_tree(it) | 1745 | sub_blocks = _blocks_in_tree(it) |
| 1753 | has_loop = _tree_has_loop([it]) | 1746 | has_loop = _tree_has_loop([it]) |
| @@ -1793,7 +1786,10 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb | |||
| 1793 | cur_dirty = sb_gen_dirty[b] if sb_clears_dirty[b] else (cur_dirty | sb_gen_dirty[b]) | 1786 | cur_dirty = sb_gen_dirty[b] if sb_clears_dirty[b] else (cur_dirty | sb_gen_dirty[b]) |
| 1794 | steps.append(("inline_block", b)) | 1787 | steps.append(("inline_block", b)) |
| 1795 | continue | 1788 | continue |
| 1796 | if has_end: | 1789 | # An `s_barrier` under a guard or in a loop: waves on different paths meet at different sites |
| 1790 | # (cs_barrier_divergent), which only the round scheduler models. Every wave enters the tail in the same | ||
| 1791 | # round, and what ran before it has no `s_barrier` that is not reached by the whole workgroup. | ||
| 1792 | if has_end or (it[0] != "block" and any(sb_has_sbarrier[u] for u in it_blocks)): | ||
| 1797 | # Early s_endpgm inside a wave-divergent guard/loop (or non-final block): hand remaining tail to x_scheduler. | 1793 | # Early s_endpgm inside a wave-divergent guard/loop (or non-final block): hand remaining tail to x_scheduler. |
| 1798 | rem = set() | 1794 | rem = set() |
| 1799 | for rem_it in flat_top[idx_it:]: | 1795 | for rem_it in flat_top[idx_it:]: |
diff --git a/tools/wave64_halves.py b/tools/wave64_halves.py index 54db61acd..9c0df3bf6 100644 --- a/tools/wave64_halves.py +++ b/tools/wave64_halves.py | |||
| @@ -921,6 +921,10 @@ class Analysis: | |||
| 921 | put_t |= T.get(r, 0) | (CTRL if (id(ins), r) in self.stale else 0) | 921 | put_t |= T.get(r, 0) | (CTRL if (id(ins), r) in self.stale else 0) |
| 922 | for d in dests: | 922 | for d in dests: |
| 923 | put(d, put_t) | 923 | put(d, put_t) |
| 924 | # v_cmpx in DPP form (SHADER-VOPCX-DPP) writes EXEC and prints no destination: it is an EXEC write like | ||
| 925 | # any v_cmpx, and never a uniform vote, as a lane whose DPP source is invalid compares 0. | ||
| 926 | if "exec" in defs: | ||
| 927 | self.exec_write(n, i, ins, op, a, dests, srcs, st, ev, violation, idiom, put_t, vote=False) | ||
| 924 | return | 928 | return |
| 925 | 929 | ||
| 926 | # --- exec writes and mask producers | 930 | # --- exec writes and mask producers |
| @@ -1261,7 +1265,7 @@ class Analysis: | |||
| 1261 | tag, tj = ("elect", g[1]), ELECT | 1265 | tag, tj = ("elect", g[1]), ELECT |
| 1262 | return tag, tj | 1266 | return tag, tj |
| 1263 | 1267 | ||
| 1264 | def exec_write(self, n, i, ins, op, a, dests, srcs, st, ev, violation, idiom, t_src): | 1268 | def exec_write(self, n, i, ins, op, a, dests, srcs, st, ev, violation, idiom, t_src, vote=True): |
| 1265 | T = st["t"] | 1269 | T = st["t"] |
| 1266 | site = ("n", n, i) | 1270 | site = ("n", n, i) |
| 1267 | old = st["x"] | 1271 | old = st["x"] |
| @@ -1292,7 +1296,9 @@ class Analysis: | |||
| 1292 | # s_mov / s_and / s_or / s_xor / s_andn2 ... with EXEC as the destination, or v_cmpx | 1296 | # s_mov / s_and / s_or / s_xor / s_andn2 ... with EXEC as the destination, or v_cmpx |
| 1293 | srcregs = [x for x in srcs if _regs(x) != ["exec"]] | 1297 | srcregs = [x for x in srcs if _regs(x) != ["exec"]] |
| 1294 | x0 = srcregs[0] if srcregs else None | 1298 | x0 = srcregs[0] if srcregs else None |
| 1295 | if op.startswith("v_cmpx"): | 1299 | if op.startswith("v_cmpx") and not vote: |
| 1300 | mg, mt = None, t_src | ||
| 1301 | elif op.startswith("v_cmpx"): | ||
| 1296 | mg, mt = self.cmp_tag(st, ins, "v_cmp" + op[len("v_cmpx"):], srcs, t_src, idiom) | 1302 | mg, mt = self.cmp_tag(st, ins, "v_cmp" + op[len("v_cmpx"):], srcs, t_src, idiom) |
| 1297 | if mg: | 1303 | if mg: |
| 1298 | mt = 0 | 1304 | mt = 0 |