diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b9821abfe..c1e7556d4 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -198,6 +198,7 @@ jobs: tests/startup_gfx2hlsl_capture_check.py \ tests/startup_translator_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ + tests/startup_gfx2hlsl_refusals_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 9905da4d7..1bbf850e3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -154,6 +154,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_capture_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_refusals_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py ./out/pe-env/bin/python -B tests/startup_flat_param_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 4335ca42b..e571fbf66 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2388,6 +2388,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: the SMEM offset 'off' is the literal 0; m0 and other operands keep their handling (#1674). add_test(NAME startup_gfx2hlsl_smem_offset COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_smem_offset_check.py") + # Startup shader translator: read-only census of every refusal site (--refusals). + add_test(NAME startup_gfx2hlsl_refusals COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_refusals_check.py") add_test(NAME startup_triage_run COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_triage_run_check.py") add_test(NAME startup_run_ps1 COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 1823ce2de..5d950574f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -11472,6 +11472,28 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mad_' -V python -B tests/startup_gfx2hlsl_mad_check.py binary llvm-mc-15 ``` +## Startup translator: refusal census + +The startup shader translator normally stops a pipeline at its first refusal. Fixing that refusal can expose gaps that were previously hidden, as documented in the [issue #1723 census](https://github.com/R0Y00/Xbox2Windows/issues/1723). + +`python -B tools/startup/gfx2hlsl.py --refusals [--json]` surveys an existing cache directory, including requests that already have a `.txt` or `.fail`. The diagnostic writes nothing and translates in memory without invoking fxc. On older translator revisions, `--refusals DIR` is treated as `--pending DIR` and writes into that directory. + +The text and JSON reports show two views. + +- **Per request key** includes RTV variants. Each reason and scope row counts requests containing that refusal, requests where it was the first site reached, and requests where it was the only distinct reason. Repeating the same reason at several sites still counts toward Only. The refusal sites per request histogram counts each site reached. **No refusal recorded (not compiled)** counts requests with zero recorded sites. +- **Per code pair** groups base requests by a hash of their `.a` and `.b` bytes and excludes RTV variants. For each reason and scope, the report counts pairs where it was reached under every observed root signature and pairs where it was reached under some but fewer than all observed roots. Multiple requests for the same pair and root contribute their combined reasons. + +The Scope column distinguishes `decode`, vertex lowering (`vs`), pixel lowering (`ps`), and `pipeline`. A refusal for an instruction of known length skips that instruction and continues. An undecodable word, or a refusal during request loading, pipeline construction, or output generation ends the pipeline, with the same reason the default path would write to `.fail`. For a pipeline-scope Only row, the single observed reason is a lower bound on what may be present. Counts after the first refusal are approximate because skipped instructions leave later state unmodelled. + +An unexpected handler exception after an earlier refusal or crash is reported as `internal error in : `, a possible follow-on effect. With no earlier refusal it is reported as `translator crash in : `, which identifies a translator bug. The reports contain no request keys, raw disassembly, register numbers or immediates. Cause numbers such as a format ID, operand width, or shader model remain visible. + +The `startup_gfx2hlsl_refusals` check covers skip and resume, a control that stops at the first refusal, file and decoding failures, count semantics, both flag orders and the `--refusals=DIR` spelling, and unchanged cache files in diagnostic mode. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_refusals$' -V +python -B tools/startup/gfx2hlsl.py --refusals out/startup/shader_cache +``` + ## Startup translator: SMEM offset operands `tools/startup/gfx2hlsl.py` accepts these offset operands for the scalar memory loads ([issue #1674](https://github.com/R0Y00/Xbox2Windows/issues/1674)): diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a24079297..6e50bf6e6 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -640,6 +640,7 @@ requests, run `python tools/startup/gfx2hlsl.py --pending `, then start the build again. The new key keeps the former bytecode and manifest together under their original name. A 16-dword table load can contain two independent image descriptors at offsets 0 and 32 from the load address. +For a read-only census of cached shader refusals, use `python -B tools/startup/gfx2hlsl.py --refusals [--json]` with a translator that supports the flag. Earlier versions treat it as `--pending` and write into the directory. See [Startup translator refusal census](experiments.md#startup-translator-refusal-census). ## Input script diff --git a/tests/startup_gfx2hlsl_refusals_check.py b/tests/startup_gfx2hlsl_refusals_check.py new file mode 100644 index 000000000..20963be18 --- /dev/null +++ b/tests/startup_gfx2hlsl_refusals_check.py @@ -0,0 +1,318 @@ +"""Check the startup translator's diagnostic refusal census without game data or fxc.""" +import contextlib +import io +import json +import os +from pathlib import Path +import struct +import sys +import tempfile +from unittest.mock import patch + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] +FIRST, SECOND = 'unsupported_first', 'unsupported_second' +ENCODING = 'synthetic encoding refusal' +END = 0xbf810000 + + +def check(label, condition): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + + +def refusal(call): + try: + call() + except G.Unsupported as reason: + return str(reason) + return None + + +def stage(refusals=None): + s = G.Stage.__new__(G.Stage) + s.kind, s.refusals = 'ps', refusals + s.sym, s.lines, s.used_v = {}, [], set() + s.exec_known = True + s.ins = [(0, 4, FIRST, FIRST), + (4, 4, 'v_mov_b32', 'v_mov_b32 v0, 0'), + (8, 4, SECOND, SECOND)] + return s + + +def check_stage(): + check('normal stage reports the first refusal', refusal(stage().translate) == FIRST) + found = [] + s = stage(found) + s.translate() + check('diagnostic stage records both refusals in order', found == [(FIRST, 'ps'), (SECOND, 'ps')]) + check('supported instruction still emits HLSL', s.lines == ['v0 = 0x00000000u;']) + + def broken(self, ops, mods): + raise TypeError('opaque handler detail') + + with patch.object(G.Stage, 'op_v_census_probe', broken, create=True): + probe = (0, 4, 'v_census_probe', 'v_census_probe v0, v1') + s = stage() + s.ins = [probe] + try: + s.translate() + check('normal stage re-raises a handler error', False) + except TypeError: + check('normal stage re-raises a handler error', True) + for preceding, label in (([], 'translator crash'), ([(FIRST, 'decode')], 'internal error')): + found = list(preceding) + s = stage(found) + s.ins = [probe, s.ins[-1]] + s.translate() + check('handler error classified as ' + label, + found == preceding + [(label + ' in v_census_probe: TypeError', 'ps'), (SECOND, 'ps')]) + + +def check_decode(): + code = struct.pack('<2I', 0, END) + with patch.object(G.D, 'decode_instruction', decode_instruction), patch.object( + G, 'check_encoding', side_effect=[G.Unsupported(ENCODING), 's_endpgm']): + found = [] + ins = G.decode(code, found) + check('encoding refusal carries decode scope', found == [(ENCODING, 'decode')]) + check('decode resumes at the next instruction', [row[:3] for row in ins] == [(4, 4, 's_endpgm')]) + + # GFX10 VOP3 v_cndmask: inline 1 (129), v1 (257), vcc (106), NEG on src0. + word1 = 129 | (257 << 9) | (106 << 18) | (1 << 29) + code = struct.pack('<3I', 0xd5010000, word1, END) + found = [] + ins = G.decode(code, found) + check('upstream NEG lowering is retained', not found and '0x80000001' in ins[0][3]) + + +def decode_instruction(blob, offset): + instructions = { + 0: ('s_nop', 's_nop 0'), + 1: ('exp', 'exp pos0 off, off, off, off done'), + 2: (FIRST, FIRST), + 3: ('v_mov_b32', 'v_mov_b32 v0, 0'), + 4: (SECOND, SECOND), + END: ('s_endpgm', 's_endpgm'), + } + name, asm = instructions[struct.unpack_from('> (9 * i)) & 0x1ff + if not (128 <= source <= 208 or 240 <= source <= 248 or source == 255): + continue + if word0 & (1 << (8 + i)): + raise Unsupported('v_cndmask_b32_e64 ABS on an immediate') + if not word1 & (1 << (29 + i)): + continue + if source <= 192: + bits = source - 128 + elif source <= 208: + bits = (192 - source) & 0xffffffff + elif source <= 248: + bits = CNDMASK_INLINE_FLOAT_BITS[source - 240] + else: + if n != 12 or off + n > len(code): + raise Unsupported('v_cndmask_b32_e64 missing literal dword') + bits, = struct.unpack_from('> (9 * i)) & 0x1ff - if not (128 <= source <= 208 or 240 <= source <= 248 or source == 255): - continue - if word0 & (1 << (8 + i)): - raise Unsupported('v_cndmask_b32_e64 ABS on an immediate') - if not word1 & (1 << (29 + i)): - continue - if source <= 192: - bits = source - 128 - elif source <= 208: - bits = (192 - source) & 0xffffffff - elif source <= 248: - bits = CNDMASK_INLINE_FLOAT_BITS[source - 240] - else: - if n != 12 or off + n > len(code): - raise Unsupported('v_cndmask_b32_e64 missing literal dword') - bits, = struct.unpack_from(' symbolic value self.used_s, self.used_v = set(), set() @@ -509,12 +524,24 @@ def translate(self): self.uniform_v = set() self.has_branches = bool(targets) start = 0 + refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ for off, n, name, asm in self.ins: if off in targets and off != start: self.blocks.append((start, self.lines, None)) self.lines, start = [], off self.pc = off - term = self.one(name, asm) + try: + term = self.one(name, asm) + except Unsupported as reason: + if refusals is None: + raise + refusals.append((str(reason), self.kind)) + continue + except Exception as error: + if refusals is None: + raise + refusals.append((handler_error(name, error, refusals), self.kind)) + continue if term: self.blocks.append((start, self.lines, term)) self.lines, start = [], off + n @@ -1712,7 +1739,8 @@ def parse_root(blob): class Pipeline: - def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None): + def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None, + refusals=None, decoded=None): self.root = parse_root(root_blob) self.vs_fetch = vs_fetch # stream_fetch(): the loads the vertex stage's entry call stands for self.packed_position_vgpr = None @@ -1734,8 +1762,13 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.notes = set() # shortcuts taken (written to the manifest as comments) self.modified = set() self.rect = self.ud(('rect',)) - self.vs = Stage(self, 'vs', vs_code) - self.ps = Stage(self, 'ps', ps_code) + if refusals is None: + self.vs = Stage(self, 'vs', vs_code) + self.ps = Stage(self, 'ps', ps_code) + else: + decoded = {} if decoded is None else decoded + self.vs = Stage(self, 'vs', vs_code, refusals=refusals, decoded=decoded.get('vs')) + self.ps = Stage(self, 'ps', ps_code, refusals=refusals, decoded=decoded.get('ps')) self.params = sorted(int(k[5:]) for k in self.vs.exports if k.startswith('param')) self.flat = sorted(a for a, how in self.ps.attrs.items() if 'flat' in how) missing = [a for a in self.ps.attrs if a not in self.params] @@ -1990,52 +2023,75 @@ def translate_to(out_dir, key, vs_code, ps_code, root_blob, check=True, rtv_form return 'ok' -def classify(blob): - text = ' '.join(x[3] for x in decode(strip_header(blob)) if x[2] == 'exp') +def classify_decoded(ins): + text = ' '.join(x[3] for x in ins if x[2] == 'exp') return 'vs' if 'pos' in text else 'ps' if 'mrt' in text or not text else 'other' # no export: a depth-only pixel shader -def translate_request(out_dir, key): - """Translate a base shader request or an RTV variant referencing its source blobs.""" +def classify(blob): + return classify_decoded(decode(strip_header(blob))) + + +def load_request(out_dir, key, refusals=None, pair_info=None): + """Read a base request or an RTV variant and classify the source stages.""" + decoded = {} + + def classify_stage(blob): + if refusals is None: + return classify(blob) + ins = decode(strip_header(blob), refusals) + kind = classify_decoded(ins) + decoded[kind] = ins + return kind + name = os.path.join(out_dir, 'req_%016x' % key) request = '' formats = () + base = key + if os.path.isfile(name + '.rtv'): + with open(name + '.rtv', encoding='ascii') as file: + request = file.read(256) + if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or fnv(request.encode('ascii')) != key: + raise Unsupported('invalid RTV variant request') + base, *formats = map(int, request.split()[1:]) + if base > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): + raise Unsupported('invalid RTV variant values') + name = os.path.join(out_dir, 'req_%016x' % base) + a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) + if pair_info is not None and not request: + import hashlib + pair_info.append((hashlib.sha256(struct.pack(' 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): - raise Unsupported('invalid RTV variant values') - name = os.path.join(out_dir, 'req_%016x' % base) - a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) - # A stream with an input layout publishes it as .ia (before .a) and hashes it into the key. - layout = open(name + '.ia', 'rb').read() if os.path.isfile(name + '.ia') else b'' - if request and pipeline_key(a, b, root, layout) != base: - raise Unsupported('RTV variant source key mismatch') - fetch = None - if a.startswith(b'DXBC') or b.startswith(b'DXBC'): - # Slot 86 records complete containers in canonical (VS, PS) order. - # Keep the container bytes in the cache key; translate only the bounded native code. - import zlib - from pixel_aot import container_code - from resource_inventory import parts - try: - container = a - a, b = (container_code(parts(blob)[b'DXIL'], stage=stage) - for blob, stage in ((a, 1), (b, 0))) - if starts_with_fetch_call(a): - fetch = stream_fetch(container, layout.decode('ascii') if layout else None) - except (KeyError, ValueError, IndexError, struct.error, zlib.error) as error: - raise Unsupported('invalid stream shader: %s' % error) from error - if classify(a) != 'vs' or classify(b) != 'ps': - raise Unsupported('stream stage and shader export disagree') - kinds = {'vs': a, 'ps': b} - else: - kinds = {classify(a): a, classify(b): b} + kinds, root, formats, request, fetch, _ = load_request(out_dir, key) except (Unsupported, OSError, UnicodeError) as reason: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason @@ -2045,7 +2101,154 @@ def translate_request(out_dir, key): return translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, vs_fetch=fetch) +REFUSALS_CAVEAT = ('Counts after the first refusal are approximate. Skipped instructions leave later state ' + 'unmodelled and can cause follow-on errors. A pipeline-scope refusal ends the pipeline, ' + 'so Only counts at pipeline scope reflect a lower bound on the reasons reached.') + + +def request_keys(out_dir): + for name in sorted(os.listdir(out_dir)): + match = re.fullmatch(r'req_([0-9a-f]{16})\.(?:a|rtv)', name) + if match: + yield int(match.group(1), 16) + + +def normalize_refusal(reason): + # Opaque decoder/container details can contain input bytes or disassembly. + for label in ('undecodable word', 'invalid stream shader', 'unverified vertex fetch record', + 'unreadable shader request', 'invalid binary shader request'): + if reason.startswith(label): + return label + reason = re.sub(r'\b([sv])\[\d+(?::(\d+))?\]', lambda m: m[1] + ('[N:N]' if m[2] else '[N]'), reason) + reason = re.sub(r'\b([sv])\d+\b', r'\1N', reason) + reason = re.sub(r'\b(pos|param|mrt)\d+\b', r'\1N', reason) + reason = re.sub(r'\blabel_[0-9a-f]+\b', 'label_N', reason, flags=re.IGNORECASE) + reason = re.sub(r'\bword_0x[0-9a-f]+\b', 'word_N', reason, flags=re.IGNORECASE) + # Preserve cause numbers. Redact hex operands and offsets, and decimal operands + # in instruction operand lists, symbolic values, and named operand fields. + number = r'[+-]?(?:0x[0-9a-f]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)' + reason = re.sub(r'(?